<template>
  <div class="rate-config">
    <cy-info-title style="margin-top: 10px; margin-bottom: 10px">
      <div>授信基本信息</div>
      <div slot="right">
        <el-button
          type="primary"
          @click="handlerOperate('add')"
        >添加</el-button>
      </div>
    </cy-info-title>
    <cy-comm-table ref="commTable" :columns="columns" :data="tableData" />
  </div>
</template>

<script>
import { getCompanyListApi } from '@/api/capitalManage/index'
import { deduplicateArray } from '@/utils'
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    detailsInfo: {
      type: Object,
      default: () => {}
    },
    financingRate: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      tableData: [],
      companyList: [],
      columns: [
        {
          label: '企业名称',
          prop: 'enterpriseName',
          ruleRequired: true,
          render: (h, row, index) => {
            const options = this.companyList.map(item => {
              return <el-option label={item.name} value={item.name}></el-option>
            })
            return (
              <el-select
                disabled={this.disabled}
                v-model={row.enterpriseName}
                onChange={() => {
                  this.companyChange(row, index)
                }}
                placeholder='请选择企业名称'
              >
                {options}
              </el-select>
            )
          }
        },
        {
          label: '统一社会信用代码',
          render: (h, row) => {
            return (
              <el-input
                v-model={row.socialCreditCode}
                disabled
                placeholder='请输入统一社会信用代码'
              ></el-input>
            )
          }
        },
        {
          label: '管理费率/年化（%）',
          ruleRequired: true,
          render: (h, row) => {
            return (
              <cy-number-input
                decimalOptions={{ needy: true, digitsNo: 2 }}
                v-model={row.managementRate}
                disabled={this.disabled}
                placeholder='请输入管理费率/年化（%）'
                onBlur={() => {
                  this.getComprehensiveQuotation()
                }}
              ></cy-number-input>
            )
          }
        },
        {
          label: '科技服务费率/年化（%）',
          ruleRequired: true,
          render: (h, row) => {
            return (
              <cy-number-input
                v-model={row.technologyServiceRate}
                decimalOptions={{ needy: true, digitsNo: 2 }}
                disabled={this.disabled}
                placeholder='请输入科技服务费率/年化（%）'
                onBlur={() => {
                  this.getComprehensiveQuotation()
                }}
              ></cy-number-input>
            )
          }
        },
        {
          label: '对外综合报价（%）',
          render: (h, row) => {
            return (
              <el-input
                v-model={row.comprehensiveQuotation}
                disabled
                placeholder='请输入科对外综合报价（%）'
              ></el-input>
            )
          }
        },
        {
          label: '操作',
          render: (h, row) => {
            const btnList = [
              {
                msg: '删除'
              }
            ]
            const options = btnList.map(item => {
              return (
                <el-button
                  type='text'
                  onClick={() => {
                    this.handlerOperate(item.category, row)
                  }}
                >
                  {item.msg}
                </el-button>
              )
            })
            return <div>{options}</div>
          },
          width: 100
        }
      ]
    }
  },
  computed: {
    isM1AOrM1B() {
      const codeList = ['M1A', 'M1B']
      return codeList.includes(this.detailsInfo.businessTypeNo)
    },
    isM2AOrM2B() {
      const codeList = ['M2A', 'M2B']
      return codeList.includes(this.detailsInfo.businessTypeNo)
    },
    isM3A() {
      const codeList = ['M3A']
      return codeList.includes(this.detailsInfo.businessTypeNo)
    }
  },
  watch: {
    detailsInfo: {
      handler(newV) {
        if (newV && Object.keys(newV).length) {
          const deepNewV = JSON.parse(JSON.stringify(newV))
          this.tableData = deepNewV.enterpriseRateAllocations
        }
      },
      immediate: true
      // deep: true
    },
    financingRate: {
      handler(newV) {
        if (newV) {
          this.getComprehensiveQuotation()
        }
      },
      immediate: true
    }
  },
  created() {
    this.getCompanyList()
  },
  methods: {
    getCompanyList() {
      const { id } = this.$route.params
      getCompanyListApi({ id }).then(({ data }) => {
        this.companyList = data
      })
    },
    handlerOperate(type) {
      if (type === 'add') {
        const obj = {
          enterpriseName: '',
          socialCreditCode: '',
          managementRate: '',
          technologyServiceRate: 0.5,
          comprehensiveQuotation: '',
          id: ''
        }
        this.tableData.push(JSON.parse(JSON.stringify(obj)))
        this.$nextTick(() => {
          this.getComprehensiveQuotation()
        })
      }
    },
    companyChange(row, index) {
      console.log(row, index)
      const obj = this.companyList.find(
        item => item.name === row.enterpriseName
      )
      this.tableData[index].socialCreditCode = obj.code
    },
    getComprehensiveQuotation() {
      this.tableData = this.tableData.map(item => {
        if (this.isM1AOrM1B) {
          item.comprehensiveQuotation = (
            Number(item.managementRate) +
            Number(item.technologyServiceRate) +
            Number(this.financingRate)
          ).toFixed(2)
        }
        if (this.isM2AOrM2B || this.isM3A) {
          item.comprehensiveQuotation = (
            Number(item.managementRate) +
            Number(item.technologyServiceRate) +
            Number(this.detailsInfo.bankRate)
          ).toFixed(2)
        }
        return item
      })
    },
    getParams(type) {
      this.newTableData = deduplicateArray(this.tableData, 'enterpriseName')
      return new Promise((resolve, reject) => {
        if (type === 'temp') {
          resolve(this.tableData)
        } else {
          for (let i = 0; i < this.tableData.length; i++) {
            const { enterpriseName, managementRate, technologyServiceRate } =
              this.tableData[i]
            if (!enterpriseName) {
              this.$message.warning('请输入企业名称重复')
              reject()
              return
            }
            if (!managementRate) {
              this.$message.warning('请输入管理费率')
              reject()
              return
            }
            if (!technologyServiceRate) {
              this.$message.warning('请输入科技服务费率')
              reject()
              return
            }
          }
          if (this.newTableData.length < this.tableData.length) {
            this.$message.warning('企业名称重复')
            reject()
          }
          resolve(this.tableData)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
