<template>
  <div class="limit-expenditure">
    <el-form ref="ruleForm" :key="formKey" :model="ruleForm" :rules="rules" label-width="150px" label-position="top" class="rule-form-orange">
      <cy-info-title>审批结论</cy-info-title>
      <el-form-item label="审批结论" prop="approvalConclusion">
        <el-radio-group v-model="ruleForm.approvalConclusion" :disabled="disabled">
          <el-radio label="pass">通过</el-radio>
          <el-radio label="back">退回</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="审批意见"
        style="width: 100%;"
        class="textarea-content"
        prop="approvalComments"
        :rules="[
          { required: ruleForm.approvalConclusion === 'back', message: '请输入审批意见', trigger: 'blur' }
        ]"
      >
        <el-input v-model="ruleForm.approvalComments" :disabled="disabled" type="textarea" style="width: 100%;" rows="3" clearable></el-input>
      </el-form-item>
      <template v-if="ruleForm.approvalConclusion === 'pass'">
        <cy-info-title>授信余额</cy-info-title>
        <el-form-item label="业务综合授信余额" class="one-form-item">
          <cy-amount-input v-model="ruleForm.businessCreditBalance" disabled placeholder="请输入业务综合授信余额" clearable>
          </cy-amount-input>
        </el-form-item>
        <el-form-item label="供应商授信余额" class="one-form-item">
          <cy-amount-input v-model="ruleForm.supplierCreditBalance" disabled placeholder="请输入供应商授信余额" clearable>
          </cy-amount-input>
        </el-form-item>
        <cy-info-title>应收账款信息</cy-info-title>
        <el-form-item label="应收账款起始日" prop="startDate">
          <el-date-picker
            v-model="ruleForm.startDate"
            :disabled="disabled"
            type="date"
            placeholder="请选择应收账款起始日"
            value-format="yyyy-MM-dd"
            @change="getEndDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="应收账款期限" prop="term">
          <el-input v-model.number="ruleForm.term" :disabled="disabled" placeholder="请输入应收账款期限" clearable @blur="getEndDate" />
        </el-form-item>
        <el-form-item label="应收账款结束日" prop="endDate">
          <el-date-picker
            v-model="ruleForm.endDate"
            disabled
            type="date"
            placeholder="请选择应收账款结束日"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <cy-info-title style="margin-top: 20px">征信上报</cy-info-title>
        <el-form-item label="账户上报方式" prop="reportMethod">
          <el-radio-group v-model="ruleForm.reportMethod" :disabled="disabled">
            <el-radio :label="1">A类</el-radio>
            <el-radio :label="0">B类</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
    </el-form>
    <template v-if="ruleForm.approvalConclusion === 'pass'">
      <financing-info
        ref="financingInfo"
        :end-date="ruleForm.endDate"
        :details-info="ruleForm.reviewFinancingInfo"
        :accounts-receivable-net-amount-total="ruleForm.accountsReceivableNetAmountTotal"
        :disabled="disabled"
        style="margin-top: 20px;"
      />
      <cy-info-title>
        收支计划
        <div slot="right">
          <el-button v-if="!disabled" type="text" @click="automaticGeneration">自动生成</el-button>
        </div>
      </cy-info-title>
      <revenue-expenditure-plan
        ref="revenueExpenditurePlan"
        :details-info="{
          incomeExpenditurePlanList: ruleForm.incomeExpenditurePlanList || [],
          planIrrStr: ruleForm.planIrrStr
        }"
        :disabled="disabled"
        @getTrrData="getTrrData"
      >
      </revenue-expenditure-plan>
      <main-contract-info ref="mainContractInfo" :details-info="ruleForm.reviewMasterContract" :disabled="disabled"></main-contract-info>
      <responsible-person ref="responsiblePerson" :disabled="disabled" :details-info="ruleForm"></responsible-person>
      <mortgage-pledge-info ref="mortgagePledgeInfo" :disabled="disabled" :details-info="ruleForm"></mortgage-pledge-info>
      <assignment ref="assignment" :details-info="ruleForm" :disabled="disabled"></assignment>
    </template>
    <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>
  </div>
</template>

<script>
import { getLimitExpenditureDatails, getExpenditurePlan, getTrr, reviewQuotaDisburseSubmit } from '@/api/financingManage'
import { parseTime } from '@/utils'
export default {
  components: {
    FinancingInfo: () => import('./components/FinancingInfo'),
    revenueExpenditurePlan: () => import('./components/RevenueExpenditurePlan'),
    MainContractInfo: () => import('./components/MainContractInfo'),
    ResponsiblePerson: () => import('./components/ResponsiblePerson'),
    MortgagePledgeInfo: () => import('./components/MortgagePledgeInfo'),
    Assignment: () => import('./components/Assignment')
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    detailsInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      ruleForm: {
        approvalConclusion: 'pass',
        approvalComments: '',
        businessCreditBalance: '',
        supplierCreditBalance: '',
        reviewMasterContract: {
          factoringAccountName: '',
          factoringAccount: '',
          factoringAccountBank: '',
          ourAccountName: '',
          ourAccount: '',
          ourAccountBank: ''
        },
        incomeExpenditurePlanList: []
      },
      rules: {
        approvalConclusion: [
          { required: true, message: '请选择审批结论', trigger: 'change' }
        ],
        startDate: [
          { required: true, message: '请选择应收账款起始日', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择应收账款结束日', trigger: 'change' }
        ],
        term: [
          { required: true, message: '请选择应收账款期限', trigger: 'blur' }
        ],
        reportMethod: [
          { required: true, message: '请选择账户上报方式', trigger: 'change' }
        ]
      },
      expenditurePlanData: {
        incomeExpenditurePlanList: [],
        planIrrStr: ''

      },
      formKey: 0
    }
  },
  watch: {
    detailsInfo: {
      handler(newV) {
        if (newV === undefined) return
        // if (this.$route.query?.type === 'see') {
        //   const { incomeExpenditurePlanHisList, reviewFinancingInfoHis, reviewMasterContractHis, reviewTransferReceivableHis, mortgageBasicInfoHisList, reviewBasicContractHisList } = JSON.parse(JSON.stringify(newV))
        //   this.ruleForm = {
        //     ...this.ruleForm,
        //     ...JSON.parse(JSON.stringify(newV)),
        //     incomeExpenditurePlanList: incomeExpenditurePlanHisList,
        //     mortgageBasicInfoList: mortgageBasicInfoHisList || [],
        //     reviewBasicContractList: reviewBasicContractHisList || [],
        //     reviewMasterContract: reviewMasterContractHis || [],
        //     reviewFinancingInfo: reviewFinancingInfoHis || [],
        //     reviewTransferReceivable: reviewTransferReceivableHis || []
        //   }
        //   this.expenditurePlanData = {
        //     incomeExpenditurePlanList: this.ruleForm.incomeExpenditurePlanList || [],
        //     planIrrStr: this.ruleForm.planIrrStr
        //   }
        // }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getDeatils()
  },
  methods: {
    getDeatils() {
      const { id } = this.$route.params
      // if (this.$route.query?.type === 'see') return
      if (!id) return
      getLimitExpenditureDatails({ id }).then(({ data }) => {
        this.ruleForm = {
          ...this.ruleForm,
          ...data
        }
        this.expenditurePlanData = {
          incomeExpenditurePlanList: this.ruleForm.incomeExpenditurePlanList || [],
          planIrrStr: this.ruleForm.planIrrStr
        }
        this.formKey += 1
      })
    },
    getEndDate() {
      const { startDate, term } = this.ruleForm
      if (startDate && term) {
        const endDateGetTime = new Date(`${startDate} 00:00:00`).getTime() + (3600 * 1000 * 24 * term)
        this.ruleForm.endDate = parseTime(endDateGetTime)
      }
    },
    async automaticGeneration() {
      const params = await this.$refs.financingInfo.getParams()
      getExpenditurePlan(params).then(({ data }) => {
        this.ruleForm.incomeExpenditurePlanList = data
        this.$nextTick(() => {
          this.getTrrData()
        })
      })
    },
    getTrrData() {
      const params = {
        incomeExpenditurePlanList: this.$refs.revenueExpenditurePlan.getParams()
      }
      getTrr(params).then(({ data }) => {
        this.ruleForm.planIrrStr = data
      })
    },
    async getParams(type) {
      // const { id } = this.$route.params
      const { taskId } = this.$route.query
      var params = {
        Loading: true
      }
      if (this.ruleForm.approvalConclusion === 'pass') {
        if (type === 'submit') {
          const { startDate, endDate } = this.ruleForm
          if (!startDate) {
            this.$message.warning('请选择应收账款起始日')
            return
          }
          if (!endDate) {
            this.$message.warning('请选择应收账款结束日')
            return
          }
        }
        const financingInfo = await this.$refs.financingInfo.getParams(type)
        const incomeExpenditurePlanList = this.$refs.revenueExpenditurePlan.getParams(type)
        const mainContractInfo = this.$refs.mainContractInfo.ruleForm
        const responsiblePerson = this.$refs.responsiblePerson.getParams(type)
        const mortgagePledgeInfo = this.$refs.mortgagePledgeInfo.getParams(type)
        const assignment = this.$refs.assignment.getParams(type)
        params = {
          ...params,
          ...this.ruleForm,
          reviewFinancingInfo: financingInfo,
          incomeExpenditurePlanList,
          reviewMasterContract: mainContractInfo,
          ...responsiblePerson,
          ...mortgagePledgeInfo,
          ...assignment,
          taskId
        }
        if (!assignment.reviewTransferReceivable.confirm) {
          params.reviewBasicContractList = []
        }
      } else {
        const { approvalConclusion, approvalComments, financingBasicInfoId, id } = this.ruleForm
        params = {
          ...params,
          approvalConclusion,
          approvalComments,
          financingBasicInfoId,
          id,
          taskId
        }
      }
      return params
    },
    async submit(type) {
      if (type === 'temp') {
        const data = await this.getParams(type)
        data.visible = type !== 'temp'
        reviewQuotaDisburseSubmit(data).then(() => {
          this.$message.warning('暂存成功')
          this.$router.go(-1)
        })
      } else {
        const data = await this.getParams(type)
        if (data.incomeExpenditurePlanList && data.incomeExpenditurePlanList.length) {
          await this.automaticGeneration()
        }
        this.$refs.ruleForm.validate(async(valid) => {
          if (valid) {
            data.visible = type !== 'temp'
            setTimeout(() => {
              reviewQuotaDisburseSubmit(data).then(() => {
                this.$message.warning('提交成功')
                this.$router.go(-1)
              })
            }, 500)
          } else {
            return false
          }
        })
      }
    }
  }
}
</script>

<style  scoped>

</style>
