<template>
  <div class="apply-financing">
    <cy-info-title>基础信息</cy-info-title>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="120px"
      class="rule-form-orange"
    >
      <el-form-item label="项目名称" prop="businessNumber">
        <el-select
          v-model="ruleForm.businessNumber"
          placeholder="请选择项目名称"
          :disabled="disabled"
          @change="projectChange"
        >
          <el-option
            v-for="item in projectList"
            :key="item.businessNumber"
            :label="item.projectName"
            :value="item.businessNumber"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="核心企业名称" prop="coreEnterpriseName">
        <el-input v-model="ruleForm.coreEnterpriseName" disabled placeholder="请输入核心企业名称" />
      </el-form-item>
      <el-form-item label="供应商（主体）名称" prop="mainEnterpriseName">
        <el-input v-model="ruleForm.mainEnterpriseName" disabled placeholder="请输入供应商（主体）名称" />
      </el-form-item>
      <el-form-item label="贸易平台" prop="platformName">
        <el-input v-model="ruleForm.platformName" disabled placeholder="请输入贸易平台" />
      </el-form-item>
      <el-form-item label="业务编号">
        <el-input v-model="ruleForm.businessNumber" disabled placeholder="请输入业务编号" />
      </el-form-item>
      <el-form-item label="合同名称（采购）" prop="purchContractName">
        <el-input v-model="ruleForm.purchContractName" disabled placeholder="请输入合同名称（采购）" />
      </el-form-item>
      <el-form-item label="合同编号（采购）" prop="purchContractNumber">
        <el-input v-model="ruleForm.purchContractNumber" disabled placeholder="请输入合同编号（采购）" />
      </el-form-item>
      <cy-info-title>
        <span>
          底层货物
          <span class="statistics">数量合计：{{ bottomCalc.numTotal }} </span>
          <span class="statistics">销售总价合计：{{ bottomCalc.salesTotal }}</span>
          <span class="statistics">采购总价合计：{{ bottomCalc.purchaseTotal }}</span>
        </span>
        <div slot="right">
          <el-button v-if="!disabled" type="text" @click="selectGoods">选择已验收的货物</el-button>
        </div>
      </cy-info-title>
      <div style="width: 100%; margin-top: 20px;">
        <cy-comm-table
          ref="commTable"
          :columns="columns"
          :data="tableData"
          :count="0"
          row-key="fid"
        />
      </div>
      <cy-info-title style="margin-top: 20px;">网价附件</cy-info-title>
      <el-form-item class="form-required" label="网价附件" prop="desc" style="width: 100%">
        <cy-upload
          ref="fileStorage"
          :upload-params="{
            fileType: 'financing_net_price_file'
          }"
          :disabled="disabled"
          :file-data="fileStorageList"
          :upload-from-orange-status="true"
          placeholder="请上传附件"
        />
      </el-form-item>
      <cy-info-title>
        <span>
          底层信息
          <span class="statistics">数量合计：{{ bottomInfoCalc.numTotal }} </span>
          <span class="statistics">应收账款金额合计：{{ bottomInfoCalc.accountsTotal }} </span>
          <span class="statistics">应收账款净额合计：{{ bottomInfoCalc.netAccounts }}</span>
        </span>
      </cy-info-title>
      <div style="width: 100%; margin-top: 20px;">
        <cy-comm-table
          ref="commTable"
          :columns="columnsInfo"
          :data="tableDataInfo"
          :count="0"
          row-key="fid"
        />
      </div>
      <cy-info-title style="margin-top: 20px;">联系信息</cy-info-title>
      <el-form-item label="保理申请人联系人" prop="applicantContact">
        <el-input v-model="ruleForm.applicantContact" :disabled="disabled" placeholder="请输入保理申请人联系人" />
      </el-form-item>
      <el-form-item label="保理申请人联系电话" prop="applicantContactNumber">
        <el-input v-model="ruleForm.applicantContactNumber" :disabled="disabled" placeholder="请输入保理申请人联系电话" />
      </el-form-item>
      <el-form-item label="保理申请人联系人邮箱" prop="applicantContactEmail">
        <el-input v-model="ruleForm.applicantContactEmail" :disabled="disabled" placeholder="请输入保理申请人联系人邮箱" />
      </el-form-item>
      <cy-info-title style="margin-top: 20px;">账户信息</cy-info-title>
      <el-form-item label="是否为江苏苏商银行" prop="smb">
        <el-radio-group v-model="ruleForm.smb" :disabled="disabled" @change="smbChange">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="保理申请人银行名称"
        prop="applicantDesignatedBankName"
        :rules="[
          { required: ruleForm.smb === 0, message: '请输入保理申请人银行名称', trigger: 'blur' }
        ]"
      >
        <el-input v-model="ruleForm.applicantDesignatedBankName" :disabled="disabled" placeholder="请输入保理申请人银行名称" />
      </el-form-item>
      <el-form-item label="保理申请人指定账户户名" prop="applicantDesignatedAccountName">
        <el-input v-model="ruleForm.applicantDesignatedAccountName" :disabled="disabled" placeholder="请输入保理申请人指定账户户名" />
      </el-form-item>
      <el-form-item label="保理申请人指定账户" prop="applicantDesignatedAccount">
        <el-input v-model="ruleForm.applicantDesignatedAccount" :disabled="disabled" placeholder="请输入保理申请人指定账户" />
      </el-form-item>
      <el-form-item label="保理申请人指定账户开户行" prop="applicantDesignatedBank">
        <el-input v-model="ruleForm.applicantDesignatedBank" :disabled="disabled" placeholder="请输入保理申请人指定账户开户行" />
      </el-form-item>
    </el-form>
    <div v-if="!disabled" class="submit-btn">
      <el-button @click="$router.go(-1)">关闭</el-button>
      <el-button type="primary" @click="submit('temp')">暂存</el-button>
      <el-button type="primary" @click="submit('submit')">提交</el-button>
    </div>
    <cy-dialog ref="dialog" title="选择已验收的货物">
      <div v-loading="goodsLoading">
        <cy-comm-table
          ref="goodsTable"
          :columns="goodsColumns"
          :data="goodsTableData"
          :count="0"
        />
        <div class="submit-btn">
          <el-button @click="$refs.dialog.show = false">关闭</el-button>
          <el-button type="primary" @click="goodsSubmit">提交</el-button>
        </div>
      </div>
    </cy-dialog>
  </div>
</template>

<script>
import { getProjectInfo, getFinishProCon, getApplicantInfo, chooseToAcceptTheGoods, generateReceivable, applySubmit, getDetailsInfo } from '@/api/myFinancing'
import { validMail } from '@/utils/validate'
import { deduplicateArray, getUuid } from '@/utils'
export default {
  name: 'ApplyFinancing',
  props: {
    detailsInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    var validMailData = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入保理申请人联系人邮箱'))
      } else {
        if (!validMail(value)) {
          callback(new Error('请输入正确的保理申请人联系人邮箱'))
        } else {
          callback()
        }
      }
    }
    return {
      ruleForm: {
        businessNumber: '',
        coreEnterpriseId: '',
        coreEnterpriseName: '',
        mainEnterpriseId: '',
        mainEnterpriseName: '',
        platformId: '',
        platformName: '',
        purchContractId: '',
        purchContractName: '',
        purchContractNumber: '',
        applicantContact: '',
        applicantContactNumber: '',
        applicantContactEmail: '',
        applicantDesignatedAccountName: '',
        applicantDesignatedAccount: '',
        applicantDesignatedBank: '',
        smb: '',
        applicantDesignatedBankName: ''
      },
      rules: {
        businessNumber: [
          { required: true, message: '请选择项目名称', trigger: 'change' }
        ],
        applicantContact: [
          { required: true, message: '请输入保理申请人联系人', trigger: 'blur' }
        ],
        applicantContactNumber: [
          { required: true, message: '请输入保理申请人联系电话', trigger: 'blur' }
        ],
        applicantContactEmail: [
          { required: true, message: '请输入保理申请人联系人邮箱', trigger: 'blur' },
          { validator: validMailData, trigger: 'blur' }

        ],
        applicantDesignatedAccountName: [
          { required: true, message: '请输入保理申请人指定账户户名', trigger: 'blur' }
        ],
        applicantDesignatedAccount: [
          { required: true, message: '请输入保理申请人指定账户', trigger: 'blur' }
        ],
        applicantDesignatedBank: [
          { required: true, message: '请输入保理申请人指定账户开户行', trigger: 'blur' }
        ],
        smb: [
          { required: true, message: '请选择是否为江苏苏商银行', trigger: 'change' }
        ]
      },
      fileStorageList: [],
      bottomCalc: {
        numTotal: 0,
        salesTotal: 0,
        purchaseTotal: 0
      },
      oldTableData: [],
      tableData: [],
      columns: [
        {
          type: 'expand',
          render: (h, row, index) => {
            const columnsDeep = this.columns.toSpliced(0, 2)
            columnsDeep.unshift({
              label: '序号',
              prop: 'tOrder',
              width: '60'
            })
            return <cy-comm-table
              columns={ columnsDeep }
              data={row.children}
              count={0}
              rowKey='tid'
            />
          }
        },
        {
          label: '序号',
          prop: 'fOrder',
          width: '60'
        },
        {
          label: '验收单货物编号',
          prop: 'acceptanceGoodsNumber',
          showTooltip: true,
          width: 150
        },
        {
          label: '预计结算日期',
          showTooltip: true,
          prop: 'expectedSettlementDate',
          width: 150
        },
        {
          label: '验收日期',
          prop: 'acceptanceDate',
          width: 120
        },
        {
          label: '货物名称',
          prop: 'goodsName',
          width: 120
        },
        {
          label: '厂家',
          prop: 'goodsFactory',
          showTooltip: true
        },
        {
          label: '型号',
          prop: 'goodsType'
        },
        {
          label: '单位',
          prop: 'goodsUnit'
        },
        {
          label: '货物数量',
          prop: 'goodsQuantity'
        },
        {
          label: '参考价格',
          prop: 'referencePrice'
        },
        {
          label: '浮动价格',
          prop: 'floatingPrice'
        },
        {
          label: '销售单价（元）',
          prop: 'salesPrice',
          width: '140'
        },
        {
          label: '销售总价（元）',
          prop: 'salesTotalPrice',
          width: '140'
        },
        {
          label: '销售质保金（元）',
          prop: 'salesGuaranteeMoney',
          width: '140'
        },
        {
          label: '采购单价（元）',
          prop: 'purchasePrice',
          width: '140'
        },
        {
          label: '采购总价（元）',
          prop: 'purchaseTotalPrice',
          width: '140'
        },
        {
          label: '采购质保金（元）',
          prop: 'purchGuaranteeMoney',
          width: '140'
        }
      ],
      bottomInfoCalc: {
        numTotal: 0,
        accountsTotal: 0,
        netAccounts: 0
      },
      oldTableDataInfo: [],
      tableDataInfo: [],
      columnsInfo: [
        {
          type: 'expand',
          render: (h, row, index) => {
            const columnsDeep = this.columnsInfo.toSpliced(0, 2)
            columnsDeep.unshift({
              label: '序号',
              prop: 'tOrder',
              width: '60'
            })
            return <cy-comm-table
              columns={ columnsDeep }
              data={row.children}
              count={0}
              rowKey='tid'
            />
          }
        },
        {
          label: '序号',
          prop: 'fOrder',
          width: '60'
        },
        {
          label: '验收单货物编号',
          prop: 'acceptanceGoodsNumber',
          showTooltip: true,
          width: 150
        },
        {
          label: '预计结算日期',
          showTooltip: true,
          prop: 'expectedSettlementDate',
          width: 150
        },
        {
          label: '验收日期',
          prop: 'acceptanceDate',
          width: 120
        },
        {
          label: '货物名称',
          prop: 'goodsName',
          width: 120
        },
        {
          label: '厂家',
          prop: 'goodsFactory',
          showTooltip: true
        },
        {
          label: '型号',
          prop: 'goodsType'
        },
        {
          label: '单位',
          prop: 'goodsUnit'
        },
        {
          label: '货物数量',
          prop: 'goodsQuantity'
        },
        {
          label: '应收账款金额（元）',
          prop: 'accountsReceivableAmount',
          width: '150'
        },
        {
          label: '应收账款净额（元）',
          prop: 'netAccountsReceivableAmount',
          width: '150'
        }
      ],
      projectList: [],
      goodsColumns: [
        {
          type: 'selection',
          single: false
        },
        {
          label: '序号',
          index: true
        },
        {
          label: '验收单货物编号',
          prop: 'acceptanceNumber',
          showTooltip: true
        },
        {
          label: '结算单编号',
          showTooltip: true,
          prop: 'settlementNumber'
        },
        {
          label: '预计/结算日期',
          prop: 'expectedSettlementDate'
        },
        {
          label: '验收状态',
          prop: 'acceptanceStatus'
        },
        {
          label: '结算状态',
          prop: 'settlementStatus'
        },
        {
          label: '验收数量',
          prop: 'acceptanceNumTotal'
        },
        {
          label: '结算总价(元)',
          prop: 'settlementAmountTotal',
          type: 'num'
        }
      ],
      goodsTableData: [],
      goodsLoading: false,
      disabled: false
    }
  },
  watch: {
    detailsInfo: {
      handler(val) {
        if (val) {
          const { type } = this.$route.query
          if (type === 'see') {
            this.initData(val)
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getProject()
    const { type } = this.$route.query
    if (type === 'see') {
      this.disabled = true
    } else {
      this.getDetails()
    }
  },
  methods: {
    initData(data) {
      const { financingBasicInfo, financingGoodsInfoList, financingAccountsReceivableInfoList, financingApplicantInfo, fileStorageDOList } = data
      this.oldTableData = financingGoodsInfoList
      this.tableData = this.handlerGoodsFormat(financingGoodsInfoList)
      const { applicantContact,
        applicantContactNumber,
        applicantContactEmail,
        applicantDesignatedAccountName,
        applicantDesignatedAccount,
        applicantDesignatedBank,
        applicantDesignatedBankName,
        smb
      } = financingApplicantInfo
      this.ruleForm = {
        ...financingBasicInfo,
        applicantContact,
        applicantContactNumber,
        applicantContactEmail,
        applicantDesignatedAccountName,
        applicantDesignatedAccount,
        applicantDesignatedBank,
        applicantDesignatedBankName,
        smb
      }
      this.fileStorageList = fileStorageDOList
      this.oldTableDataInfo = financingAccountsReceivableInfoList
      this.tableDataInfo = this.handlerGoodsFormat(financingAccountsReceivableInfoList)
      this.getGoodsCalc(financingGoodsInfoList)
      this.getReceivableCalc(financingAccountsReceivableInfoList)
    },
    getDetails() {
      const { id } = this.$route.params
      if (id === 'add') return
      getDetailsInfo({ id }).then(({ data }) => {
        this.initData(data)
      })
    },
    getProject() {
      getProjectInfo().then(({ data }) => {
        this.projectList = data
      })
    },
    projectChange(val) {
      getFinishProCon({ businessNumber: val }).then(({ data }) => {
        this.ruleForm = {
          ...this.ruleForm,
          ...data
        }
      })
      this.getApplican()
      this.tableData = []
      this.tableDataInfo = []
    },
    getApplican() {
      getApplicantInfo({ businessNumber: this.ruleForm.businessNumber }).then(({ data }) => {
        const {
          applicantContact,
          applicantContactNumber,
          applicantContactEmail,
          applicantDesignatedAccountName,
          applicantDesignatedAccount,
          applicantDesignatedBank } = data
        this.ruleForm = {
          ...this.ruleForm,
          applicantContact,
          applicantContactNumber,
          applicantContactEmail,
          applicantDesignatedAccountName,
          applicantDesignatedAccount,
          applicantDesignatedBank
        }
      })
    },
    selectGoods() {
      this.goodsLoading = true
      this.$refs.dialog.show = true
      const { businessNumber, supplierId, mainEnterpriseId } = this.ruleForm
      const params = {
        supplierId: mainEnterpriseId,
        businessNumber
      }
      chooseToAcceptTheGoods(params).then(({ data }) => {
        this.goodsTableData = data.rows
        var selectRow = []
        this.tableData.forEach(item => {
          selectRow.push(this.goodsTableData.find(row => row.acceptanceNumber === item.acceptanceGoodsNumber))
        })
        this.$refs.goodsTable.toggleRowSelection(selectRow)
        this.goodsLoading = false
      })
    },
    goodsSubmit() {
      const multipleList = this.$refs.goodsTable.multipleSelection
      const list = deduplicateArray(multipleList, 'signConfirm')
      if (!multipleList.length) {
        this.$message.warning('请选择已验收的货物')
        return
      }
      // if (list.length < multipleList.length) {
      //   this.$message.warning('已签署和未签署验收单不能同时选择')
      //   return
      // }
      if (list.length && !multipleList.every(el => el.signConfirm === list[0].signConfirm)) {
        this.$message.warning('已签署和未签署验收单不能同时选择')
        return
      }
      this.getMultipleList(multipleList)

      this.$refs.dialog.show = false
    },
    // 底层货物
    getMultipleList(multipleList) {
      this.oldTableData = []
      multipleList.forEach(item => {
        const { acceptanceNumber, settlementNumber, expectedSettlementDate, acceptanceGoodInfos } = item
        const list = acceptanceGoodInfos.map(item => {
          item.acceptanceNumber = acceptanceNumber
          item.settlementNumber = settlementNumber
          item.expectedSettlementDate = expectedSettlementDate
          return item
        })
        this.oldTableData.push(...list)
      })
      this.getGoodsCalc(this.oldTableData)
      this.getReceivable(this.oldTableData)
      this.tableData = this.handlerGoodsFormat(this.oldTableData)
    },
    // 底层货物计算
    getGoodsCalc(list) {
      this.bottomCalc = {
        numTotal: 0,
        salesTotal: 0,
        purchaseTotal: 0
      }
      list.forEach(item => {
        const { numTotal, salesTotal, purchaseTotal } = this.bottomCalc
        this.bottomCalc = {
          numTotal: (Number(numTotal) + Number(item.goodsQuantity)).toFixed(4),
          salesTotal: (Number(salesTotal) + Number(item.salesTotalPrice)).toFixed(4),
          purchaseTotal: (Number(purchaseTotal) + Number(item.purchaseTotalPrice)).toFixed(4)
        }
      })
    },
    // 生成底层
    getReceivable(list) {
      generateReceivable(list).then(({ data }) => {
        this.oldTableDataInfo = data
        this.tableDataInfo = this.handlerGoodsFormat(data)
        this.getReceivableCalc(data)
      })
    },
    // 底层信息计算
    getReceivableCalc(list) {
      this.bottomInfoCalc = {
        numTotal: 0,
        accountsTotal: 0,
        netAccounts: 0
      }
      list.forEach(item => {
        const { numTotal, accountsTotal, netAccounts } = this.bottomInfoCalc
        this.bottomInfoCalc = {
          numTotal: (Number(numTotal) + Number(item.goodsQuantity)).toFixed(4),
          accountsTotal: (Number(accountsTotal) + Number(item.accountsReceivableAmount)).toFixed(4),
          netAccounts: (Number(netAccounts) + Number(item.netAccountsReceivableAmount)).toFixed(4)
        }
      })
    },
    submit(type) {
      const { applicantContact, applicantContactNumber, applicantContactEmail, applicantDesignatedAccountName, applicantDesignatedAccount, applicantDesignatedBank, smb, applicantDesignatedBankName } = this.ruleForm
      const fileStorageList = this.$refs.fileStorage.getFileLists
      const params = {
        financingBasicInfo: {
          ...this.ruleForm
        },
        financingGoodsInfoList: this.oldTableData,
        financingAccountsReceivableInfoList: this.oldTableDataInfo,
        financingApplicantInfo: {
          applicantContact,
          applicantContactNumber,
          applicantContactEmail,
          applicantDesignatedAccountName,
          applicantDesignatedAccount,
          applicantDesignatedBank,
          smb,
          applicantDesignatedBankName
        },
        fileIds: fileStorageList.map(item => item.id),
        visible: type !== 'temp'
      }
      if (type === 'temp') {
        applySubmit(params).then(() => {
          this.$message.success('暂存成功')
          this.$router.go(-1)
        })
      } else {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (!fileStorageList.length) {
              this.$message.warning('请上传网价附件')
              return
            }
            applySubmit(params).then(() => {
              this.$message.success('提交成功')
              this.$router.go(-1)
            })
          } else {
            return false
          }
        })
      }
    },
    handlerGoodsFormat(arr) {
      let fOrder = 0
      let tOrder = 0
      return Object.values(arr.reduce((acc, cur) => {
        if (!acc[cur.acceptanceGoodsNumber]) {
          fOrder += 1
          tOrder = 0
          acc[cur.acceptanceGoodsNumber] = { ...cur, fid: getUuid(), tid: getUuid(), fOrder, children: [] }
        }
        tOrder += 1
        acc[cur.acceptanceGoodsNumber].children.push({ ...cur, fid: getUuid(), tid: getUuid(), tOrder })
        return acc
      }, {}))
    },
    smbChange(val) {
      if (val) {
        this.ruleForm.applicantDesignatedBankName = '江苏苏商银行'
      } else {
        this.ruleForm.applicantDesignatedBankName = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.apply-financing {
  .statistics {
    color: #FF0000;
    margin-left: 20px;
  }
}

</style>
