<template>
  <div class="history-cooperation">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange"
    >
      <el-form-item label="历史合作时间" prop="historicalCooperationDuration">
        <el-radio-group v-model="ruleForm.historicalCooperationDuration">
          <el-radio v-for="item in timeList" :key="item.code" :label="item.code">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="历史合作规模" prop="historicalCooperationScale">
        <el-radio-group v-model="ruleForm.historicalCooperationScale">
          <el-radio v-for="item in scaleList" :key="item.code" :label="item.code">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="累计历史开票金额" prop="historicalCooperationInvoicingAmount">
        <el-radio-group v-model="ruleForm.historicalCooperationInvoicingAmount">
          <el-radio v-for="item in amountList" :key="item.code" :label="item.code">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="历史回款最长账期" prop="historicalCooperationMaximumAccountingPeriod">
        <el-select v-model="ruleForm.historicalCooperationMaximumAccountingPeriod" placeholder="请选择历史回款最长账期">
          <el-option
            v-for="item in periodList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="历史合作项目数量" prop="historicalCooperationTimes">
        <el-radio-group v-model="ruleForm.historicalCooperationTimes">
          <el-radio v-for="item in countList" :key="item.code" :label="item.code">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="历史合作资料上传" style="width: 100%;">
        <template slot="label">
          <span>*历史合作资料上传</span>
          <span style="color: #A3A8AC; margin-left: 10px; font-weight: 500;">提供近一年与核心企业合作的相关项目，招投标文件、购销合同、订单、验收单、结算单、发票、回单，格式为：pdf</span>
        </template>
        <cy-comm-table
          ref="commTable"
          :columns="columns"
          :data="tableData"
          :count="0"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getDictionaryInfo } from '@/api/myBusiness/projectInfo'
export default {
  props: {
    details: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      timeList: [],
      scaleList: [],
      amountList: [],
      periodList: [],
      countList: [],
      ruleForm: {
        historicalCooperationDuration: '',
        historicalCooperationScale: '',
        historicalCooperationInvoicingAmount: '',
        historicalCooperationMaximumAccountingPeriod: '',
        historicalCooperationTimes: ''
      },
      rules: {
        historicalCooperationDuration: [
          { required: true, message: '请选择历史合作时间', trigger: 'change' }
        ],
        historicalCooperationScale: [
          { required: true, message: '请选择历史合作规模', trigger: 'change' }
        ],
        historicalCooperationInvoicingAmount: [
          { required: true, message: '请选择累计历史开票金额', trigger: 'change' }
        ],
        historicalCooperationMaximumAccountingPeriod: [
          { required: true, message: '请选择历史回款最长账期', trigger: 'change' }
        ],
        historicalCooperationTimes: [
          { required: true, message: '请选择历史合作项目数量', trigger: 'change' }
        ]
      },
      tableData: [
        { fileStorageDOS: [] }
      ],
      columns: [
        {
          label: '序号',
          index: true
        },
        // {
        //   label: '项目',
        //   prop: 'postName',
        //   showTooltip: true,
        //   width: 160
        // },
        {
          label: '历史合同及相应单据',
          ruleRequired: true,
          render: (h, row, index) => {
            return <cy-upload
              ref={`fileStorage${index}`}
              limit={1}
              uploadParams={{
                fileType: 'projectCoreEnterpriseFile'
              }}
              fileData={row.fileStorageDOS}
              defaultDesc='提供1份与核心企业合作过的历史合同及相应单据：招投标文件、购销合同、订单、验收单、结算单、发票、回单（格式为：pdf）'
            />
          }
        },
        {
          label: '操作',
          show: this.$route.query.type !== 'details',
          render: (h, row, index) => {
            const btnList = [
              { msg: '添加', icon: 'iconfont icon-orange icon-a-Group812', category: 'add' },
              { msg: '删除', icon: 'iconfont icon-orange icon-a-Group991', category: 'delete' }
            ]
            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.optionsClick(item.category, index) }}></i>
                  </span>
                </el-tooltip>
              )
            })
            return <div>{ options }</div>
          },
          width: 150
        }]
    }
  },
  watch: {
    details: {
      handler(newV) {
        if (newV && Object.keys(newV)) {
          const details = JSON.parse(JSON.stringify(newV))
          for (const k in this.ruleForm) {
            if (details[k] !== '' && details[k] !== null && details[k] !== undefined) {
              this.ruleForm[k] = details[k]
            }
          }
          if (details.projectCoreEnterpriseFiles.length) {
            this.tableData = details.projectCoreEnterpriseFiles
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getTimeList()
    this.getScaleList()
    this.getAmountList()
    this.getPeriodList()
    this.getCountList()
  },
  methods: {
    optionsClick(type, index) {
      if (type === 'add') {
        this.tableData.push(
          {
            fileStorage: []
          }
        )
      } else if (type === 'delete') {
        if (this.tableData.length > 1) {
          this.tableData.splice(index, 1)
        }
      }
    },
    validate(submitType) {
      const projectCoreEnterpriseFiles = this.tableData.map((item, index) => {
        const fileStorage = this.$refs.commTable.$refs[`fileStorage${index}`].getFileLists
        return {
          projectNumber: index + 1,
          fileIds: fileStorage.map(item => item.id)
        }
      })

      const projectCoreEnterprise = {
        ...this.ruleForm,
        projectCoreEnterpriseFiles
      }
      return new Promise((resolve, reject) => {
        if (submitType === 'submit') {
          this.$refs.ruleFormRef.validate(valid => {
            if (valid) {
              if (submitType === 'submit') {
                let flag = false
                for (let i = 0; i < projectCoreEnterpriseFiles.length; i++) {
                  if (projectCoreEnterpriseFiles[i].fileIds.length === 0) {
                    flag = true
                    break
                  }
                }
                if (flag) {
                  this.$message.warning('请上传历史合作资料')
                  return
                }
              }
              return resolve(projectCoreEnterprise)
            } else {
              reject()
              return false
            }
          })
        } else {
          resolve(projectCoreEnterprise)
        }
      })
    },

    // 历史合作时间
    getTimeList() {
      getDictionaryInfo({ parentCode: 'c_core_enterprise_cooperation_time' }).then(res => {
        this.timeList = res.data
      })
    },
    // 历史合作规模
    getScaleList() {
      getDictionaryInfo({ parentCode: 'c_core_enterprise_cooperation_scale' }).then(res => {
        this.scaleList = res.data
      })
    },
    // 累计历史开票金额
    getAmountList() {
      getDictionaryInfo({ parentCode: 'c_core_enterprise_invoice_amount' }).then(res => {
        this.amountList = res.data
      })
    },
    // 历史回款最长账期
    getPeriodList() {
      getDictionaryInfo({ parentCode: 'c_core_enterprise_longest_accounting_period' }).then(res => {
        this.periodList = res.data
      })
    },
    // 历史合作项目数量
    getCountList() {
      getDictionaryInfo({ parentCode: 'c_core_enterprise_cooperation_count' }).then(res => {
        this.countList = res.data
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.history-cooperation {
  .el-form {
    padding: 10px 20px;
  }
}
</style>
