<template>
  <div class="app-container">
    <el-form ref="form" :label-position="labelPosition" :model="form" :rules="rules" label-width="106px">
      <el-divider content-position="left">授信信息</el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="资金方:" prop="zfpcrFundSide">
            <el-select v-model="form.zfpcrFundSide" style="width : 284px" clearable>
              <el-option
                v-for="(item,index) in zfCompanyList"
                :key="index"
                :label="item.scyName"
                :value="item.scyId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="融资产品:" prop="zfpcrProductId">
            <el-select v-model="form.zfpcrProductId" style="width : 284px" clearable>
              <el-option
                v-for="(item,index) in financeProductList"
                :key="index"
                :label="item.zfpName"
                :value="item.zfpId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="授信企业名称:" prop="zfpcrCompanyId">
            <el-select v-model="form.zfpcrCompanyId" style="width : 284px" clearable>
              <el-option
                v-for="(item,index) in hxCompanyList"
                :key="index"
                :label="item.scyName"
                :value="item.scyId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="原授信额度:" prop="zfpcrOldAmount" >
            <el-input v-model="form.zfpcrOldAmount"   style="width:284px" disabled>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="已用授信额度:" prop="zfiAmount" >
            <el-input v-model="form.zfiAmount"   style="width:284px" disabled>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="剩余授信额度:" prop="usableAmount" >
            <el-input v-model="form.usableAmount"   style="width:284px" disabled>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="授信额度:" prop="zfpcrAmount">
            <!-- <el-tooltip class="item" effect="light" :content= "zfpcrAmountFormat" placement="top-start"> -->
            <el-input v-model="form.zfpcrAmount" placeholder="请输入授信额度"  style="width:284px">
              <template slot="append">元</template>
            </el-input>
            <!-- </el-tooltip> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="利率:" prop="zfpcrRate">
          <el-input v-model="form.zfpcrRate" placeholder="请输入利率" style="width:284px">
            <template slot="append">%起</template>
          </el-input>
        </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="有效期:" prop="zfpcrDateType">
            <el-radio-group v-model="form.zfpcrDateType" size="medium">
              <el-radio-button  v-for="(dict,index) in dateTypeOptions" :key="index" :label="dict.dictValue" border>{{dict.dictLabel}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="有效期范围:" prop="dateTime" v-if="this.form.zfpcrDateType == '1'">
            <el-date-picker  
              v-model="form.dateTime"
              clearable
              style="width: 284px"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="融资网点:" prop="zfpcrAddress">
            <el-input v-model="form.zfpcrAddress" placeholder="请输入融资网点" style="width:284px"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否收取手续费:" prop="zfpcrCharge" label-width="113px">
            <el-radio-group v-model="form.zfpcrCharge" size="medium" >
              <el-radio-button  v-for="(dict,index) in chargeOptions" :key="index" :label="dict.dictValue" border>{{dict.dictLabel}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="平台服务费收取费率:" prop="zfpcrChargeRate" label-width="139px" v-if="this.form.zfpcrCharge == '1'">
          <el-input v-model="form.zfpcrChargeRate" placeholder="请输入平台服务费收取费率" style="width:284px">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="核心企业还款账户账号:" prop="zfpcrAccount" label-width="142px">
            <el-autocomplete
              style="width:286px"
              class="inline-input"
              v-model="form.zfpcrAccount"
              :fetch-suggestions="querySearch"
              placeholder="核心企业还款账户账号"
              ></el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="融资放款方式:" prop="zfpcrLoanType">
            <el-select v-model="form.zfpcrLoanType" placeholder="请选择状态" clearable style="width : 284px" clearable>
              <el-option
                v-for="dict in loanTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="记账簿托管方式:" prop="zfpcrBookkeepingType" label-width="113px">
            <el-select v-model="form.zfpcrBookkeepingType" placeholder="请选择状态" clearable style="width : 284px" clearable>
              <el-option
                v-for="dict in bookkeepingTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
        </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">关联合同</el-divider>
      <el-form-item prop="zfqcrContractId" style="margin-left: 100px" >
        <el-button size="mini" type="primary" @click="openTicket">选择合同</el-button>
        <el-button size="mini" @click="deleteTicekt">清空全部</el-button>
        <el-table :data="ticketList" style="width: 1100px">
          <el-table-column label="合同模板编号"  align="center"  prop="zfcNumber" show-overflow-tooltip />
          <el-table-column label="合同模板名称"  align="center"  prop="zfcName"   />
          <el-table-column label="签署主体"  align="center"  prop="zfcSubject"    />
          <el-table-column label="合同id"  align="center"  prop="zfcId" v-if="false"  />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.$index, ticketList)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <!-- 合同信息 -->
    <el-dialog :title="title" :visible.sync="open" width="1120px" append-to-body>
      <el-form :model="queryParamsContract"  ref="formQuery"  :inline="true"  label-width="68px"  style="margin-bottom: -21px">
        <el-form-item label="合同模板编号" prop="zfcNumber">
          <el-input
            v-model="queryParamsContract.zfcNumber"
            placeholder="请输入合同模板编号"
            clearable
            size="small"
            maxlength="11"
            @keyup.enter.native="handleQuerys"/>
        </el-form-item>
        <el-form-item label="合同模板名称" prop="zfcName">
          <el-input
            v-model="queryParamsContract.zfcName"
            placeholder="请输入合同模板名称"
            clearable
            size="small"
            maxlength="11"
            @keyup.enter.native="handleQuerys"/>
        </el-form-item>
        <el-form-item>
          <el-button
            type="cyan"
            icon="el-icon-search"
            size="mini"
            @click="handleQuerys"
            >搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuerys"
            >重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="contractList"
        ref="tableContract"
        class="single-select-table"
        @selection-change="handleSelectionChange" 
        :row-key="rowkey">
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="50"
          align="center"/>
        <el-table-column label="序号" type="index" width="50" align="center">
          <template slot-scope="scope">
            <span>{{ (queryParamsContract.pageNum - 1) * queryParamsContract.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同模板编号"  align="center"  prop="zfcNumber" show-overflow-tooltip />
          <el-table-column label="合同模板名称"  align="center"  prop="zfcName"   />
          <el-table-column label="签署主体"  align="center"  prop="zfcSubject"    />
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParamsContract.pageNum"
        :limit.sync="queryParamsContract.pageSize"
        @pagination="getContractList" />
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="cancelTicket">取消</el-button>
        <el-button size="mini" type="primary" @click="closeTicket">确认</el-button>
      </span>
    </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <!-- <el-button @click="cancel">取 消</el-button> -->
      </div>
  </div>
</template>

<script>
import { listCreditLine, getCreditLine, delCreditLine, addCreditLine, updateCreditLine} from "@/api/service/creditLine/creditLine";
import { listFinanceProduct } from "@/api/common/financeProduct"
import { listCompany } from "@/api/common/company"
import { listCompanyAcc } from "@/api/common/companyAcc"
export default {
  name: "editCreditLine",
  components: {},
  data() {
    return {
      //存储授信额度
      amount: '',
      //金额展示
      zfpcrAmountFormat: '',
      //还款账户搜所
      restaurants: [],
      labelPosition: 'top',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业授信额度表格数据
      creditLineList: [],
      //资金方数据
      zfCompanyList: [],
      //融资产品数据
      financeProductList: [],
      //核心企业数据
      hxCompanyList: [],
      //核心企业还款账户数据:
      accList: [],
      //合同表格数据
      ticketList: [],
      //合同列表数据
      contractList: [],
      //有效期数据字典
      dateTypeOptions: [],
      //是否收取手续费数据字典
      chargeOptions: [],
      //融资放款方式数据字典
      loanTypeOptions: [],
      //记账簿托管方式数据字典
      bookkeepingTypeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        zfpcrProductId: null,
        zfpcrCompanyId: null,
        zfpcrType: null,
        zfpcrAmount: null,
        zfpcrRate: null,
        zfpcrDivisionAmount: null,
        zfpcrDateType: null,
        zfpcrStartDate: null,
        zfpcrEndDate: null,
        zfpcrAddress: null,
        zfpcrCharge: null,
        zfpcrChargeRate: null,
        zfpcrAccount: null,
        zfpcrLoanType: null,
        zfpcrBookkeepingType: null,
        zfpcrStatus: null,
        zfpcrProfitSpare1: null,
        zfpcrProfitSpare2: null,
        zfpcrProfitSpare3: null,
        zfpcrProfitSpare4: null,
        zfpcrProfitSpare5: null,
        zfpcrProfitSpare6: null,
        zfpcrProfitSpare7: null,
        zfpcrProfitSpare8: null,
        zfpcrProfitSpare9: null,
      },
      queryParamsContract: {
        pageNum: 1,
        pageSize: 10,
        zfcId: null,
        zfcName: null,
        zfcNumber: null,
        zfcManagementId: null
      },
      // 表单参数
      form: {
        zfpcrDateType: '0',
        zfpcrCharge: '1'
      },
      // 表单校验
      rules: {
        zfpcrFundSide: [
          { required: true, message: "资金方不能为空", trigger: ["blur", "change"] }
        ],
        zfpcrProductId: [
          { required: true, message: "融资产品不能为空", trigger: ["blur", "change"] }
        ],
        zfpcrCompanyId: [
          { required: true, message: "授信企业名称不能为空", trigger: ["blur", "change"] }
        ],
        zfpcrAmount: [
          { required: true, message: "授信额度不能为空", trigger: ["blur", "change"] },
          {
            pattern: /^[0-9][0-9]{0,7}$|^[1-9][0-9]{0,7}[.]\d{1,2}$/,
            message: "请输入正确的额度",
            trigger: "change",
          },
        ],
        zfpcrRate: [
          { required: true, message: "利率不能为空", trigger: ["blur", "change"] },
          {
            pattern: /^([0-9]{1,2}$)|(^[0-9]{1,2}\.[0-9]{1,2}$)|100$/,
            message: "请输入正确的利率",
            trigger: "change",
          }, 
        ],
        dateTime: [
          { required: true, message: "有效期范围不能为空", trigger: ["blur", "change"] }
        ],
        zfpcrChargeRate: [
          { required: true, message: "平台服务费收取费率不能为空", trigger: ["blur", "change"] },
          {
            pattern: /^([0-9]{1,2}$)|(^[0-9]{1,2}\.[0-9]{1,2}$)|100$/,
            message: "请输入正确的平台服务费收取费率",
            trigger: "change",
          },
        ],
        zfpcrAccount: [
          { required: true, message: "核心企业还款账户账号", trigger: ["blur", "change"] }
        ],
        zfpcrLoanType: [
          { required: true, message: "融资放款方式不能为空", trigger: ["blur", "change"] }
        ],
        zfpcrBookkeepingType: [
          { required: true, message: "记账簿托管方式不能为空", trigger: ["blur", "change"] }
        ],
      }
    };
  },
  created() {
    const zfpcrId = this.$route.params && this.$route.params.zfpcrId;
    const zfiAmount = this.$route.params && this.$route.params.zfiAmount;
    const usableAmount = this.$route.params && this.$route.params.usableAmount;
    getCreditLine(zfpcrId).then((response) => {
      this.ticketList = response.data.ticketList;
                   /* 查询资方 */
      //公司类型
      const scyType = '03';
      //公司id
      const scyId = response.data.list[0].zfpManagementId;
      listCompany(scyType,scyId).then((response) =>{
        this.zfCompanyList  = response.data
      });
                   /* 查询融资产品 */
      //产品id
      const zfpcrProductId = response.data.list[0].zfpcrProductId;
      listFinanceProduct(zfpcrProductId).then((response) =>{
        this.financeProductList  = response.data
      });
                   /* 查询授信企业名称 */
      //公司类型
      const scyTypes = '01';
      //公司id
      const scyIds = response.data.list[0].zfpcrCompanyId;
      listCompany(scyTypes,scyIds).then((response) =>{
        this.hxCompanyList = response.data
      });
                  /* 查询还款账户 */
      //银行卡号
      const zfpcrAccount = response.data.list[0].zfpcrAccount;
      listCompanyAcc(zfpcrAccount).then((response) =>{
        this.accList  = response.data
        this.restaurants = response.data;
      }).then(()=>{
        this.form = response.data.list[0]
        this.amount = response.data.list[0].zfpcrAmount
        this.form.zfpcrFundSide = this.zfCompanyList[0];
        this.$set(this.form, "dateTime", [response.data.list[0].zfpcrStartDate, response.data.list[0].zfpcrEndDate])
        this.$set(this.form, "zfiAmount", zfiAmount);
        this.$set(this.form, "usableAmount", usableAmount);
      });   
    });
    // this.getZfCompany();
    // this.getFinanceProduct();
    // this.getHxCompany();
    // this.getCompanyAcc();
    this.getDicts("zc_zfpcr_date_type").then(response => {
      this.dateTypeOptions = response.data;
    });
    this.getDicts("zc_zfpcr_charge").then(response => {
      this.chargeOptions = response.data;
    });
    this.getDicts("zc_zfpcr_loan_type").then(response => {
      this.loanTypeOptions = response.data;
    });
    this.getDicts("zc_zfpcr_bookkeeping_type").then(response => {
      this.bookkeepingTypeOptions = response.data;
    });
  },
  methods: {
    /* 资方公司 */
    getZfCompany(){
      //公司类型
      const scyType = '03'
      listCompany(scyType).then((response) =>{
        this.zfCompanyList  = response.data
      })
    },
    /* 融资产品 */
    getFinanceProduct(){
      listFinanceProduct().then((response) =>{
        this.financeProductList  = response.data
      })
    },
    /* 授信企业 */
    getHxCompany(){
      //公司类型
      const scyTypes = '01'
      listCompany(scyTypes).then((response) =>{
        this.hxCompanyList  = response.data
      })
    },
    /* 核心企业还款账户账号 */
    getCompanyAcc(){
      listCompanyAcc().then((response) =>{
        this.accList  = response.data
        this.restaurants = response.data;
      })
    },
    /* 账户模糊搜所 */
    querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    /* 合同相关 */
    //合同列表
    getContractList() {
      this.queryParamsContract.zfcManagementId = this.form.zfpcrFundSide
      listContract(this.queryParamsContract).then((response) => {
        this.contractList = response.data.records;
        this.selectChecked();
        this.total = response.data.total;
      });
    },
    //打开合同选择列表
    openTicket() {
      this.getContractList()
      this.open = true
      this.title = "合同信息"
    },
    selectChecked() {
      this.ticketList.forEach((item) => {
        this.contractList.forEach(row => {
          if (row.zfcId == item.zfcId) {
            this.$nextTick(() => {
              this.$refs.tableContract && this.$refs.tableContract.toggleRowSelection(row, true);
            })
          }
        });
      });
    },
    /* 多选框跨页 */
    rowkey(row) {
      return row.zfcId;
    },
    // 多选框选中数据
    handleSelectionChange(val) {
        this.chooseTicket = val
    },
    // 确认选择
    closeTicket() {
        if(this.chooseTicket.length > 0){
          this.ticketList = this.chooseTicket
          this.$set(this.form, "zfcName", this.ticketList[0].zfcName);
          this.$set(this.form, "zfcNumber", this.ticketList[0].zfcNumber);
          this.$set(this.form, "zfcSubject", this.ticketList[0].zfcSubject);
          this.$set(this.form, "zfcId", this.ticketList[0].zfcId);
          this.open = false
      }else{
        this.$message({
          message: '请选择合同',
          type: 'warning'
        });
      }
    },
    //取消选择合同按钮
    cancelTicket(){
      this.ticketList = [];
      if(this.$refs.tableContract){
        this.$refs.tableContract.clearSelection();
      }
      this.open = false;
    },
    /** 清空选择发票信息 */
    deleteTicekt() {
      this.ticketList = []
      if(this.$refs.tableContract){
        this.$refs.tableContract.clearSelection();
      }
    },
    /* 删除按钮 */
    handleDelete(index, rows) {
      rows.splice(index, 1);
      if(this.$refs.tableContract){
        this.$refs.tableContract.clearSelection();
      }
      this.selectChecked();
    },
    onSelectAll() {
      if(this.$refs.tableContract){
        this.$refs.tableContract.clearSelection();
      }
    },
    handleQuerys() {
      this.queryParamsContract.pageNum = 1;
      this.getContractList();
    },
    resetQuerys() {
      this.resetForm("formQuery");
      this.handleQuerys();
    },
    /** 提交按钮 */
    submitForm() {
      // if(this.ticketList == undefined || this.ticketList.length == 0){
      //   this.$message({
      //       message: '请选择合同',
      //       type: 'warning'
      //     });
      //     return;
      // }
      this.$refs["form"].validate(valid => {
        this.form.ticketList = this.ticketList;
        this.form.zfpcrOldAmount = this.amount;
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          updateCreditLine(this.form).then(response => {
            this.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.go(-1);
          }).catch((response) => {
              loading.close();
          });
        }
      });
    },
    /* 金额展示 */
    handleInput(str) {
        this.zfpcrAmountFormat = amtformat(str,2, ".", ",");
    },
    /* //  将数字金额转换为大写金额 */
    smallToBig(money) {
      //  将数字金额转换为大写金额
      var cnNums = new Array(
        "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" ); //汉字的数字
      var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
      var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
      var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
      var cnInteger = "整"; //整数金额时后面跟的字符
      var cnIntLast = "元"; //整数完以后的单位
      //最大处理的数字
      var maxNum = 999999999999999.9999;
      var integerNum; //金额整数部分
      var decimalNum; //金额小数部分
      //输出的中文金额字符串
      var chineseStr = "";
      var parts; //分离金额后用的数组，预定义
      if (money == "" || money == null || money == undefined) {
        return "零元零角零分";
      }
      money = parseFloat(money);
      if (money >= maxNum) {
        //超出最大处理数字
        return "超出最大处理数字";
      }
      if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
      }
      //四舍五入保留两位小数,转换为字符串
      money = Math.round(money * 100).toString();
      integerNum = money.substr(0, money.length - 2);
      decimalNum = money.substr(money.length - 2);
      //获取整型部分转换
      if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
          var n = integerNum.substr(i, 1);
          var p = IntLen - i - 1;
          var q = p / 4;
          var m = p % 4;
          if (n == "0") {
            zeroCount++;
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0];
            }
            //归零
            zeroCount = 0;
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m == 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        chineseStr += cnIntLast;
      }
      //小数部分
      if (decimalNum != "") {
        var decLen = decimalNum.length;
        for (var i = 0; i < decLen; i++) {
          var n = decimalNum.substr(i, 1);
          if (n != "0") {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (chineseStr == "") {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (decimalNum == "" || /^0*$/.test(decimalNum)) {
        chineseStr += cnInteger;
      }
      return chineseStr;
    },
  },
};
</script>
<style>
.single-select-table thead .el-table-column--selection .cell {
  display: none;
}

</style>
