<template>
  <!-- ________________________________________融资企业用________________________________________________ -->
  <div class="app-container zap-main">
    <el-row class="zap-table-search">
      <el-row style="padding-top: 16px;">
        <right-toolbar
          class="zap-right-toolbar"
          :showSearch.sync="showSearch"
          @queryTable="getList"
        >收起</right-toolbar>
        <span class="zap-table-search__title">所选条件:</span>
        <div style="float: right;margin-right:1%">
          <el-button type="cyan" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery" style="float: ;">重置</el-button>
          <column-setting
            class="zap-column-setting"
            :checkList="checkList"
            :tableList="tableList"
            :selfDom="selfDom"
            :tableId="tableId"
          ></column-setting>
        </div>
        <hr style="margin-top: 16px;" />
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="auto"
        >
          <!-- <el-form-item label="融资编号" prop="zfrNumber" size="large">
            <el-input
              maxlength="30"
              v-model="queryParams.zfrNumber"
              placeholder="请输入融资编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="开立企业" prop="coreScyName" size="large">
            <el-input
              maxlength="30"
              v-model="queryParams.coreScyName"
              placeholder="请输入开立企业名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item> -->
          <el-form-item label="类型" prop="zciQuery" size="large">
            <el-select v-model="queryParams.zciQuery" clearable>
              <el-option
              v-for="dict in queryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
              v-if="dict.dictValue == '02' && companyType  != '02'"
              />
              <el-option
              v-for="dict in queryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
              v-if="dict.dictValue != '02'"
              />
            </el-select>
        </el-form-item>
        <el-form-item prop="zciValue" v-if="this.queryParams.zciQuery"  size="large">
          <el-input v-model="queryParams.zciValue" placeholder="请输入关键字模糊查询" clearable maxlength="25"/>
        </el-form-item>
          <el-form-item label="融资状态" prop="zfrStatus" size="large">
            <el-select v-model="queryParams.zfrStatus" placeholder="融资状态" clearable>
              <el-option
                v-for="dict in zfrStatusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="费用状态" prop="zciStatus" size="large">
            <el-select v-model="queryParams.zciStatus" placeholder="费用状态" clearable>
              <el-option
                v-for="dict in zciStatusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发票状态" prop="zciInvoiceStatus" size="large">
            <el-select v-model="queryParams.zciInvoiceStatus" placeholder="发票状态" clearable>
              <el-option
                v-for="dict in zciInvoiceStatusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" size="large">
            <el-date-picker
              v-model="dateRange"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </el-row>
    </el-row>

    <div class="zap-content zap-margin-top">
      <el-button
        type="warning"
        @click="handleExport"
        v-hasPermi="['service:cost:export']"
        :disabled="total == 0"
      >导出</el-button>
    </div>

    <el-row class="zap-form">
      <el-table v-loading="loading" :data="costList" stripe>
        <el-table-column label="序号" type="index" width="50" align="center">
          <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="融资编号" align="center" prop="zfrNumber" v-if="uncheckList.zfrNumber" />
        <el-table-column
          label="开立企业"
          align="center"
          prop="coreScyName"
          v-if="uncheckList.coreScyName"
          show-overflow-tooltip
        />
        <el-table-column
          label="融资产品"
          align="center"
          prop="zfpName"
          v-if="uncheckList.zfpName"
          show-overflow-tooltip
        />
        <el-table-column
          label="融资金额"
          align="center"
          prop="zfrAmount"
          :formatter="moneyFormat"
          v-if="uncheckList.zfrAmount"
          show-overflow-tooltip
        />
        <el-table-column
          label="融资状态"
          align="center"
          prop="zfrStatus"
          :formatter="zfrStatusFormat"
          v-if="uncheckList.zfrStatus"
          show-overflow-tooltip
        />
        <el-table-column
          label="费用状态"
          align="center"
          prop="zciStatus"
          :formatter="zciStatusFormat"
          v-if="uncheckList.zciStatus"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          v-if="uncheckList.createTime"
          show-overflow-tooltip
        />
        <el-table-column
          label="手续费"
          align="center"
          prop="zciAmount"
          :formatter="moneyFormat"
          v-if="uncheckList.zciAmount "
          show-overflow-tooltip
        />
        <el-table-column
          label="发票状态"
          align="center"
          prop="zciInvoiceStatus"
          :formatter="zciInvoiceStatusFormat"
          v-if="uncheckList.zciInvoiceStatus"
          show-overflow-tooltip
        />
        <el-table-column
          label="快递单号"
          align="center"
          prop="zciExpressNo"
          v-if="uncheckList.zciExpressNo"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="150"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.zciInvoiceStatus == '2' || scope.row.zciInvoiceStatus == '4'"
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['service:cost:update']"
            >发票</el-button>
            <el-button
              v-if="scope.row.zfrStatus != '02' && (scope.row.zciStatus == '00' || scope.row.zciStatus == '05')"
              size="mini"
              type="text"
              @click="handlePay(scope.row)"
              v-hasPermi="['service:cost:pay']"
            >去缴费</el-button>
            <el-button
              v-if="scope.row.zciStatus == '02' && (scope.row.zfrStatus == '01' || scope.row.zfrStatus == '03') && scope.row.zciInvoiceStatus == '0'"
              size="mini"
              type="text"
              @click="handleApply(scope.row)"
              v-hasPermi="['service:cost:apply']"
            >申请开票</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 发票框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="140px" :inline="true">
        <el-form-item label="企业名称" prop="scyName">
          <el-input v-model="form.scyName" disabled />
        </el-form-item>
        <el-form-item label="企业统一代码" prop="scySocialCode">
          <el-input v-model="form.scySocialCode" disabled />
        </el-form-item>
        <el-form-item label="企业注册电话" prop="scyPhone">
          <el-input v-model="form.scyPhone" disabled />
        </el-form-item>
        <el-form-item label="收件人" prop="ziaContacts">
          <el-input v-model="form.ziaContacts" disabled />
        </el-form-item>
        <el-form-item label="收件人电话" prop="ziaContactsPhone">
          <el-input v-model="form.ziaContactsPhone" disabled />
        </el-form-item>
        <el-form-item label="邮寄地址" prop="ziaAddress">
          <el-input v-model="form.ziaAddress" disabled />
        </el-form-item>
        <el-form-item label="快递单号" prop="zciExpressNo">
          <el-input v-model="form.zciExpressNo" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 申请开票框 -->
    <el-dialog :title="titleApply" :visible.sync="openApply" width="800px" append-to-body>
      <el-form
        ref="formApply"
        :model="formApply"
        :rules="rulesApply"
        label-width="140px"
        :inline="true"
      >
        <el-form-item label="企业名称" prop="scyName">
          <el-input v-model="formApply.scyName" disabled />
        </el-form-item>
        <el-form-item label="企业统一代码" prop="scySocialCode">
          <el-input v-model="formApply.scySocialCode" disabled />
        </el-form-item>
        <el-form-item label="企业注册电话" prop="scyPhone">
          <el-input v-model="formApply.scyPhone" disabled />
        </el-form-item>
        <el-form-item label="收件人" prop="ziaContacts">
          <el-input
            v-model="formApply.ziaContacts"
            placeholder="请输入收件人"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="收件人电话" prop="ziaContactsPhone">
          <el-input
            v-model="formApply.ziaContactsPhone"
            placeholder="请输入收件人电话"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="邮寄地址" prop="ziaAddress">
          <el-input
            v-model="formApply.ziaAddress"
            placeholder="请输入邮寄地址"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCost,
  listInvoice,
  selectInvoiceList,
  applyInvoice,
  invoicing,
  daleteInvoice,
  getUser,
  changeZfiStatus
} from "@/api/service/cost/costManage";
import { uploadFileNew } from "@/api/common/file";
import { getToken } from "@/utils/auth";
import { columnQuery, columnfilter } from "@/api/common/columnSetting";
import ColumnSetting from "../../../components/Table/columnSetting.vue";
import { balance,transfer } from "@/api/bank/bankInterface";
export default {
  name: "userCostManage",
  components: {
    ColumnSetting
  },
  data() {
    return {
      //企业类型
      companyType: null,
      //费用列表
      costList: [],
      //创建时间范围
      dateRange: [],
      //费用状态
      zciStatusOptions: [],
      //发票状态
      zciInvoiceStatusOptions: [],
      //融资状态
      zfrStatusOptions: [],
      //筛选条件
      queryOptions: [],
      //操作员Id
      userId: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // 弹出层标题
      title: "",
      openInvoiceTitle: "",
      titleApply: "",
      total: 0,
      // 是否显示弹出层
      open: false,
      openInvoice: false,
      openApply: false,
      // 链属查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        zfrNumber: null,
        coreScyName: null,
        zciStatus: null,
        zfrStatus: null,
        zciInvoiceStatus: null,
        zciQuery: null,
        zciValue: null
      },
      //筛选按钮的数据列表，与table表头的数据一致 --显示隐藏列用
      tableList: [
        {
          label: "zfrNumber",
          value: "融资编号"
        },
        {
          label: "supScyName",
          value: "融资企业"
        },
        {
          label: "coreScyName",
          value: "开立企业"
        },
        {
          label: "zfpName",
          value: "融资产品"
        },
        {
          label: "zfrAmount",
          value: "融资金额"
        },
        {
          label: "zciStatus",
          value: "费用状态"
        },
        {
          label: "zfrStatus",
          value: "融资状态"
        },
        {
          label: "createTime",
          value: "创建时间"
        },
        {
          label: "zciAmount",
          value: "手续费"
        },
        {
          label: "zciInvoiceStatus",
          value: "发票状态"
        },
        {
          label: "zciExpressNo",
          value: "快递单号"
        }
      ],
      checkList: [], //筛选列选中的数据列表--显示隐藏列用
      uncheckList: {}, //控制筛选列显示隐藏--显示隐藏列用
      selfDom: this,
      tableId: "/sc-service/cost/list",
      // 表单参数
      form: {
        zciId: null,
        scyId: null,
        scyName: null,
        scySocialCode: null,
        scyPhone: null,
        ziaContacts: null,
        ziaContactsPhone: null,
        ziaAddress: null,
        zciExpressNo: null,
        zciInvoiceStatus: null
      },
      formApply: {
        zciId: null,
        scyId: null,
        scyName: null,
        scySocialCode: null,
        scyPhone: null,
        ziaContacts: null,
        ziaContactsPhone: null,
        ziaAddress: null,
        zciExpressNo: null,
        zciInvoiceStatus: null
      },
      // 表单校验
      rulesApply: {
        ziaContacts: [
          { required: true, message: "收件人不能为空", trigger: "blur" }
        ],
        ziaContactsPhone: [
          { required: true, message: "收件人电话不能为空", trigger: "blur" },
          {
            pattern: /^((\d{3}-\d{7,8}|\d{4}-\d{7,8})|(1[3465789]\d{9}))$/,
            message: "电话格式不正确",
            trigger: "blur"
          }
        ],
        ziaAddress: [
          { required: true, message: "邮寄地址不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getDicts("ser_zci_status").then(response => {
      this.zciStatusOptions = response.data;
    });
    this.getDicts("	ser_zci_invoice_status").then(response => {
      this.zciInvoiceStatusOptions = response.data;
    });
    this.getDicts("	ser_zfr_status").then(response => {
      this.zfrStatusOptions = response.data;
    });
    this.getDicts("	zc_zci_query").then(response => {
      this.queryOptions = response.data;
    });
    this.getUser();
    this.getList();
  },
  activated() {
    this.getDicts("ser_zci_status").then(response => {
      this.zciStatusOptions = response.data;
    });
    this.getDicts("	ser_zci_invoice_status").then(response => {
      this.zciInvoiceStatusOptions = response.data;
    });
    this.getDicts("	ser_zfr_status").then(response => {
      this.zfrStatusOptions = response.data;
    });
    this.getUser();
    this.getList();
  },
  mounted() {
    this.columnQuery();
  },
  methods: {
    //列表格式化金额
    moneyFormat(row, column, cellValue) {
      if (cellValue == null || cellValue == undefined || cellValue == "") {
        cellValue = "0.00";
      }
      cellValue += "";
      if (!cellValue.includes(".")) {
        cellValue += ".00";
      }
      return cellValue
        .replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
          return $1 + ",";
        })
        .replace(/\.$/, "");
    },
    //获取当前客户是否之前设置过列展示隐藏
    columnQuery() {
      //获取页面路径
      var psfPagePath = window.location.pathname;
      //用请求后台的url作为唯一标识
      var psfTableName = this.tableId;
      var columnForm = {};
      columnForm.psfPagePath = psfPagePath;
      columnForm.psfTableName = psfTableName;
      columnQuery(columnForm).then(response => {
        if (response.data && response.data.psfShowData) {
          this.checkList = response.data.psfShowData;
        }
        this.filter();
      });
    },
    //控制隐藏显示的函数
    filter(checkList) {
      if (!!checkList) {
        this.checkList = checkList;
      }
      columnfilter(this.selfDom);
    },

    //菜单状态字典翻译
    zciStatusFormat(row, column) {
      return this.selectDictLabel(this.zciStatusOptions, row.zciStatus);
    },
    zciInvoiceStatusFormat(row, column) {
      return this.selectDictLabel(
        this.zciInvoiceStatusOptions,
        row.zciInvoiceStatus
      );
    },
    zfrStatusFormat(row, column) {
      return this.selectDictLabel(this.zfrStatusOptions, row.zfrStatus);
    },
    /** 查询链属列表 */
    getList() {
      this.loading = true;
      listCost(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.costList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openApply = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery();
    },
    /** 发票按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (row.zciId) {
      } else {
        this.$message({
          type: "warning",
          message: "无费用数据"
        });
        return;
      }
      if (row.zfiSupplierId) {
      } else {
        this.$message({
          type: "warning",
          message: "无融资企业信息"
        });
        return;
      }
      const zciId = row.zciId || this.ids;
      const scyId = row.zfiSupplierId || this.ids;
      listInvoice(scyId, zciId).then(response => {
        this.form = response.data[0];
        this.form.zciId = zciId;
      });
      this.open = true;
      this.title = "发票信息";
    },

    /** 发票按钮操作 */
    handleApply(row) {
      this.reset();
      if (row.zciId) {
      } else {
        this.$message({
          type: "warning",
          message: "无费用数据"
        });
        return;
      }
      if (row.zfiSupplierId) {
      } else {
        this.$message({
          type: "warning",
          message: "无融资企业信息"
        });
        return;
      }
      const zciId = row.zciId || this.ids;
      const scyId = row.zfiSupplierId || this.ids;
      listInvoice(scyId, zciId).then(response => {
        this.formApply = response.data[0];
        this.formApply.zciId = zciId;
      });
      this.openApply = true;
      this.titleApply = "申请开票信息";
    },
    //去缴费
    handlePay(row) {
      debugger
      var self = this;
      const zciId = row.zciId || this.ids;
      const maney = row.zciAmount;
      this.$confirm('您需缴纳手续费"' + maney + '"元', {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(function() {
          const loading = self.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          // self.paiAccno = '3115730025230000214';
          if(row.accNo){
            balance(row.accNo).then(response => {
              if(eval(row.zciAmount) > eval(response.data.list.row.KYAMT)){
                self.$message({
                  message: '余额为'+response.data.list.row.KYAMT+'不足以抵扣本次缴费费用,请及时充值',
                  type: 'warning'
                });
                loading.close();
              }else{
                if(row.zfrStatus == '01' || row.zfrStatus == '03'){
                  var map = {'recvAccNo':'','recvAccNm':'','tranAmt':row.zciAmount,'businessId':row.zciId,'type':'01'}
                  transfer(map).then(response => {
                    loading.close();
                    self.msgSuccess("缴费成功");
                    return changeZfiStatus(zciId);
                  }).catch(() => {
                      loading.close();
                  });
                }else{
                  var map = {'recvAccNo':'','recvAccNm':'','tranAmt':row.zciAmount,'businessId':row.zciId,'type':'00'}
                  transfer(map).then(response => {
                    loading.close();
                    self.msgSuccess("缴费成功");
                    return changeZfiStatus(zciId);
                  }).catch(() => {
                      loading.close();
                  });
                }
                
              }
            }).catch(() => {
                loading.close();
            });
          }else{
            self.$message({
              message: '您还没有电子账户,请联系平台开通电子账户',
              type: 'warning'
            });
            loading.close();
          }
        })
        // .then(() => {
        //   this.getList();
        //   this.msgSuccess("缴费成功");
        // })
        // .catch(() => {
        //   this.$message({
        //     type: "warning",
        //     message: "已取消缴费"
        //   });
        // });
    },

    /** 提交按钮 */
    submitForm() {
      var self = this;
      this.$refs["formApply"].validate(valid => {
        let fd = new FormData();
        for (var key in self.formApply) {
          fd.append(key, self.formApply[key]);
        }
        if (valid) {
          if (this.formApply.scyId != null) {
            const loading = this.$loading({
              lock: true,
              text: "Loading",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)"
            });
            applyInvoice(self.formApply)
              .then(response => {
                this.msgSuccess("申请成功");
                loading.close();
                this.openApply = false;
                this.getList();
              })
              .catch(response => {
                loading.close();
              });
          }
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      // this.getList();
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.download(
        "/sc-service/cost/export",
        {
          ...this.queryParams,
          ...this.dateRange
        },
        "费用信息.xlsx"
      );
      setTimeout(() => {
        loading.close();
      }, 2000);
    },

    //获取操作员Id
    getUser() {
      getUser().then(response => {
        this.userId = response.data.userId;
        this.companyType = response.data.scyType
      });
    }
  }
};
</script>