<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <div class="tab-header webtop">
        <div>{{ viewTitle }}</div>
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="submit()">提交
          </el-button>
          <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <div class="listconadd">
        <el-form ref="form_obj" :model="formobj" :rules="rules" label-position="top" class="formadd">
          <el-row style="border-top: 1px solid #e0e3eb">
            <el-col :span="4" class="tleftb">
              <span>申请部门</span>
            </el-col>
            <el-col :span="4">
              <el-form-item>
                <span>{{ formobj.createDept }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>申请人</span>
            </el-col>
            <el-col :span="4">
              <el-form-item>
                <span>{{ formobj.createByName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>申请日期</span>
            </el-col>
            <el-col :span="4">
              <el-form-item>
                <span>{{ formobj.createDate }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span><span class="icon">*</span>销售部门</span>
            </el-col>
            <el-col :span="4" class="trightb">
              <el-form-item prop="staffDeptName">
                <el-select v-model="formobj.staffDeptName" placeholder="请选择" :disabled="forbidden" @change="changeStaffDept" filterable>
                  <el-option v-for="item in staffDept_list" :key="item.orgDeptSid" :label="item.orgDeptName" :value="item.orgDeptName"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span><span class="icon">*</span>销售专员</span>
            </el-col>
            <el-col :span="4" class="trightb">
              <el-form-item prop="staffName">
                <el-select v-model="formobj.staffName" placeholder="请选择" :disabled="forbidden" @change="changeStaff" filterable>
                  <el-option v-for="item in staff_list" :key="item.staffSid" :label="item.staffName" :value="item.staffName"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span><span class="icon">*</span>开票单位</span>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="purchaseSystemName">
                <el-select v-model="formobj.purchaseSystemName" placeholder="请选择" :disabled="forbidden" @change="changePurchase" filterable clearable>
                  <el-option v-for="item in purchase_list" :key="item.deptSid" :label="item.purchaseSystemName" :value="item.purchaseSystemName"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span><span class="icon">*</span>收款方式</span>
            </el-col>
            <el-col :span="4" class="trightb">
              <el-form-item prop="collectionTypeValue">
                <el-select v-model="formobj.collectionTypeValue" placeholder="请选择" :disabled="forbidden" @change="changeCollectionType" filterable clearable>
                  <el-option v-for="item in receiptType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span><span class="icon">*</span>收款金额(元)</span>
            </el-col>
            <el-col :span="4" class="trightb">
              <el-form-item prop="collectionMoney">
                <el-input v-model="formobj.collectionMoney" @keyup.native="UpNumber" @keydown.native="UpNumber" :disabled="forbidden" @change="changeCollectionMoney" placeholder="" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span><span class="icon">*</span>收款日期</span>
            </el-col>
            <el-col :span="4" class="trightb">
              <el-form-item prop="collectionDate">
                <el-date-picker value-format="yyyy-MM-dd" v-model="formobj.collectionDate" :disabled="forbidden" clearable type="date" style="width: 93%" placeholder="请选择"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-show="formobj.collectionTypeKey === '03' || formobj.collectionTypeKey === '05'">
            <el-col :span="4" class="tleftb balanceStyle">
              <span><span class="icon">*</span>收款银行账号</span>
            </el-col>
            <el-col :span="4" class="tlineheightb">
              <el-form-item>
                <el-select v-model="formobj.collectionBankNum" placeholder="请选择" :disabled="forbidden" @change="changeCollectionBankNum" filterable clearable>
                  <el-option v-for="item in collectionBankNum_list" :key="item.accountSid" :label="item.bankAccount" :value="item.bankAccount"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb balanceStyle">
              <span>收款账户名称</span>
            </el-col>
            <el-col :span="4" class="tlineheightb">
              <el-form-item>
                <span>{{ formobj.receivingName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb balanceStyle">
              <span>收款银行</span>
            </el-col>
            <el-col :span="4" class="tlineheightb">
              <el-form-item>
                <span>{{ formobj.collectionBank }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span><span class="icon">*</span>付款方名称</span>
            </el-col>
            <el-col :span="4" class="trightb">
              <el-form-item prop="payerName">
                <el-input v-model="formobj.payerName" :disabled="forbidden" placeholder="" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span v-show="formobj.collectionTypeKey === '03' || formobj.collectionTypeKey === '05'"><span class="icon">*</span>付款账号后4位</span>
            </el-col>
            <el-col :span="4" class="trightb">
              <el-form-item>
                <el-input v-model="formobj.payAccount" v-show="formobj.collectionTypeKey === '03' || formobj.collectionTypeKey === '05'" :disabled="forbidden" maxlength="4" placeholder="" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span v-show="formobj.collectionTypeKey === '03' || formobj.collectionTypeKey === '05'">付款银行</span>
            </el-col>
            <el-col :span="4" class="trightb">
              <el-form-item>
                <el-input v-model="formobj.payBank" v-show="formobj.collectionTypeKey === '03' || formobj.collectionTypeKey === '05'" :disabled="forbidden" placeholder="" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span>备注</span>
            </el-col>
            <el-col :span="20" class="trightb">
              <el-form-item>
                <el-input v-model="formobj.remarks" :disabled="forbidden" style="width: 70%" placeholder="" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="tleftb">
              <span>打款凭证</span>
            </el-col>
            <el-col :span="8" class="trightb">
              <el-form-item>
                <Upload v-show="forbidden !== true" style="float:left;" ref="remit" @handleSuccess="remitAdd" @handleRemove="remitRemove" />
                <span v-show="forbidden == true" v-for="(item, index) in list1" :key="index">{{ item.name }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>汇款确认书</span>
            </el-col>
            <el-col :span="8" class="trightb">
              <el-form-item>
                <Upload style="float:left;" ref="remittance" @handleSuccess="remittanceAdd" @handleRemove="remittanceRemove" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" style="padding: 0px">
              <el-form ref="listQueryform" :inline="true" :model="listQuery" class="tab-header">
                <el-form-item label="合同编号:">
                  <el-input v-model="listQuery.contractNo" size="mini" placeholder="" style="width: 110px" clearable/>
                </el-form-item>
                <el-form-item label="客户名称:">
                  <el-input v-model="listQuery.customerName" size="mini" placeholder="" style="width: 100px" clearable/>
                </el-form-item>
                <el-form-item label="联系电话:">
                  <el-input v-model="listQuery.customerPhone" size="mini" placeholder="" style="width: 140px" clearable/>
                </el-form-item>
                <el-form-item label="车架号:">
                  <el-input v-model="listQuery.vinNo" size="mini" placeholder="" style="width: 140px" clearable/>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div style="display: flex;flex-direction: row;justify-content: space-between;align-items: center">
                <div style="padding-left: 20%">
                  <el-button type="primary" size="mini" @click="handleFilter">查询</el-button>
                  <el-button type="primary" size="mini" @click="handReset">重置</el-button>
                  <el-button type="primary" size="mini" @click="handleSelect">选择已认款项</el-button>
                </div>
                <div>
                  <span >余额:</span><el-input v-model="balance" placeholder="" style="width: 120px" readonly/>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <div>
                <div class="tableTitle">应收未收款款项明细</div>
                <el-table border :key="overduereceivableKey" width="100%" :data="overduereceivable_list">
                  <el-table-column fixed label="操作" align="center" width="80">
                    <template slot-scope="scope">
                      <el-button type="primary" size="small" @click="handAdd(scope.row)">添加</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column label="合同编号" align="center" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.contractNo }}
                    </template>
                  </el-table-column>
                  <el-table-column label="车架号" align="center" width="90">
                    <template slot-scope="scope">
                      {{ scope.row.VIN }}
                    </template>
                  </el-table-column>
                  <el-table-column label="客户/电话" align="center" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.customerName }} {{ scope.row.customerPhone }}
                    </template>
                  </el-table-column>
                  <el-table-column label="付款" align="center" width="70">
                    <template slot-scope="scope">
                      {{ scope.row.payType }}
                    </template>
                  </el-table-column>
                  <el-table-column label="应收金额" align="center" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.reveivableMoney }}
                    </template>
                  </el-table-column>
                  <el-table-column label="应收项目" align="center" width="90">
                    <template slot-scope="scope">
                      {{ scope.row.receivablesName }}
                    </template>
                  </el-table-column>
                  <el-table-column label="当前应收" align="center" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.currentReceivableMoney }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
            <el-col :span="14">
              <div>
                <div class="tableTitle">已选款项明细</div>
                <el-table border :key="selectedreceivableKey" width="100%" :data="formobj.finSelectedReceivablesDetaileds">
                  <el-table-column fixed label="操作" align="center" width="70">
                    <template slot-scope="scope">
                      <el-button type="danger" size="small" @click="handDelete(scope.row)">移除</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column label="合同编号" align="center" width="95">
                    <template slot-scope="scope">
                      {{ scope.row.contractNo }}
                    </template>
                  </el-table-column>
                  <el-table-column label="车架号" align="center" width="90">
                    <template slot-scope="scope">
                      {{ scope.row.VIN }}
                    </template>
                  </el-table-column>
                  <el-table-column label="客户/电话" align="center" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.customerName }} {{ scope.row.customerPhone }}
                    </template>
                  </el-table-column>
                  <el-table-column label="付款" align="center" width="70">
                    <template slot-scope="scope">
                      {{ scope.row.payType }}
                    </template>
                  </el-table-column>
                  <el-table-column label="应收项目" align="center" width="90">
                    <template slot-scope="scope">
                      {{ scope.row.receivablesName }}
                    </template>
                  </el-table-column>
                  <el-table-column label="当前应收" align="center" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.currentReceivableMoney }}
                    </template>
                  </el-table-column>
                  <el-table-column label="认款金额" align="center" width="130">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.subscriptionMoney" @input="changeMoney(scope.row)" @keyup.native="UpNumber" @keydown.native="UpNumber" @change="changeSubscriptionMoney" placeholder="" clearable/>
                    </template>
                  </el-table-column>
                  <el-table-column label="剩余应收" align="center" width="100">
                    <template slot-scope="scope">
                      <span>{{ scope.row.surplusReceivable }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="认款申请日期" align="center" width="120">
                    <template slot-scope="scope">
                      <span>{{ scope.row.subscriptionDate }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <amountpledged v-show="viewState == 2" ref="divSelect" @doback="resetState" @backData="backData"/>
  </div>
</template>

<script>
import { save, listAll, fetchDetailBySid } from '@/api/anruifinmanagement/paymentConfirmation.js'
import Upload from '@/components/uploadFile/filesUpload' // 上传文件
import { selAccountByOrgSid, typeValues, fetchDetailsByUseOrgSid, getOrgSidByPath, selectOrgList2 } from '@/api/jichuxinxi/dictcommons'
import amountpledged from '../paymentConfirmation/relation/amountpledged'

export default {
  name: 'DaiShouKuanAdd',
  components: {
    Upload,
    amountpledged
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      dialogStatus: '',
      overduereceivableKey: 0,
      selectedreceivableKey: 1,
      staffDept_list: [],
      staff_list: [],
      receiptBank_list: [],
      collectionBankNum_list: [],
      receiptType_list: [],
      overduereceivable_list: [],
      purchase_list: [],
      forbidden: false,
      list1: [],
      list2: [],
      formobj: {
        sid: '',
        createDept: '',
        createDeptSid: '',
        createDate: '',
        createByName: '',
        staffSid: '',
        collectionDate: '',
        collectionBank: '',
        collectionBankKey: '',
        collectionBankNum: '',
        collectionBankNumKey: '',
        collectionTypeKey: '',
        collectionTypeValue: '',
        payerName: '',
        collectionMoney: '',
        paymentVoucherUrl: '',
        remittanceConfirmationUrl: '',
        balance: '',
        useOrgSid: '',
        userSid: '',
        receivingName: '',
        payBank: '',
        payAccount: '',
        accountSid: '',
        purchaseSystemName: '',
        purchaseSystemSid: '',
        orgPath: '',
        staffName: '',
        staffUserSid: '',
        staffDeptName: '',
        staffDeptSid: '',
        finSelectedReceivablesDetaileds: [],
        paymentVoucherAppendixs: [],
        remittanceConfirmationAppendixs: []
      },
      listQuery: {
        contractNo: '',
        customerName: '',
        customerPhone: '',
        sids: [],
        createBySid: '',
        vinNo: '',
        orgPath: '',
        state: '',
        purchaseSystemSid: '',
        staffDeptSid: ''
      },
      rules: {
        collectionMoney: [{ required: true, message: '收款金额不能为空', trigger: 'blur' }],
        collectionDate: [{ required: true, message: '收款日期不能为空', trigger: 'change' }],
        collectionTypeValue: [{ required: true, message: '收款方式不能为空', trigger: 'change' }],
        payerName: [{ required: true, message: '付款方不能为空', trigger: 'blur' }],
        purchaseSystemName: [{ required: true, message: '采购系统不能为空', trigger: 'change' }],
        staffDeptName: [{ required: true, message: '销售部门不能为空', trigger: 'change' }],
        staffName: [{ required: true, message: '销售专员不能为空', trigger: 'change' }]
      },
      submitdisabled: false,
      balance: '', // 余额
      balanceCopy: '' // 计算余额时使用(针对已选应收款项明细表中认款金额多次输入导致余额计算错误)
    }
  },
  methods: {
    // 获取制单日期
    newDate() {
      let date = new Date()
      let year = date.getFullYear() // 年
      let month = date.getMonth() + 1 // 月
      let day = date.getDate() // 日
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      this.formobj.createDate = year + '-' + month + '-' + day
      this.formobj.collectionDate = year + '-' + month + '-' + day
    },
    UpNumber(e) {
      e.target.value = e.target.value.replace(/[^\d.-]/g, '') // 清除“数字”和“.”"-"以外的字符
      e.target.value = e.target.value.replace(/^00/, '0.') // 开头不能有两个0
      e.target.value = e.target.value.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      e.target.value = e.target.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.') // 只保留第一个-
      e.target.value = e.target.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      if (e.target.value.indexOf('.') < 0 && e.target.value !== '') {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        console.log(e.target.value)
        e.target.value = parseFloat(e.target.value)
      }
    },
    DataDictionary() {
      typeValues({ type: 'receiptBank' }).then((res) => {
        if (res.code === '200') {
          this.receiptBank_list = res.data
        }
      })
      typeValues({ type: 'customerPayType' }).then((res) => {
        if (res.code === '200') {
          this.receiptType_list = res.data
        }
      })
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          fetchDetailsByUseOrgSid(res.data).then((resp) => {
            if (resp.success) {
              this.purchase_list = resp.data
            }
          })
        }
      })
      selectOrgList2({ userSid: window.sessionStorage.getItem('userSid'), orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.staffDept_list = res.data
        }
      })
    },
    changeStaffDept(value) {
      const choose = this.staffDept_list.filter((item) => item.orgDeptName === value)
      this.formobj.staffDeptSid = choose[0].orgDeptSid
      this.staff_list = choose[0].staffinfoVoList
    },
    changeStaff(value) {
      const choose = this.staff_list.filter((item) => item.staffName === value)
      this.formobj.staffUserSid = choose[0].userSid
      this.listQuery.createBySid = choose[0].userSid
    },
    changeCollectionBankNum(value) {
      let aa = null
      this.collectionBankNum_list.forEach((e) => {
        if (e.bankAccount === value) {
          aa = {
            accountSid: e.accountSid,
            accountName: e.accountName,
            depositBank: e.depositBank,
            bankAccount: e.bankAccount
          }
        }
      })
      this.formobj.accountSid = aa.accountSid
      this.formobj.collectionBankNum = aa.bankAccount
      this.formobj.receivingName = aa.accountName
      this.formobj.collectionBank = aa.depositBank
    },
    changePurchase(value) {
      if (this.formobj.staffName === '') {
        this.formobj.purchaseSystemName = ''
        this.$message({ showClose: true, type: 'error', message: '请先选择销售专员' })
        return
      }
      const choose = this.purchase_list.filter((item) => item.purchaseSystemName === value)
      this.formobj.purchaseSystemSid = choose[0].deptSid
      this.getlist()
    },
    changeCollectionType(value) {
      let aa = null
      this.receiptType_list.forEach((e) => {
        if (e.dictKey === value) {
          aa = {
            name: e.dictValue,
            value: e.dictKey
          }
        }
      })
      this.formobj.collectionTypeValue = aa.name
      this.formobj.collectionTypeKey = aa.value
      if (this.formobj.collectionTypeKey === '03' || this.formobj.collectionTypeKey === '05') {
        selAccountByOrgSid({ userSid: window.sessionStorage.getItem('userSid'), orgPath: window.sessionStorage.getItem('defaultOrgPath'), collectionTypeKey: this.formobj.collectionTypeKey }).then((resp) => {
          if (resp.success) {
            this.collectionBankNum_list = resp.data
          }
        })
      }
    },
    changeCollectionMoney() {
      if (this.dialogStatus === '') {
        this.balance = this.formobj.collectionMoney
        this.balanceCopy = this.formobj.collectionMoney
      }
    },
    changeMoney(row) {
      if (row.subscriptionMoney !== '') {
        row.surplusReceivable = parseFloat(row.currentReceivableMoney) - parseFloat(row.subscriptionMoney)
      } else {
        row.surplusReceivable = ''
      }
    },
    changeSubscriptionMoney() {
      let subscriptionMoney = '0'
      for (var i = 0; i < this.formobj.finSelectedReceivablesDetaileds.length; i++) {
        if (this.formobj.finSelectedReceivablesDetaileds[i].subscriptionMoney === '') {
          subscriptionMoney = '1'
          return
        }
      }
      if (subscriptionMoney === '0') {
        this.calculateBalance()
      }
    },
    // 计算余额
    calculateBalance() {
      var list = []
      for (var b = 0; b < this.formobj.finSelectedReceivablesDetaileds.length; b++) {
        list.push(this.formobj.finSelectedReceivablesDetaileds[b].subscriptionMoney)
      }
      var sumNum = 0
      for (var i = 0; i < list.length; i++) {
        // 替换掉字符串中的千分位分隔符并相加
        sumNum += Number(list[i].replace(/,/g, ''))
      }
      // 将总数四舍五入
      var f1 = Math.round(sumNum * 100) / 100
      // 转化为字符串
      var strNum = f1.toString()
      // 将整数和小数点分割
      var rs = strNum.indexOf('.')
      if (rs < 0) {
        rs = strNum.length
        strNum += '.'
      }
      while (strNum.length <= rs + 2) {
        strNum += '0'
      }
      var resNum = strNum.replace(/\d+/, function(n) {
        return n.replace(/(\d)(?=(\d{3})+$)/g, function(u) {
          return u
        })
      })
      this.balance = parseFloat(this.balanceCopy) - parseFloat(resNum)
    },
    getlist() {
      if (this.formobj.purchaseSystemName === '') {
        this.$message({ showClose: true, type: 'error', message: '请选择采购系统' })
        return
      }
      if (this.formobj.staffDeptName === '') {
        this.$message({ showClose: true, type: 'error', message: '请选择销售部门' })
        return
      }
      this.listQuery.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      this.listQuery.purchaseSystemSid = this.formobj.purchaseSystemSid
      this.listQuery.staffDeptSid = this.formobj.staffDeptSid
      this.listQuery.state = '1'
      listAll(this.listQuery).then((res) => {
        if (res.success) {
          this.overduereceivable_list = res.data
        }
      })
    },
    handleFilter() {
      this.getlist()
    },
    handReset() {
      this.listQuery = {
        contractNo: '',
        customerName: '',
        customerPhone: '',
        sids: [],
        createBySid: '',
        vinNo: '',
        orgPath: '',
        state: '',
        purchaseSystemSid: '',
        staffDeptSid: ''
      }
      this.getlist()
    },
    handleSelect() {
      if (this.formobj.collectionMoney === '') {
        this.$message({ showClose: true, type: 'error', message: '请先填写收款金额' })
        return
      }
      if (this.formobj.purchaseSystemName === '') {
        this.$message({ showClose: true, type: 'error', message: '请先选择采购系统' })
        return
      }
      this.viewState = 2
      this.$refs['divSelect'].showData(this.formobj.finSelectedReceivablesDetaileds, this.formobj.purchaseSystemSid, this.formobj.staffUserSid)
    },
    backData(val) {
      this.viewState = 1
      var nowDate = new Date()
      var date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        day: nowDate.getDate()
      }
      var dayDate = date.year + '-' + (date.month >= 10 ? date.month : '0' + date.month) + '-' + (date.day >= 10 ? date.day : '0' + date.day)
      for (var i = 0; i < val.length; i++) {
        this.formobj.finSelectedReceivablesDetaileds.push({
          createByName: window.sessionStorage.getItem('name'),
          contractSid: val[i].contractSid,
          contractNo: val[i].contractNo,
          customerSid: val[i].customerSid,
          customerName: val[i].customerName,
          VIN: val[i].VIN,
          useOrgSid: '',
          customerPhone: val[i].customerPhone,
          receivablesName: val[i].receivablesName,
          currentReceivableMoney: val[i].currentReceivableMoney,
          lastSubscriptionMoney: '',
          subscriptionMoney: '',
          surplusReceivable: '',
          subscribedOf: val[i].subscribedOf,
          subscriptionDate: dayDate,
          collSid: '',
          receivablesSid: val[i].receivablesSid,
          payType: val[i].payType,
          payTypeKey: val[i].payTypeKey,
          sid: val[i].sid
        })
      }
    },
    resetState() {
      this.viewState = 1
    },
    showAdd() {
      this.DataDictionary()
      this.newDate()
      this.viewTitle = '【新建】收款申请'
      this.formobj.createByName = window.sessionStorage.getItem('name')
      this.formobj.staffSid = window.sessionStorage.getItem('staffSid')
      this.formobj.createDept = window.sessionStorage.getItem('defaultOrgPathName').substring(window.sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1)
      this.formobj.createDeptSid = window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1)
      this.formobj.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
    },
    showEdit(row) {
      this.DataDictionary()
      this.viewTitle = '【编辑】收款申请'
      this.dialogStatus = 'edit'
      fetchDetailBySid(row.sid).then(resp => {
        if (resp.success) {
          this.formobj = resp.data
          this.balance = this.formobj.balance
          this.balanceCopy = this.formobj.balance
          this.getlist()
          this.forbidden = true
          if (this.formobj.paymentVoucherAppendixs.length > 0) {
            for (var i = 0; i < this.formobj.paymentVoucherAppendixs.length; i++) {
              this.list1.push({
                  name: this.formobj.paymentVoucherAppendixs[i].fileName
                }
              )
            }
          }
          if (this.formobj.remittanceConfirmationAppendixs.length > 0) {
            for (var b = 0; b < this.formobj.remittanceConfirmationAppendixs.length; b++) {
              this.list2.push({
                  name: this.formobj.remittanceConfirmationAppendixs[b].fileName
                }
              )
            }
          }
          this.formobj.finSelectedReceivablesDetaileds = []
          this.$nextTick(() => {
            this.$refs['remit'].show(this.list1)
            this.$refs['remittance'].show(this.list2)
            this.$refs['form_obj'].clearValidate()
          })
        }
      }).catch(e => {
        this.formobj = row
      })
    },
    remitAdd(item) {
      var arrayList = []
      arrayList = item.data
      this.formobj.paymentVoucherAppendixs.push({
        createBySid: window.sessionStorage.getItem('userSid'),
        name: window.sessionStorage.getItem('name'),
        fileName: arrayList.sourceFileName.substr(0, arrayList.sourceFileName.lastIndexOf('.')),
        fileType: arrayList.sourceFileName.substr(arrayList.sourceFileName.lastIndexOf('.')),
        linkSid: '',
        attachType: '',
        fileSize: arrayList.size,
        filePath: arrayList.fullUrl
      })
    },
    remitRemove(item) {
      this.formobj.paymentVoucherAppendixs.forEach((e, index) => {
        if (item.name.indexOf(e.fileName) === 0) {
          this.formobj.paymentVoucherAppendixs.splice(index, 1)
        }
      })
    },
    remittanceAdd(item) {
      var arrayList = []
      arrayList = item.data
      this.formobj.remittanceConfirmationAppendixs.push({
        createBySid: window.sessionStorage.getItem('userSid'),
        name: window.sessionStorage.getItem('name'),
        fileName: arrayList.sourceFileName.substr(0, arrayList.sourceFileName.lastIndexOf('.')),
        fileType: arrayList.sourceFileName.substr(arrayList.sourceFileName.lastIndexOf('.')),
        linkSid: '',
        attachType: '',
        fileSize: arrayList.size,
        filePath: arrayList.fullUrl
      })
    },
    remittanceRemove(item) {
      this.formobj.remittanceConfirmationAppendixs.forEach((e, index) => {
        if (item.name.indexOf(e.fileName) === 0) {
          this.formobj.remittanceConfirmationAppendixs.splice(index, 1)
        }
      })
    },
    handAdd(row) {
      if (this.formobj.collectionMoney === '') {
        this.$message({ showClose: true, type: 'error', message: '请先填写收款金额' })
      } else {
        var nowDate = new Date()
        var date = {
          year: nowDate.getFullYear(),
          month: nowDate.getMonth() + 1,
          day: nowDate.getDate()
        }
        var dayDate = date.year + '-' + (date.month >= 10 ? date.month : '0' + date.month) + '-' + (date.day >= 10 ? date.day : '0' + date.day)
        this.formobj.finSelectedReceivablesDetaileds.push({
          createByName: window.sessionStorage.getItem('name'),
          contractSid: row.contractSid,
          contractNo: row.contractNo,
          customerSid: row.customerSid,
          customerName: row.customerName,
          VIN: row.VIN,
          useOrgSid: '',
          customerPhone: row.customerPhone,
          receivablesName: row.receivablesName,
          currentReceivableMoney: row.currentReceivableMoney,
          lastSubscriptionMoney: '',
          subscriptionMoney: '',
          surplusReceivable: '',
          subscribedOf: row.subscribedOf,
          subscriptionDate: dayDate,
          collSid: '',
          receivablesSid: row.sid,
          payType: row.payType,
          payTypeKey: row.payTypeKey,
          sid: row.sid
        })
        this.listQuery.sids.push(row.sid)
        this.getlist()
      }
    },
    handDelete(row) {
      this.formobj.finSelectedReceivablesDetaileds.splice(this.formobj.finSelectedReceivablesDetaileds.indexOf(row), 1)
      this.calculateBalance()
      if (row.subscribedOf == 0) {
        this.listQuery.sids.splice(this.listQuery.sids.indexOf(row.sid), 1)
        this.getlist()
      }
    },
    submit() {
      if ((this.formobj.collectionTypeKey === '03' || this.formobj.collectionTypeKey === '05') && this.formobj.collectionBankNum === '') {
        this.$message({ showClose: true, type: 'error', message: '收款银行账号不能为空' })
        return
      }
      if ((this.formobj.collectionTypeKey === '03' || this.formobj.collectionTypeKey === '05') && this.formobj.payAccount === '') {
        this.$message({ showClose: true, type: 'error', message: '付款账号后4位不能为空' })
        return
      }
      if (this.formobj.paymentVoucherAppendixs.length > 0) {
        var paymentVoucherUrl_list = []
        for (var i = 0; i < this.formobj.paymentVoucherAppendixs.length; i++) {
          paymentVoucherUrl_list.push(this.formobj.paymentVoucherAppendixs[i].filePath)
        }
        this.formobj.paymentVoucherUrl = paymentVoucherUrl_list.join(',')
      }
      if (this.formobj.remittanceConfirmationAppendixs.length > 0) {
        var remittanceConfirmationUrl_list = []
        for (var b = 0; b < this.formobj.remittanceConfirmationAppendixs.length; b++) {
          remittanceConfirmationUrl_list.push(this.formobj.remittanceConfirmationAppendixs[b].filePath)
        }
        this.formobj.remittanceConfirmationUrl = remittanceConfirmationUrl_list.join(',')
      }
      this.formobj.userSid = window.sessionStorage.getItem('userSid')
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          save(this.formobj).then((resp) => {
            if (resp.success) {
              this.$message({ showClose: true, type: 'success', message: resp.msg })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        sid: '',
        createDept: '',
        createDeptSid: '',
        createDate: '',
        createByName: '',
        staffSid: '',
        collectionDate: '',
        collectionBank: '',
        collectionBankKey: '',
        collectionBankNum: '',
        collectionBankNumKey: '',
        collectionTypeKey: '',
        collectionTypeValue: '',
        payerName: '',
        collectionMoney: '',
        paymentVoucherUrl: '',
        remittanceConfirmationUrl: '',
        balance: '',
        useOrgSid: '',
        userSid: '',
        receivingName: '',
        payBank: '',
        payAccount: '',
        accountSid: '',
        purchaseSystemName: '',
        purchaseSystemSid: '',
        orgPath: '',
        staffName: '',
        staffUserSid: '',
        staffDeptName: '',
        staffDeptSid: '',
        finSelectedReceivablesDetaileds: [],
        paymentVoucherAppendixs: [],
        remittanceConfirmationAppendixs: []
      }
      this.listQuery = {
        contractNo: '',
        customerName: '',
        customerPhone: '',
        sids: [],
        createBySid: '',
        vinNo: '',
        orgPath: '',
        state: '',
        purchaseSystemSid: '',
        staffDeptSid: ''
      }
      this.list1 = []
      this.list2 = []
      this.forbidden = false
      this.$nextTick(() => {
        this.$refs['remit'].show(this.list1)
        this.$refs['remittance'].show(this.list2)
      })
      this.balance = ''
      this.balanceCopy = ''
      this.dialogStatus = ''
      this.submitdisabled = false
      this.$refs['form_obj'].resetFields()
      this.$emit('doback')
    }
  }
}
</script>

<style scoped>
.titwu {
  padding: 0;
}
.tableTitle{
  border: 1px solid #e0e3eb;
  line-height: 42px;
  text-align: center;
  font-weight: bold;
  font-size: 18px;
}
.balanceStyle {
  line-height: 15px !important;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.tlineheightb {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}
/deep/ .tlineheightb .el-form-item .el-form-item__content {
  line-height: 15px !important;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}
</style>
