<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="card-title">{{ $t('请款单') }} {{id ? `-${form.paymentNo}` :''}}</div>
      <el-form
        ref="form"
        :model="form"
        label-width="120px"
        label-position="left"
      >
        <el-descriptions :column="3" class="card" border>
          <el-descriptions-item :label="$t('供应商')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="supplierId"
              :rules="{ required: true, trigger: ['blur', 'change'],message:$t('供应商不能为空') }"
              :error="$t('供应商不能为空')"
            >
              <!-- <customer-selector v-model="form.supplierId" @change="consignor = $event" /> -->
              <el-select
                v-model="form.supplierId"
                :placeholder="$t('请选择供应商')"
                @change="selectChange"
              >
                <el-option
                  v-for="supplier in allSupplier"
                  :key="supplier.id"
                  :label="supplier.companyZh"
                  :value="supplier.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('部门')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="departmentId"
              :rules="{required:true,message:$t('部门不能为空')}"
              :error="$t('部门不能为空')"
            >
              <el-select
                v-model="form.departmentId"
                style="width: 300px"
                :placeholder="$t('请选择部门')"
              >
                <el-option
                  @click.native="selslectVal('departmentName', item.name)"
                  v-for="item in deptData"
                  :key="item.id"
                  :label="item.named"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('业务员')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="salesmanName"
              :rules="{required:true,message:$t('业务员不能为空')}"
              :error="$t('业务员不能为空')"
            >
              <el-select v-model="form.salesmanName" :placeholder="$t('请选择业务员')">
                <el-option
                  v-for="item in creatorData"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.nickname"
                  @click.native="selslectVal('salesmanId',item.id)"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('申请日期')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="applicationAt"
              :rules="{required:true,message:$t('申请日期不能为空')}"
              :error="$t('申请日期不能为空')"
            >
              <el-date-picker
                clearable
                v-model="form.applicationAt"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                type="date"
                :placeholder="$t('选择申请日期')"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('供应商银行账号')" style="width: 50%">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="supplierBankAccount"
            >
              <el-select v-model="form.supplierBankAccount"  @change="selectChangeBank" :placeholder="$t('请选择收款账户')">
                <el-option
                  v-for="item in bankData"
                  :key="item.id"
                  :label="item.bankName + '(' + item.bankAccount+ ')'"
                  :value="item.bankAccount"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions :column="3" class="card" border>
          <el-descriptions-item :label="$t('最后付款日期')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="latestPayAt"
              :rules="{required:true,message:$t('最后付款不能为空')}"
              :error="$t('最后付款日期不能为空')"
            >
              <el-date-picker
                clearable
                v-model="form.latestPayAt"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                type="date"
                :placeholder="$t('选择最后付款日期')"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('结算方式')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              :rules="{required:true,message:$t('结算方式不能为空')}"
              :error="$t('选择结算方式')"
              prop="settlementType"
            >
              <dict-selector
                :type="DICT_TYPE.CUSTOMER_BALANCE"
                v-model="form.settlementType"
              />
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
    </el-card>
    <el-card class="card">
      <div slot="header" class="card-title">{{ $t('费用信息') }}</div>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          style="padding: 10px; margin-bottom: 10px"
          >{{ $t('添加未付供应商款项') }}</el-button
        >
      </el-col>
      <el-table v-loading="loadings" :data="list" border :show-summary="!!list.length" :summary-method="getSummaries">
        <el-table-column :label="$t('自编号')" align="center" prop="payableNo" />
        <el-table-column :label="$t('费用类型')" align="center" prop="feeType">
          <template slot-scope="scope">
            <dict-tag
              :type="DICT_TYPE.FEE_TYPE"
              :value="scope.row.feeType"
            ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('发票号码')" align="center" prop="invoiceNumber">
          <template slot-scope="scope">
            <el-input v-model="scope.row.invoiceNumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column :label="$t('应付金额')" align="center" prop="totalAmount" />
        <el-table-column :label="$t('币种')" align="center" prop="currencyId">
          <template slot-scope="scope">
			  {{getCurrencyLabel(scope.row.currencyId)}}
            <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
          </template>
        </el-table-column>
        <el-table-column :label="$t('汇率')" align="center" prop="exchangeRate">
          <template slot-scope="scope">
            <el-input v-model="scope.row.exchangeRate"></el-input>
          </template>
        </el-table-column>
        <el-table-column :label="$t('税率')+'%'" align="center" prop="taxRate" >
          <template slot-scope="scope">
            <el-input v-model="scope.row.taxRate" @keyup.native="scope.row.taxRate = oninput(scope.row.taxRate)"></el-input>
          </template>
        </el-table-column>
        <el-table-column :label="$t('价税合计(RMB)')" align="center" prop="total" >
          <template slot-scope="scope">
           <span>{{ scope.row.total = ((scope.row.totalAmount * scope.row.exchangeRate) + (scope.row.totalAmount * scope.row.exchangeRate) * (scope.row.taxRate/100)).toFixed(2) }}</span>
           <!-- <span>{{scope.row.total}}</span> -->
          </template>
        </el-table-column>
      </el-table>

      <el-form
        ref="forms"
        :model="form"
        label-width="120px"
        label-position="left"
        style="width: 50%"
      >
        <el-descriptions :column="1" class="card" border>
          <el-descriptions-item :label="$t('账单号')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="accountNumber"
              :rules="[
                { required: true, message:$t('账单号不能为空'), trigger: 'blur' },
              ]"
            >
              <el-input
                v-model="form.accountNumber"
                :placeholder="$t('请输入账单号')"
              ></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('发票')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoiceStatus"
              required
              :error="$t('请选择是否开票')"
            >
              <el-select
                v-model="form.invoiceStatus"
                :placeholder="$t('请选择是否开票')"
              >
                <el-option :label="$t('未开票')" value="0" />
                <el-option :label="$t('已开票')" value="1" />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
    </el-card>
    <div slot="header" class="bpm-title">{{ $t('审核流程') }}</div>
     <work-flow  xmlkey="merge_order" v-model="form.copyUserList"></work-flow>

     <div slot="footer" style="margin: 20px 0">
       <el-button v-if="id==0||form.state==0" type="primary" @click="submitForm(1)">{{$t('提交申请')}}</el-button>
       <el-button v-if="id==0||form.state==0" type="primary"  @click="submitForm(0)">{{ $t('保存草稿') }}</el-button>
       <el-button v-if="form.state==1" type="primary" @click="$router.push(`/bpm/process-instance/detail?id=`+bpmId)">{{$t('审核中')}}</el-button>
       <!-- <el-button v-if="form.state==1" plain type="primary" @click="dialogVisible = true">{{$t('取消审核')}}</el-button> -->
       <el-button plain type="primary" @click="$store.dispatch('tagsView/delCurrentView')">{{$t('返回')}}</el-button>
     </div>
<!--    <div slot="footer" style="margin: 20px 0">
      <el-button type="primary" @click="submitDraft">{{ $t('保 存') }}</el-button>
      <el-button type="primary" @click="submitForm">{{id==0?$t('新增'):$t('编辑')}}</el-button>
    </div> -->
      <el-dialog
        :title="$t('提示')"
        :visible.sync="dialogVisible"
        width="30%">
        <span class="cancel_notice">{{$t('付款单申请正在审核中，你确定取消付款单申请吗？')}}</span>
        <div class="cancel_content">
          <span>{{$t('取消原因：')}}</span>
          <el-input v-model="reason" :placeholder="$t('请输入取消原因')"></el-input>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">{{$t('取消')}}</el-button>
          <el-button type="primary" @click="cancelApproval">{{$t('确定')}}</el-button>
        </span>
      </el-dialog>
    <el-dialog
      :visible.sync="open"
      :title="$t('添加未付供应商款项')"
      width="80%"
      append-to-body
      @open="openDialog"
    >
      <div>
        <!-- <div slot="header" class="card-title">{{ $t('添加未收客户款项') }}</div> -->
        <!-- 搜索工作栏 -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          label-width="80px"
        >
          <!-- <el-row> -->
            <el-form-item :label="$t('供应商')">
              <customer-selector
                v-model="queryParams.supplierId"
                @change="consignor = $event"
              />
            </el-form-item>
        <el-form-item :label="$t('始发仓')">
            <el-select
              v-model="queryParams.departureId"
              :placeholder="$t('请选择始发仓')"
              clearable
            >
              <el-option
                v-for="item in exportWarehouseList"
                :label="$l(item, 'title')"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的仓')">
            <el-select
              v-model="queryParams.objectiveId"
              :placeholder="$t('请选择目的仓')"
              clearable
            >
              <el-option
                v-for="item in importWarehouseList"
                :label="$l(item, 'title')"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
            <el-form-item :label="$t('运输方式')">
              <dict-selector
                :type="DICT_TYPE.ECW_TRANSPORT_TYPE"
                v-model="queryParams.transportId"
                formatter="number"
              />
            </el-form-item>
            <!--  </el-row> -->
            <el-form-item :label="$t('出货渠道')">
              <el-select
                v-model="queryParams.channelId"
                :placeholder="$t('请选择出货渠道')"
              >
                <el-option
                  v-for="item in channelList"
                  :label="item.nameZh"
                  :value="item.channelId"
                  :key="item.channelId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <!-- <el-row> -->
<!--            <el-form-item :label="$t('报关方式')">
              <dict-selector
                :type="DICT_TYPE.ECW_CUSTOMS_TYPE"
                v-model="queryParams.customsType"
              />
            </el-form-item>
            <el-form-item :label="$t('控货')">
              <dict-selector
                :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                v-model="queryParams.control"
              />
            </el-form-item>
            <el-form-item :label="$t('客户名称')">
              <customer-selector
                v-model="queryParams.consignorId"
                @change="consignor = $event"
              />
            </el-form-item>
          </el-row> -->
          <el-form-item :label="$t('订单号')" prop="orderNo">
            <el-input
              v-model="queryParams.orderNo"
              :placeholder="$t('请输入订单号')"
              clearable
            />
          </el-form-item>

          <el-form-item :label="$t('业务编号')" prop="selfNo">
            <el-input
              v-model="queryParams.selfNo"
              :placeholder="$t('请输入业务编号')"
              clearable
              @blur="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >{{ $t('查询') }}</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="orderData"
          border
          @selection-change="handleSelectionChange"
          row-key="id"
        >
          <el-table-column type="selection" width="55" :reserve-selection="true"> </el-table-column>
          <el-table-column :label="$t('业务编号')" align="center" prop="payableNo" />
          <el-table-column :label="$t('货柜号')" align="center" prop="containerNo" />
          <el-table-column :label="$t('供应商')" align="center" prop="supplierName" />
          <el-table-column :label="$t('费用类型')" align="center" prop="feeType">
            <template slot-scope="scope">
              <dict-tag
                :type="DICT_TYPE.FEE_TYPE"
                :value="scope.row.feeType"
              ></dict-tag>
            </template>
          </el-table-column>
          <el-table-column :label="$t('金额')" align="center" prop="totalAmount">
            <template slot-scope="scope">
              <span>{{ scope.row.totalAmount }}{{getCurrencyLabel(scope.row.currencyId)}}</span>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.rows"
          @pagination="getList"
        />
        <!-- </el-card> -->
        <div slot="footer" style="margin: 20px 0; text-align: center;">
          <el-button type="primary" @click="saveSelectList">{{ $t('确认添加') }}</el-button>
          <el-button @click="hiddenDialog">{{ $t('取消') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSimpleUsers } from "@/api/system/user";
import { DICT_TYPE } from "@/utils/dict";
import { getToken } from "@/utils/auth";
import { getChannelList } from "@/api/ecw/channel";
import CustomerSelector from "@/components/CustomerSelector";
import { listSimpleDepts } from "@/api/system/dept";
import { getTradeCityList } from "@/api/ecw/region";
import { getSupplierPage,getSupplier } from "@/api/ecw/supplier";
import { getPayableList, getPayableInfoByIds, createPayment, getPaymentInfoByIds, getPaymentItem, updatePayment } from "@/api/ecw/financial"
import { getCurrencyPage } from "@/api/ecw/currency";
import NP from 'number-precision'
import {getWarehouseList} from '@/api/ecw/warehouse'
import WorkFlow from '@/components/WorkFlow/'
import { getExchangeRatePage } from "@/api/ecw/exchangeRate";

export default {
  name: "EcwFinancialCreatpayment",
  components: {
    CustomerSelector,WorkFlow
  },
  data() {
    return {
      id: 0,
      payableId: 0,
      orderData: [],
      total: 0,
      loadings: false,
      open: false,
      form: {},
      creatorData: [],
      list: [],
      defaultList: [],
      channelList: [],
      loading: "",
      bankData: [],
      reason:'',
      params: {
        page: 1,
        rows: 20,
      },
      deptData: [],
      deptArr: [],
      queryParams: {
        page: 1,
        rows: 20,
      },
      multipleSelection: [],
      tradeCityList: [],
      allSupplier: [],
      currencyList: [],
      warehouseList:[],
      selectedUsers:[],
      dialogVisible:false,
      rateList:[],
    };
  },
  activated(){
    console.log(11)
    if (this.$route.query.payableId && this.$route.query.payableId != 0) {
      this.payableId = this.$route.query.payableId;
      getPayableInfoByIds({ id: this.payableId }).then(res => {
        this.handleSelectionChange([res.data])
        this.list = this.multipleSelection
        this.$set(this.form, 'supplierId', res.data.supplierId)
        this.selectChange(this.form.supplierId)
      })
    }
    if (this.$route.query.id && this.$route.query.id !== '0') {
      this.id = this.$route.query.id;
      getPaymentInfoByIds({ id: this.id }).then(res => {
        this.form = {
          ...res.data,
          latestPayAt: this.parseTime(res.data.latestPayAt, '{y}-{m}-{d}'),
          applicationAt: this.parseTime(res.data.applicationAt, '{y}-{m}-{d}'),
          invoiceStatus: String(res.data.invoiceStatus),
        }

        this.$set(this.form,'supplierBankAccount',res.data.supplierBankAccount)
        console.log(this.form)
      })
      getPaymentItem({ id: this.id }).then(res => {
        this.list = [...res.data]
        this.defaultList = [...res.data]
      })
    }
  },
  async created() {
    await getCurrencyPage(this.params).then(res => this.currencyList = res.data.list)
    await getExchangeRatePage({page:1,rows: 100}).then(res => this.rateList = res.data.list)
    getWarehouseList().then(res => this.warehouseList = res.data)
    let that = this;
    if (that.$route.query.payableId && that.$route.query.payableId != 0) {
      this.payableId = this.$route.query.payableId;
      getPayableInfoByIds({ id: this.payableId }).then(res => {
        this.handleSelectionChange([res.data])
        this.list = this.multipleSelection
        this.$set(this.form, 'supplierId', res.data.supplierId)
        this.selectChange(this.form.supplierId)
      })
    }
    if (that.$route.query.id && that.$route.query.id !== '0') {
      this.id = this.$route.query.id;
      getPaymentInfoByIds({ id: this.id }).then(res => {
        this.form = {
          ...res.data,
          latestPayAt: this.parseTime(res.data.latestPayAt, '{y}-{m}-{d}'),
          applicationAt: this.parseTime(res.data.applicationAt, '{y}-{m}-{d}'),
          invoiceStatus: String(res.data.invoiceStatus),
        }

        this.$set(this.form,'supplierBankAccount',res.data.supplierBankAccount)
        console.log(this.form)
      })
      getPaymentItem({ id: this.id }).then(res => {
        this.list = [...res.data]
        this.defaultList = [...res.data]
      })
    }
    listSimpleUsers().then((res) => (that.creatorData = res.data));
    getChannelList().then((res) => (that.channelList = res.data));
    getTradeCityList().then((res) => (that.tradeCityList = res.data));
    // getBankAccountPage(that.params).then(
    //   (res) => (that.bankData = res.data.list)
    // );
    getSupplierPage({ pageNo: "1", pageSize: "10000" }).then((res) => {
      const { data } = res;
      this.allSupplier = data.list;
      this.selectChange(this.form.supplierId)
    });
    listSimpleDepts().then((res) => {
      res.data.forEach((item) => {
        if (item.parentId == 0) {
          that.deptArr.push(item);
        } else {
          that.deptData.push(item);
        }
      });

      that.deptData.forEach((value) => {
        var dept = that.deptArr.filter((itt) => itt.id == value.parentId);
        if (dept.length > 0) {
          value.named = dept[0].name + " | " + value.name;
        }else {
          value.named =  value.name;
        }
      });
    });
  },
  computed: {
    expoerCityList() {
      return this.tradeCityList.filter((item) => item.type == 2);
    },
    importCityList() {
      return this.tradeCityList.filter((item) => item.type == 1);
    },
    exportWarehouseList(){
      /* tradeType 1 进口，2出口，3进出口 */
      return this.warehouseList.filter(item => item.tradeType == 2 || item.tradeType == 3)
    },
    importWarehouseList(){
      return this.warehouseList.filter(item => item.tradeType == 1 || item.tradeType == 3)
    },
  },
  methods: {
    selslectVal(key,value){
      this.form[key] = value;
    },
	  getCurrencyLabel(id){
	    var label = this.currencyList.filter(item=>item.id == id)
	    if(label.length>0) return this.$i18n.locale=='zh_CN'?label[0].titleZh:label[0].titleEn
	    return ''
	  },
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime");
      // 执行查询
      getPayableList(params).then((response) => {
        this.orderData = response.data.list;
        this.total = response.data.total;
        this.loading = false;
        this.$nextTick(() => {
          this.list.forEach(itm => {
            const t = this.orderData.find(v => v.id == itm.id)
            t && this.$refs.multipleTable.toggleRowSelection(t, true)
          })
        })
      });
    },
    getSummaries(param) {
      console.log(param)
      const { columns, data } = param;
      const sums = new Array(columns.length).map(v => '');
      const index = sums.length - 1
      sums[index - 1] = this.$t('价税合计大写')
      const t = data.map(v => v.total).reduce((prev, curr) => {
        return parseFloat(prev) + parseFloat(curr);
      }, 0)
      sums[index] = this.convertCurrency(t)
      return sums;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
    },
    submitForm(addType) {
      this.$refs.form.validate ((valid)=>{
        if (valid) {
          this.$refs.forms.validate((val) => {
            if (val) {
              const params = {...this.form}
              params.addType = addType
              if (this.list && this.list.length > 0) {
                params.payableReqVOList = [...this.list]
              }else{
                this.$modal.msgError(this.$t('请选择供应商未付款项'));
                return
              }
              if(!params.supplierBankAccount){
                this.$modal.msgError(this.$t('请选择供应商银行账号'));
                return
              }
              if (this.id && this.id !== '0') {
                updatePayment(params).then(res => {
                  this.$modal.msgSuccess(this.$t('申请成功'));
                  this.$router.back();
                })
              } else {
                createPayment(params).then(res => {
                  this.$modal.msgSuccess(this.$t('新增成功'));
                  this.$router.back();
                })
              }
            }
          })
        }
      })
    },
    submitDraft() {
      this.$refs.form.validate ((valid)=>{
        if (valid) {
          const params = {...this.form}
          if (this.list && this.list.length > 0) {
            params.payableReqVOList = [...this.list]
          }else{
            this.$modal.msgError(this.$t('请选择供应商未付款项'));
            return
          }
          if(!params.supplierBankAccount){
            this.$modal.msgError(this.$t('请选择供应商银行账号'));
            return
          }
          if (this.id && this.id !== '0') {
            updatePayment(params).then(res => {
              this.$modal.msgSuccess(this.$t('修改成功'));
              this.$router.back();
            })
          } else {
            createPayment(params).then(res => {
              this.$modal.msgSuccess(this.$t('新增成功'));
              this.$router.back();
            })
          }
          // console.log(params, '-----params---------')
        }
      })
    },
    selectChangeBank(val){
      this.$forceUpdate()
      var bank = this.bankData.find(item=>item.bankAccount==this.form.supplierBankAccount)
      this.form.supplierBank = bank.bankName
      this.form.supplierBankAccountName = bank.accountName
    },
    selectChange(val) {
      this.bankData = []
      // this.form.supplierBankAccount=''
      if(val){
        getSupplier(val).then((res)=>{
          this.bankData = res.data.bankList
          var bank = this.bankData.find(item=>item.bankAccount==this.form.supplierBankAccount)
          if(this.bankData.length==0||!bank) this.form.supplierBankAccount=''
        })
      }

      const t = this.allSupplier.find(v => v.id == val)

      t && (this.form.supplierName = t.companyZh)
      // t && (this.bankData = t.bankList)
    },
    handleQuery() {
      this.queryParams.page = 1;
      this.getList()
    },
    UStoRMB() {
      return NP.divide(this.currencyList.find(v => v.titleEn === 'USD').huilv, 100).toFixed(6)
    },
    NANtoRMB() {
      return NP.divide(this.currencyList.find(v => v.titleEn === 'NGN').huilv, 100).toFixed(6)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(v => {
        // var rate = NP.divide(this.currencyList.find(vs => vs.id === v.currencyId).huilv, 100).toFixed(6)
        var rate = this.getRate(v.currencyId)
        return Object.assign(v, { exchangeRate: rate })
      });
    },
    //获取汇率
    getRate(sourceCurrencyId){
      var targetCurrencyId = this.currencyList.find(vs=>vs.titleEn=='RMB').id
      var rate = this.rateList.find(v=>(v.sourceCurrencyId === sourceCurrencyId&&v.targetCurrencyId===targetCurrencyId))
      if(rate) return rate.currencyRate
      return ''
    },
    hiddenDialog() {
      this.open = false;
    },
    saveSelectList() {
      if (this.id && this.id !== '0') {
        this.list = [...this.defaultList, ...this.multipleSelection]
      } else {
        this.list = this.multipleSelection
      }
      this.open = false;
    },
    cancelApproval(){

    },
    convertCurrency(money) {
      //汉字的数字
      var cnNums = new Array('零', this.$t('壹'), this.$t('贰'), this.$t('叁'), this.$t('肆'), this.$t('伍'), this.$t('陆'), this.$t('柒'), this.$t('捌'), '玖');
      //基本单位
      var cnIntRadice = new Array('', this.$t('拾'), this.$t('佰'), '仟');
      //对应整数部分扩展单位
      var cnIntUnits = new Array('', this.$t('万'), this.$t('亿'), '兆');
      //对应小数部分单位
      var cnDecUnits = new Array('角', this.$t('分'), this.$t('毫'), '厘');
      //整数金额时后面跟的字符
      var cnInteger = this.$t('整');
      //整型完以后的单位
      var cnIntLast = this.$t('元');
      //最大处理的数字
      var maxNum = 999999999999999.9999;
      //金额整数部分
      var integerNum;
      //金额小数部分
      var decimalNum;
      //输出的中文金额字符串
      var chineseStr = '';
      //分离金额后用的数组，预定义
      var parts;
      // 传入的参数为空情况
      if(money === '') {
        return '';
      }
      money = parseFloat(money)
      if(money >= maxNum){
        return ''
      }
      // 传入的参数为0情况
      if (money === 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr
      }
      // 转为字符串
      money = money.toString();
      // indexOf 检测某字符在字符串中首次出现的位置 返回索引值（从0 开始） -1 代表无
      if (money.indexOf('.') == -1) {
        integerNum = money;
        decimalNum = ''
      }else{
        parts = money.split('.');
        integerNum = parts[0];
        decimalNum = parts[1].substr(0,4);
      }
      //转换整数部分
      if(parseInt(integerNum,10) > 0){
        let zeroCount  = 0;
        let IntLen = integerNum.length
        for(let i = 0; i < IntLen; i++){
          let n = integerNum.substr(i,1);
          let p = IntLen - i - 1;
          let q = p / 4;
          let 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 != ''){
        let decLen = decimalNum.length;
        for(let i = 0; i <decLen; i++){
          let n = decimalNum.substr(i,1);
          if(n != '0'){
            chineseStr += cnNums[Number(n)] + cnDecUnits[i]
          }
        }
      }
      if(chineseStr == ''){
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      }else if(decimalNum == ''){
        chineseStr += cnInteger;
      }
      return chineseStr
    },
    openDialog() {
      this.getList()
    },
    oninput(num) {
      let str = num
      let len1 = str.substr(0, 1)
      let len2 = str.substr(1, 1)
      //如果第一位是0，第二位不是点，就用数字把点替换掉
      if (str.length > 1 && len1 == 0 && len2 != '.') {
          str = str.substr(1, 1)
      }
      //第一位不能是.
      if (len1 == '.') {
          str = ''
      }
      //限制只能输入一个小数点
      if (str.indexOf('.') != -1) {
          let str_ = str.substr(str.indexOf('.') + 1)
          if (str_.indexOf('.') != -1) {
              str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          } else {
            // if (str_.length > 2) {
            //   str = str.substr(0, str.indexOf('.') + 1) + str_.substr(0, 2)
            // }
          }
      }
      //正则替换
      str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
      // str = str.replace(/\.\d\d\d$/,'') // 小数点后只能输两位
      return str
    }
  },
};
</script>

<style scoped>
.card {
  margin-top: 20px;
}
.dialog-footer {
  padding: 40px;
}
.card-title {
  font-size: 18px;
  font-weight: bold;
}
  .bpm-title{
    font-size: 20px;
    font-weight: bold;
    color:#666;
    margin:20px 0;
  }
</style>
