<template>
  <div class="accounts-receivable">
    <cy-info-title>应收账款</cy-info-title>
    <div class="table-box header-border-table table-disabled">
      <div v-for="(item, tIndex) in tableData" :key="tIndex">
        <cy-info-title type="left">关联第{{ tIndex + 1 }}笔应收账款</cy-info-title>
        <el-table :data="[item]" row-key="id" :default-expand-all="tIndex === 0" :expand-row-keys="expandsKeys" @row-click="rowClick">
          <el-table-column type="expand">
            <template slot-scope="props">
              <div v-for="(tPItem, tPIndex) in props.row.tradePlanFactoringList" :key="tPIndex" class="table-box">
                <cy-info-title type="left">关联第{{ tIndex + 1 }}笔应收账款 - 第{{ tPIndex + 1 }}笔放款收放款计划</cy-info-title>
                <el-table ref="tradePlanFactoring" :data="tPItem.planFactoringList" @selection-change="handleSelectionChange">
                  <el-table-column v-if="oa" type="selection" width="50" :selectable="selectable" />
                  <el-table-column type="index" label="序号" width="50" />
                  <el-table-column prop="planDate" label="约定日期" width="160" header-align="center">
                    <template slot-scope="{ row }">
                      <el-date-picker
                        v-model="row.planDate"
                        style="width: 100%"
                        type="date"
                        :disabled="disabled || !row.allowedChange"
                        placeholder="请选择约定日期"
                        :picker-options="pickerOptions(row)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="amountType" label="金额类型">
                    <template slot-scope="scope">
                      <el-select
                        v-model="scope.row.amountType"

                        placeholder="请选择金额类型"
                        :disabled="disabled || !scope.row.allowedChange"
                        style="width: 100%"
                        @change="amountCollectionTypeChange({one: tIndex, two: index, three: scope.$index, amountType: scope.row.amountType, paymentCollectionType: scope.row.paymentCollectionType, rowData: scope.row})"
                      >
                        <el-option
                          v-for="cItem in incormeExpenditureType"
                          :key="cItem.id"
                          :label="cItem.name"
                          :value="cItem.id"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column prop="paymentCollectionType" label="收放款类型" width="100">
                    <template slot-scope="scope">
                      <el-select
                        v-model="scope.row.paymentCollectionType"

                        placeholder="请选择收放款类型"
                        :disabled="disabled || !scope.row.allowedChange"
                        style="width: 100%"
                        @change="amountCollectionTypeChange({one: tIndex, two: index, three: scope.$index, amountType: scope.row.amountType, paymentCollectionType: scope.row.paymentCollectionType, rowData: scope.row})"
                      >
                        <el-option
                          v-for="cItem in constant.payCollType"
                          :key="cItem.id"
                          :label="cItem.name"
                          :value="cItem.code"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column prop="amount" label="金额" width="150">
                    <template slot-scope="scope">
                      <div style="display: flex; align-items: center">
                        <span>{{ scope.row.currencyTypeCode }} </span>
                        {{ formatMoney(scope.row.amount) }}
                        <!-- <cy-amount-input
                          v-model="scope.row.amount"
                          placeholder="请输入金额"
                          :disabled="disabled || !scope.row.allowedChange"
                          :clearable="false"
                          @change="amountChange(scope.row, {one: tIndex, two: index, three: scope.$index})"
                        /> -->
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="actualCashFlow" label="实际现金流" width="150">
                    <template slot-scope="{row}">
                      <div style="display: flex; align-items: center">
                        <span>{{ row.currencyTypeCode }} </span>
                        {{ formatMoney(row.actualCashFlow) }}
                        <!-- <cy-amount-input
                          v-model="row.actualCashFlow"
                          placeholder="请输入实际现金流"
                          disabled
                        /> -->
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="actualCashFlow" label="实收/付日期" width="120">
                    <template slot-scope="{row}">
                      <div v-for="(cItem, index) in row.paymentCollectionType === 'pay_coll_payment'? row.loanRecordList : row.collRecordList" :key="index">
                        {{ row.paymentCollectionType === 'pay_coll_payment' ? cItem.thisLoanDate : cItem.actualDate }}
                      </div>
                      <!-- <cy-amount-input
                        v-model="row.actualCashFlow"
                        placeholder="请输入实收/付日期"
                        :disabled="disabled"
                        clearable
                      >
                      </cy-amount-input> -->
                    </template>
                  </el-table-column>
                  <el-table-column prop="actualCashFlow" label="实收/付总金额" width="120">
                    <template slot-scope="{row}">
                      <div v-for="(cItem, index) in row.paymentCollectionType === 'pay_coll_payment'? row.loanRecordList : row.collRecordList" :key="index">
                        {{ row.currencyTypeCode }} {{ row.paymentCollectionType === 'pay_coll_payment' ? formatMoney(cItem.thisLoanAmount) : formatMoney(cItem.actualAmount) }}
                      </div>
                      <!-- <cy-amount-input
                        v-model="row.actualCashFlow"
                        placeholder="请输入实收/付总金额"
                        :disabled="disabled"
                        clearable
                      >
                      </cy-amount-input> -->
                    </template>
                  </el-table-column>
                  <el-table-column prop="receivingSubject" label="收款主体">
                    <template slot-scope="{ row }">
                      <el-select
                        v-if="row.receivingSubject"
                        v-model="row.receivingSubject"

                        placeholder="请选择收款主体"
                        :disabled="disabled || !row.allowedChange"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="cItem in constant.receivingSubjectList"
                          :key="cItem.id"
                          :label="cItem.name"
                          :value="cItem.code"
                        />
                      </el-select>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="overDate" label="宽限到期日" width="100" disabled show-overflow-tooltip />
                  <el-table-column prop="status" label="状态">
                    <template slot-scope="{ row }">
                      {{ row.status }}
                      <!-- <el-select
                        v-model="row.status"

                        placeholder="请选择状态"
                        :disabled="disabled || !row.allowedChange"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="cItem in paymentCollectionPlanStatus(row)"
                          :key="cItem.id"
                          :label="cItem.name"
                          :value="cItem.code"
                        />
                      </el-select> -->
                    </template>
                  </el-table-column>
                  <el-table-column prop="graceType" label="宽限期类型" width="100">
                    <template slot-scope="{ row }">
                      <!-- {{ row.graceType }} -->
                      <!-- <el-select
                        v-model="row.graceType"
                        placeholder="请选择宽限期类型"

                        :disabled="disabled || !row.allowedChange"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="cItem in constant.graceTypeList"
                          :key="cItem.value"
                          :label="cItem.name"
                          :value="cItem.value"
                        />
                      </el-select> -->
                    </template>
                  </el-table-column>
                  <el-table-column v-if="type === 'executeFinancing' && !btnDisabled " label="操作" width="120">
                    <template slot-scope="scope">
                      <template v-if="scope.row.paymentCollectionType === 'pay_coll_collection'">
                        <el-tooltip v-if="isAllocation(scope.row)" effect="dark" content="金额分配" placement="top">
                          <i class="iconfont icon-fenpei" @click="executeFinancingModify(scope.row, 'submit', props.row.id)" />
                        </el-tooltip>
                        <el-tooltip v-if="isCancelAllocation(scope.row)" effect="dark" content="取消分配" placement="top">
                          <i class="iconfont icon-quxiaofenpei" @click="executeFinancingModify(scope.row, 'cancel', props.row.id)" />
                        </el-tooltip>
                        <el-tooltip effect="dark" content="查看金额分配" placement="top">
                          <i class="iconfont icon-fangdajing" @click="executeFinancingModify(scope.row, 'see', props.row.id)" />
                        </el-tooltip>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="type === 'planChange' && !disabled" label="操作" width="60">
                    <template slot-scope="scope">
                      <div style="color: #5AC4FC; cursor: pointer;">
                        <span @click="modifyClick('add', {one: tIndex, two: index, three: scope.$index})">新增</span>
                        <span v-if="scope.row.allowedDelete" @click="modifyClick('delete', {one: tIndex, two: index, three: scope.$index})">删除</span>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="underlyingAssetsNo" label="底层资产编号">
            <template slot-scope="{ row }">
              <el-input
                v-model="row.underlyingAssetsNo"
                placeholder="请输入业务编号"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column prop="tradeReceivablesNumber" label="贸理通底层编号">
            <template slot-scope="{ row }">
              <el-input
                v-model="row.tradeReceivablesNumber"
                placeholder="请输入贸理通底层编号"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column prop="accountReceivableAmount" label="应收账款金额">
            <template slot-scope="{ row }">
              <cy-amount-input
                v-model="row.accountReceivableAmount"
                placeholder="请输入应收账款金额"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column prop="accountReceivableNetAmount" label="应收账款净额">
            <template slot-scope="{row}">
              <cy-amount-input
                v-model="row.accountReceivableNetAmount"
                placeholder="请输入应收账款净额"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column prop="startDate" label="应收账款起始日">
            <template slot-scope="{ row }">
              <el-date-picker
                v-model="row.startDate"
                style="width: 100%"
                type="date"
                disabled
                placeholder="请选择应收账款起始日"
              />
            </template>
          </el-table-column>
          <el-table-column prop="term" label="应收账款期限">
            <template slot-scope="{ row }">
              <el-input
                v-model="row.term"
                placeholder="请输入应收账款期限"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column prop="endDate" label="应收账款到期日">
            <template slot-scope="{ row }">
              <el-date-picker
                v-model="row.endDate"
                style="width: 100%"
                type="date"
                disabled
                placeholder="请选择应收账款起始日"
              />
            </template>
          </el-table-column>
          <el-table-column prop="payAmount" label="本次付款金额">
            <template slot-scope="{row}">
              <cy-amount-input
                v-model="row.payAmount"
                placeholder="请输入本次付款金额"
                disabled
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <cy-dialog ref="allocationDialog" title="金额分配" width="70%" top="15vh">
      <money-allocation ref="moneyAllocation" :allocation-dialog-status="allocationDialogStatus" :amount-allocation-row="amountAllocationRow" @close-dialog="closeDialog" />
    </cy-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { endPickerDate, formatMoney, filterListData, codeChangeName } from '@/utils'
export default {
  components: {
    MoneyAllocation: () => import('./MoneyAllocation')
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    // 用于发票跳转过来，不显示按钮
    btnDisabled: {
      type: Boolean,
      default: false
    },
    oa: {
      type: Boolean,
      default: false
    },
    selectedList: {
      type: Array,
      default: () => []
    },
    receivableInfo: {
      type: Object,
      default: () => {}
    },
    //  type:  planChange: 计划变更  executeFinancing:收放款执行  credit: 征信上报
    type: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tableData: [],
      allocationDialogStatus: '',
      allocationKey: 0,
      ruleForm: {},
      rules: {},
      amountAllocationRow: {},
      expandsKeys: []
    }
  },
  computed: {
    ...mapGetters(['constant']),
    formatMoney() {
      return (val) => {
        return formatMoney(val)
      }
    },
    pickerOptions() {
      return (row) => {
        // 修改后逻辑
        const pickerDate = endPickerDate(row.minChangeDate, row.maxChangeDate, true)

        const { reportDataFlag } = this.ruleForm
        // 上报过征信-手动生成未上报征信
        if (reportDataFlag === 2) {
          return {}
        } else {
          return {
            ...pickerDate
          }
        }
      }
    },
    // 金额类型
    incormeExpenditureType() {
      // 占用公司资金-是-金额类型下拉框没有垫款
      if (this.ruleForm.occupationFlag === 1) {
        return filterListData(this.constant.incormeExpenditureType, 'money_advanced')
      } else {
        return this.constant.incormeExpenditureType
      }
    },
    // 状态
    paymentCollectionPlanStatus() {
      return (row) => {
        const amountType = codeChangeName(this.constant.incormeExpenditureType, row.amountType, 'id', 'code')
        // 金额类型-是-逾期利息-修改范围为已豁免、计划中
        if (amountType === 'overdue_interest') {
          return filterListData(this.constant.paymentCollectionPlanStatus, ['pay_coll_plan_executing', 'pay_coll_plan_overdue', 'pay_coll_plan_part_allocate', 'pay_coll_plan_part_completed', 'pay_coll_plan_overdue_completed', 'pay_coll_plan_notneed_completed', 'pay_coll_plan_deduction', 'pay_coll_plan_deduction_completed', 'pay_coll_plan_completed'])
        } else {
          // 保证金-是-状态下拉框增加抵扣中、抵扣完成
          if (amountType === 'margin') {
            return this.constant.paymentCollectionPlanStatus
          } else {
            return filterListData(this.constant.paymentCollectionPlanStatus, ['pay_coll_plan_deduction', 'pay_coll_plan_deduction_completed'])
          }
        }
      }
    },
    isAllocation() {
      return (row) => {
        if (row.paymentCollectionType === 'pay_coll_collection') {
          if (row.status === 'pay_coll_planning' || row.status === 'pay_coll_plan_part_allocate' || row.status === 'pay_coll_plan_overdue') {
            return true
          } else {
            return false
          }
        }
      }
    },
    isCancelAllocation() {
      return (row) => {
        if (row.paymentCollectionType === 'pay_coll_collection') {
          // row.status?.code === 'pay_coll_plan_part_allocate' || row.status?.code === 'pay_coll_plan_completed' || row.status?.code === 'pay_coll_plan_overdue_completed' || row.status?.code === 'pay_coll_plan_overdue'
          if (row.collRecordList.length) {
            return true
          } else {
            return false
          }
        }
      }
    }
  },
  watch: {
    receivableInfo: {
      handler(newV) {
        if (Object.keys(newV).length) {
          const { tradePlanReceivableList, occupationFlag, reportDataFlag } = JSON.parse(JSON.stringify(newV))
          this.tableData = tradePlanReceivableList.map(item => {
            item.tradePlanFactoringList = item.tradePlanFactoringList.map(tradeItem => {
              tradeItem.planFactoringList = tradeItem.planFactoringList.map(planItem => {
                planItem.amountType = planItem.amountType?.id
                planItem.currencyTypeCode = planItem.currencyType?.code
                planItem.status = planItem.status?.name
                return planItem
              })
              return tradeItem
            })
            return item
          })
          // this.getSelectData(this.selectedList)
          this.ruleForm = {
            occupationFlag,
            reportDataFlag
          }
        }
      },
      immediate: true,
      deep: true
    },
    selectedList: {
      handler(newV) {
        if (newV === undefined) return
        if (newV && newV.length) {
          // console.log(newV, 1111111111111)
          // console.log(this.tableData, 99999)
          // console.log(this.$refs.tradePlanFactoring, 2222)
          // this.getSelectData(newV)
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['payCollType', 'incormeExpenditureType'])
    // this.$store.dispatch('getConstant', ['incormeExpenditureType', 'payCollType', 'receivingSubjectList', 'graceTypeList', 'paymentCollectionPlanStatus'])
  },
  methods: {
    getSelectData(data) {
      if (data && data.length) {
        this.$nextTick(() => {
          this.$refs.tradePlanFactoring.forEach(item => {
            data.forEach(el => {
              setTimeout(() => {
                item.toggleRowSelection(el)
              }, 1000)
            })
          })
        })
      }
    },
    executeFinancingModify(row, type, key) {
      this.allocationDialogStatus = type
      this.$refs.allocationDialog.show = true
      this.expandsKeys = [key]
      this.amountAllocationRow = row
      this.$nextTick(() => {
        if (type === 'submit') {
          this.$refs.allocationDialog.oTitle = '金额分配'
          this.$refs.moneyAllocation.getAmountAllocation(row)
        } else if (type === 'cancel') {
          this.$refs.allocationDialog.oTitle = '取消分配'
          this.$refs.moneyAllocation.getAmountAllocationCancleList(row)
        } else if (type === 'see') {
          this.$refs.allocationDialog.oTitle = '查看金额分配'
          this.$refs.moneyAllocation.amountAllocationCancelSee(row)
        }
      })
    },
    modifyClick(type, orderIndex) {
      const { one, two, three } = orderIndex
      if (type === 'add') {
        // 新增默认状态为计划种
        const currencyType = this.tableData[0].tradePlanFactoringList[0].planFactoringList[0].currencyType
        const obj = {
          planDate: '',
          amountType: '',
          paymentCollectionType: 'pay_coll_collection',
          amount: '',
          actualCashFlow: '',
          receivingSubject: 'debtor',
          overDate: '',
          graceType: 0,
          status: 'pay_coll_planning',
          allowedChange: true,
          allowedDelete: true,
          id: null,
          currencyType: currencyType,
          currencyTypeCode: currencyType.code
        }
        this.tableData[one].tradePlanFactoringList[two].planFactoringList.splice(three + 1, 0, obj)
      } else if (type === 'delete') {
        this.tableData[one].tradePlanFactoringList[two].planFactoringList.splice(three, 1)
        // this.getIrrCalc()
      }
    },
    amountChange(row, orderIndex) {
      const { one, two, three } = orderIndex
      if (row.paymentCollectionType === 'pay_coll_payment') {
        if (Number(row.amount) < 0) {
          this.tableData[one].tradePlanFactoringList[two].planFactoringList[three].actualCashFlow = Math.abs(Number(row.amount))
        } else {
          this.tableData[one].tradePlanFactoringList[two].planFactoringList[three].actualCashFlow = -Number(row.amount)
        }
      } else {
        this.tableData[one].tradePlanFactoringList[two].planFactoringList[three].actualCashFlow = row.amount
      }
      // this.getIrrCalc()
    },
    // 金额类型发生变化
    amountCollectionTypeChange(row) {
      const { one, two, three, amountType, paymentCollectionType, rowData } = row
      const amountTypeCode = codeChangeName(this.constant.incormeExpenditureType, amountType, 'id', 'code')
      if (amountTypeCode === 'margin' && paymentCollectionType === 'pay_coll_payment') {
        this.tableData[one].tradePlanFactoringList[two].planFactoringList[three].receivingSubject = ''
      } else {
        this.tableData[one].tradePlanFactoringList[two].planFactoringList[three].receivingSubject = 'debtor'
      }
      this.amountChange(rowData, { one, two, three })
    },
    getIrrCalc() {
      for (let i = 0; i < this.tableData.length; i++) {
        const { planDate, amount } = this.tableData[i]
        if (!planDate) {
          this.$message.warning(`请选择${i + 1}条的约定日期`)
          return
        }
        if (!amount) {
          this.$message.warning(`请输入${i + 1}条的金额`)
          return
        }
      }
      const params = this.tableData.map(item => {
        const obj = {
          planDate: item.planDate,
          actualCashFlow: item.actualCashFlow,
          amountType: {
            id: item.amountType
          },
          paymentCollectionType: item.paymentCollectionType
        }
        if (item.paymentCollectionType === 'pay_coll_payment') {
          obj.loanRecordList = item.loanRecordList.map(item => {
            return {
              thisLoanAmount: item.thisLoanAmount,
              thisLoanDate: item.thisLoanDate
            }
          })
        } else {
          obj.collRecordList = item.collRecordList.map(item => {
            return {
              actualAmount: item.actualAmount,
              actualDate: item.actualDate
            }
          })
        }
        return obj
      })
      this.$api.customManage.collectionLoanManage.getIrrCalc(params).then((data) => {
        this.ruleForm.irr = (data.data * 100).toFixed(2)
      })
    },
    closeDialog(type) {
      this.$refs.allocationDialog.show = false
      if (type === 'submit') {
        this.$emit('execute-financing-trade')
      }
    },
    rowClick(row, column, event) {
      if (this.expandsKeys.includes(row.id)) {
        this.expandsKeys = this.expandsKeys.filter(val => val !== row.id)
      } else {
        this.expandsKeys.push(row.id)
      }
    },
    handleSelectionChange(val) {
      console.log(val, 4342432432423)
      this.$emit('accounts-receivable', val)
    },
    // echo() {
    //   console.log(111)
    //   this.$nextTick(() => {
    //     this.tableData.forEach(row => {
    //       row.tradePlanFactoringList.forEach(data => {
    //         data.planFactoringList.forEach((list) => {
    //           if (val.some(data => data.id === list.id)) {
    //             this.$refs.tradePlanFactoring.toggleRowSelection([list])
    //           }
    //         })
    //       })
    //     })
    //   })
    // },
    selectable(row, index) {
      if (row.oaSelect === 0) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style scoped>
.accounts-receivable .title {
  font-weight: bold;
  margin-top: 0px !important;
}

.allocation-box .el-checkbox__inner {
  margin-top: 2px;
  margin-left: 10px;
}

</style>
<style>

.accounts-receivable .el-table__expand-icon {
  font-size: 18px;
}
</style>
