<template>
  <div class="divide-account-edit">
    <el-form ref="ruleForm" :key="key" :model="ruleForm" :rules="rules" label-width="150px" label-position="top" class="rule-form-orange">
      <cy-info-title>基础信息</cy-info-title>
      <el-form-item label="企业名称">
        <el-input v-model="ledgerAccountBasicInfo.customerName" disabled placeholder="请输入企业名称" />
      </el-form-item>
      <el-form-item label="标签">
        <el-radio-group v-model="ledgerAccountBasicInfo.label" disabled>
          <el-radio :label="0">下游回款</el-radio>
          <el-radio :label="1">上游回购</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分账单号">
        <el-input v-model="ledgerAccountBasicInfo.ledgerNumber" disabled placeholder="请输入分账单号" />
      </el-form-item>
      <el-form-item label="入账类型">
        <el-input v-model="ledgerAccountBasicInfo.ledgerTypeDict.name" disabled placeholder="请输入入账类型" />
      </el-form-item>
      <el-form-item label="入账金额">
        <cy-amount-input v-model="ledgerAccountBasicInfo.ledgerAmount" disabled placeholder="请输入入账金额" />
      </el-form-item>
      <el-form-item label="入账日期">
        <el-input v-model="ledgerAccountBasicInfo.ledgerDate" disabled placeholder="请输入入账日期" />
      </el-form-item>
      <template v-if="ledgerAccountBasicInfo.ledgerTypeDict.code === 'entryType_bills_discounted'">
        <cy-info-title>贴现费用</cy-info-title>
        <el-form-item label="贴现费用">
          <cy-amount-input v-model="ledgerAccountBasicInfo.discountCharge" disabled placeholder="请输入贴现费用" />
        </el-form-item>
        <el-form-item label="说明" class="two-form-item">
          <el-input v-model="ruleForm.remark" placeholder="请输入说明" :disabled="disabled" />
        </el-form-item>
      </template>

      <cy-info-title>
        货款分配
        <div v-if="!disabled" slot="right">
          <el-button type="text" @click="oneCalc('click')">一键计算</el-button>
          <el-button type="primary" @click="financingGoods">选择已融资货物</el-button>
          <el-button type="primary" @click="acceptanceGoods">选择已验收货物</el-button>
        </div>
      </cy-info-title>
      <el-form-item label="货款金额" prop="name" style="width: 100%">
        <div slot="label">
          <span>货款金额</span>
          <span class="form-label">(特别提醒：如一键计算后的分账结果不满足需求，请与风控经理沟通，调整还款方式为手动生成后进行收放款计划变更，再进行分账。)</span>
        </div>
        <cy-amount-input v-model="goodsMoney" disabled placeholder="请输入货款金额" />
      </el-form-item>
      <el-form-item style="width: 100%; margin-top: 20px">
        <cy-comm-table
          :columns="loanColumns"
          :data="loanTableData"
          :count="0"
        />
        <div class="calc-box">
          <span>逾期利息合计：{{ handlerMoneyEmpty(getloanCalc.financingOverdueInterest) }}</span>
          <span>融资利息合计：{{ handlerMoneyEmpty(getloanCalc.financingInterest) }}</span>
          <span>融资管理费合计：{{ handlerMoneyEmpty(getloanCalc.financingManagementFee) }}</span>
          <span>融资本金合计：{{ handlerMoneyEmpty(getloanCalc.financingPrincipal) }}</span>
          <span>计提金额合计：{{ handlerMoneyEmpty(getloanCalc.accrualAmount) }}</span>
          <span>平台利润合计：{{ handlerMoneyEmpty(getloanCalc.platformProfit) }}</span>
          <span>质保金合计：{{ handlerMoneyEmpty(getloanCalc.guarantee) }}</span>
          <span>实退金额合计：{{ handlerMoneyEmpty(getloanCalc.discountAmount) }}</span>
          <span>应退利息合计：{{ handlerMoneyEmpty(getloanCalc.refundInterest) }}</span>
          <span>应退管理费合计：{{ handlerMoneyEmpty(getloanCalc.refundManagementFee) }}</span>
        </div>
      </el-form-item>

      <cy-info-title>
        关联收款账号
        <!-- <div slot="right">
          <el-button type="primary" @click="paymentAccountClick">一键获取收款账号</el-button>
        </div> -->
      </cy-info-title>
      <el-form-item style="width: 100%; margin-top: 20px">
        <cy-comm-table
          :columns="accountColumns"
          :data="accountTableData"
          :count="0"
        />
      </el-form-item>

      <cy-info-title>回款合计</cy-info-title>
      <el-form-item label="货款金额" class="one-form-item">
        <cy-amount-input v-model="goodsMoney" disabled placeholder="请输入货款金额" />
      </el-form-item>
      <el-form-item v-if="ledgerAccountBasicInfo.ledgerTypeDict.code === 'entryType_bills_discounted'" label="贴现费用" class="one-form-item">
        <cy-amount-input v-model="ledgerAccountBasicInfo.discountCharge" disabled placeholder="请输入贴现费用" />
      </el-form-item>
    </el-form>
    <div v-if="!disabled" class="submit-btn">
      <el-button @click="() => { this.$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="financingGoodsRef" title="选择融资货物" width="70%">
      <financing-goods ref="financingGoods" :select-data="loanTableData" :table-data="financingGoodsList"></financing-goods>
      <div class="submit-btn">
        <el-button @click="() => { this.$refs.financingGoodsRef.show = false }">取消</el-button>
        <el-button type="primary" @click="financingSubmit">提交</el-button>
      </div>
    </cy-dialog>

    <cy-dialog ref="acceptanceGoodsRef" title="选择验收货物" width="70%">
      <acceptance-goods ref="acceptanceGoods" :select-data="loanTableData" :table-data="acceptanceGoodsList"></acceptance-goods>
      <div class="submit-btn">
        <el-button @click="() => { this.$refs.acceptanceGoodsRef.show = false }">取消</el-button>
        <el-button type="primary" @click="acceptanceSubmit">提交</el-button>
      </div>
    </cy-dialog>

    <cy-dialog ref="viewIncomePlan" title="查看收支计划" width="60%">
      <view-income-plan :income-plan-data="incomePlanData"></view-income-plan>
      <div class="submit-btn">
        <el-button @click="() => { this.$refs.viewIncomePlan.show = false }">取消</el-button>
      </div>
    </cy-dialog>
  </div>
</template>

<script>
import { getDetails, getFinancingGoods, getAcceptanceGoods, getCalculateAssign, getSupplierBankInfoList, accountSubmit } from '@/api/divideAccountsManage/divideAccountsManage'
import { handleMoney } from '@/utils'
export default {
  name: 'DivideAccountEdit',
  components: {
    FinancingGoods: () => import('./components/FinancingGoods'),
    AcceptanceGoods: () => import('./components/AcceptanceGoods'),
    ViewIncomePlan: () => import('./components/ViewIncomePlan')
  },
  data() {
    return {
      ruleForm: {
        remark: ''
      },
      rules: {},
      key: 0,
      loanTableData: [],
      accountTableData: [],
      accountColumns: [
        {
          label: '供应商名称',
          prop: 'supplierName'
        },
        {
          label: '所属银行',
          prop: 'bankName'
        },
        {
          label: '账户名称',
          prop: 'accountName'
        },
        {
          label: '账号',
          prop: 'accountNumber'
        }
      ],
      detailsInfo: {},
      financingGoodsList: [],
      acceptanceGoodsList: [],
      ledgerAccountBasicInfo: {
        ledgerTypeDict: {}
      },
      selectFinancingGoodsList: [],
      selectAcceptanceGoodsList: [],
      oneCalcStatus: false,
      incomePlanData: {},
      disabled: false
    }
  },
  computed: {
    goodsMoney() {
      return this.loanTableData.length ? this.loanTableData.reduce((total, item) => {
        return total * 1 + item.currentAssignAmount * 1
      }, 0) : '0.00'
    },
    getloanCalc() {
      const obj = {
        financingOverdueInterest: 0,
        financingInterest: 0,
        financingManagementFee: 0,
        financingPrincipal: 0,
        accrualAmount: 0,
        platformProfit: 0,
        guarantee: 0,
        discountAmount: 0,
        refundInterest: 0,
        refundManagementFee: 0
      }
      this.loanTableData.forEach(item => {
        obj.financingOverdueInterest += Number(item.financingOverdueInterest)
        obj.financingInterest += Number(item.financingInterest)
        obj.financingManagementFee += Number(item.financingManagementFee)
        obj.financingPrincipal += Number(item.financingPrincipal)
        obj.accrualAmount += Number(item.accrualAmount)
        obj.platformProfit += Number(item.platformProfit)
        obj.guarantee += Number(item.guarantee)
        obj.discountAmount += Number(item.discountAmount)
        obj.refundInterest += Number(item.refundInterest)
        obj.refundManagementFee += Number(item.refundManagementFee)
      })
      return obj
    },
    loanColumns() {
      return [
        {
          label: '序号',
          index: true
        },
        {
          label: '结算单号',
          prop: 'settlementNumber',
          showTooltip: true,
          width: '120'
        },
        {
          label: '业务编号',
          prop: 'businessNumber',
          showTooltip: true,
          width: '120'
        },
        {
          label: '保理合同编号',
          width: '110',
          prop: 'contractNo',
          showTooltip: true
        },
        {
          label: '支用批次',
          prop: 'quotaDisburseBatch',
          showTooltip: true
        },
        {
          label: '供应商名称',
          prop: 'supplierName',
          width: '150',
          showTooltip: true
        },
        {
          label: '销售总价',
          prop: 'salesTotalPrice',
          showTooltip: true,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.salesTotalPrice) }</span>
          }
        },
        {
          label: '采购总价',
          prop: 'purchaseTotalPrice',
          showTooltip: true,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.purchaseTotalPrice) }</span>
          }
        },
        {
          label: '待分配金额',
          prop: 'toAssignedAmount',
          width: '150',
          showTooltip: true,
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.toAssignedAmount) }</span>
          }
        },
        {
          label: '放款日期结算日期',
          prop: 'loanDate',
          showTooltip: true,
          width: '80'
        },
        {
          label: '待回款金额',
          prop: 'returnedAmount',
          width: '120',
          showTooltip: true,
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.returnedAmount) }</span>
          }
        },
        {
          label: '本次分配金额',
          prop: 'currentAssignAmount',
          width: '160',
          render: (h, row) => {
            return <cy-amount-input disabled={this.disabled} v-model={row.currentAssignAmount} placeholder='请输入本次分配金额' onBlur={ this.oneCalc }></cy-amount-input>
          }
        },
        {
          label: '是否计提(履约保证金)',
          prop: 'accrual',
          showTooltip: true,
          width: '100',
          render: (h, row) => {
            return <el-select v-model={ row.accrual } disabled={this.disabled} onChange={() => { this.oneCalc('click') }} placeholder='请选择是否计提'>
              <el-option label='是' value={true}></el-option>
              <el-option label='否' value={false}></el-option>
            </el-select>
          }
        },
        {
          label: '是否分配逾期利息',
          prop: 'hasAssignOverdueInterest',
          showTooltip: true,
          width: '80',
          render: (h, row) => {
            return <el-select disabled={this.disabled} v-model={ row.hasAssignOverdueInterest } onChange={() => { this.oneCalc('click') }} placeholder='请选择是否'>
              <el-option label='是' value={true}></el-option>
              <el-option label='否' value={false}></el-option>
            </el-select>
          }
        },
        {
          label: '逾期利息',
          prop: 'financingOverdueInterest',
          showTooltip: true,
          show: this.oneCalcStatus,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.financingOverdueInterest) }</span>
          }
        },
        {
          label: '是否分配融资利息和管理费',
          prop: 'hasAssignInterest',
          showTooltip: true,
          width: '110',
          render: (h, row) => {
            return <el-select disabled={this.disabled} v-model={ row.hasAssignInterest } onChange={() => { this.oneCalc('click') }} placeholder='请选择是否'>
              <el-option label='是' value={true}></el-option>
              <el-option label='否' value={false}></el-option>
            </el-select>
          }
        },
        {
          label: '融资利息',
          prop: 'financingInterest',
          showTooltip: true,
          show: this.oneCalcStatus,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.financingInterest) }</span>
          }
        },
        // {
        //   label: '是否分配管理费',
        //   prop: 'hasAssignManagementFee',
        //   showTooltip: true,
        //   width: '80',
        //   render: (h, row) => {
        //     return <el-select disabled={this.disabled} v-model={ row.hasAssignManagementFee } onChange={() => { this.oneCalc('click') }} placeholder='请选择是否'>
        //       <el-option label='是' value={true}></el-option>
        //       <el-option label='否' value={false}></el-option>
        //     </el-select>
        //   }
        // },
        {
          label: '融资管理费',
          prop: 'financingManagementFee',
          width: '120',
          showTooltip: true,
          show: this.oneCalcStatus,
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.financingManagementFee) }</span>
          }

        },
        {
          label: '融资本金',
          prop: 'financingPrincipal',
          showTooltip: true,
          show: this.oneCalcStatus,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.financingPrincipal) }</span>
          }
        },
        {
          label: '履约保证金',
          prop: 'accrualAmount',
          showTooltip: true,
          show: this.oneCalcStatus,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.accrualAmount) }</span>
          }
        },
        {
          label: '平台利润',
          prop: 'platformProfit',
          showTooltip: true,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.platformProfit) }</span>
          }
        },
        {
          label: '质保金',
          prop: 'guarantee',
          showTooltip: true,
          show: this.oneCalcStatus,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.guarantee) }</span>
          }
        },
        {
          label: '实退金额',
          prop: 'discountAmount',
          showTooltip: true,
          show: this.oneCalcStatus,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.discountAmount) }</span>
          }
        },
        {
          label: '应退利息',
          prop: 'refundInterest',
          showTooltip: true,
          show: this.oneCalcStatus,
          width: '120',
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.refundInterest) }</span>
          }
        },
        {
          label: '应退管理费',
          prop: 'refundManagementFee',
          width: '120',
          showTooltip: true,
          show: this.oneCalcStatus,
          render: (h, row) => {
            return <span> { this.handlerMoneyEmpty(row.refundManagementFee) }</span>
          }
        },
        {
          label: '操作',
          width: '100',
          render: (h, row, index) => {
            const btnList = []
            if (!this.disabled) {
              btnList.push({ msg: '删除', icon: 'el-icon-delete', category: 'delete' })
            }
            if (row.contractNo && row.quotaDisburseBatch) {
              btnList.unshift({ msg: '查看放款计划', icon: 'iconfont icon-Magnifier', category: 'see' })
            }
            const options = btnList.map(item => {
              return (
                <el-tooltip class='item' effect='dark' content={item.msg} placement='top'>
                  <span class='table-icon-box'>
                    <i class={item.icon} onClick={() => { this.handlerOperate(item.category, row, index) }}></i>
                  </span>
                </el-tooltip>
              )
            })
            return <div>{ options }</div>
          }
        }
      ]
    }
  },
  created() {
    this.getDetails()
    const { type } = this.$route.query
    if (type === 'see') {
      this.disabled = true
    }
  },
  methods: {
    getDetails() {
      const { id } = this.$route.params
      getDetails({ id }).then((data) => {
        const { ledgerAccountBasicInfo, goodsAssignList, supplierBankCardInfoList } = data.data
        this.ledgerAccountBasicInfo = ledgerAccountBasicInfo
        this.loanTableData = goodsAssignList
        this.accountTableData = supplierBankCardInfoList
        if (goodsAssignList.length) {
          this.oneCalcStatus = true
        }
      })
    },
    getFinancingGoodsList() {
      const { label, enterpriseId } = this.ledgerAccountBasicInfo
      const params = {
        label,
        enterpriseId
      }
      getFinancingGoods(params).then((data) => {
        this.financingGoodsList = data.data
      })
    },
    getAcceptanceGoodsList() {
      const { label, enterpriseId } = this.ledgerAccountBasicInfo
      const params = {
        label,
        enterpriseId
      }
      getAcceptanceGoods(params).then((data) => {
        this.acceptanceGoodsList = data.data
      })
    },

    handlerOperate(type, row, index) {
      if (type === 'see') {
        this.incomePlanData = row
        this.$refs.viewIncomePlan.show = true
      } else if (type === 'delete') {
        this.loanTableData.splice(index, 1)
        this.paymentAccountClick()
      }
    },
    financingGoods() {
      this.getFinancingGoodsList()
      this.$refs.financingGoodsRef.show = true
    },
    financingSubmit() {
      const data = this.$refs.financingGoods.getData()
      if (!data.length) return this.$message.warning('请选择已融资货物')
      this.selectFinancingGoodsList = data
      this.selectGoodsMapData()
      this.$refs.financingGoodsRef.show = false
    },

    async acceptanceGoods() {
      this.$refs.acceptanceGoodsRef.show = true
      this.getAcceptanceGoodsList()
    },
    acceptanceSubmit() {
      const data = this.$refs.acceptanceGoods.getData()
      if (!data.length) return this.$message.warning('请选择已验收货物')
      this.selectAcceptanceGoodsList = data
      this.selectGoodsMapData()
      this.$refs.acceptanceGoodsRef.show = false
    },
    selectGoodsMapData() {
      this.loanTableData = [
        ...this.selectFinancingGoodsList,
        ...this.selectAcceptanceGoodsList
      ]
      this.loanTableData = this.loanTableData.map(item => {
        if (!item.accrual) item.accrual = false
        if (!item.hasAssignInterest) item.hasAssignInterest = true
        if (!item.hasAssignManagementFee) item.hasAssignManagementFee = true
        if (!item.hasAssignOverdueInterest) item.hasAssignOverdueInterest = true
        return item
      })
      this.paymentAccountClick()
    },
    handlerMoneyEmpty(val) {
      return val || Number(val === 0) ? handleMoney(val) : val
    },
    oneCalc(type) {
      return new Promise((resolve, reject) => {
        if (!this.loanTableData.length) {
          this.$message.error('请先选择货物')
          return
        }
        const currentAssignAmountStatus = this.loanTableData.every(item => item.currentAssignAmount)
        if (!currentAssignAmountStatus) {
          if (type === 'click') {
            this.$message.error('请填写本次分配金额')
          }
          return
        }
        const params = {
          Loading: true,
          ledgerAccountBasicInfo: this.ledgerAccountBasicInfo,
          goodsAssignList: this.loanTableData
          // this.loanTableData.map(item => {
          //   delete item.financingOverdueInterestList
          //   delete item.financingInterestList
          //   delete item.financingManagementFeeList
          //   return item
          // })
        }
        getCalculateAssign(params).then(({ data }) => {
          const { goodsAssignList } = data
          // const goodsAssignListDeep = goodsAssignList.map(item => {
          //   item.financingOverdueInterestList = this.handlerGoodsData(item.financingOverdueInterest)
          //   item.financingInterestList = this.handlerGoodsData(item.financingInterest)
          //   item.financingManagementFeeList = this.handlerGoodsData(item.financingManagementFee)
          //   return item
          // })
          this.loanTableData = JSON.parse(JSON.stringify(goodsAssignList))
          this.oneCalcStatus = true
          resolve()
        })
      })
    },

    // 处理货物数据
    handlerGoodsData(val) {
      return Number(val) === 0 ? [] : [{ label: val, value: val }, { label: 0, value: 0 }]
    },
    // 一键获取收款账户
    paymentAccountClick() {
      if (!this.loanTableData.length) {
        this.accountTableData = []
        // this.$message.error('请先选择货物')
        return
      }
      getSupplierBankInfoList(this.loanTableData).then(({ data }) => {
        this.accountTableData = data
      })
    },
    submit(type) {
      var params = {
        Loading: true,
        ledgerAccountBasicInfo: {
          ...this.ledgerAccountBasicInfo,
          goodsAmount: this.goodsMoney
        },
        goodsAssignList: this.loanTableData,
        supplierBankCardInfoList: this.accountTableData,
        submit: type === 'submit'
      }
      if (type === 'submit') {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.oneCalc('click').then(() => {
              params.goodsAssignList = this.loanTableData
              accountSubmit(params).then(() => {
                this.$message.success('提交成功')
                this.$router.go(-1)
              })
            })
          } else {
            return false
          }
        })
      } else {
        accountSubmit(params).then(() => {
          this.$message.success('暂存成功')
          this.$router.go(-1)
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.divide-account-edit {
  .form-label {
    color: red;
    margin-left: 10px;
  }
  .calc-box {
    width: 100%;
    padding: 5px 10px;
    background: #F5F6F6;
    // margin-top: 20px;
    & > span {
      margin-right: 10px;
    }
  }
}
</style>

<style lang="scss">
.divide-account-edit {
  .el-icon-delete {
    color: #FE7D0B;
    font-size: 16px;
  }
}

</style>
