<template>
  <div class="pledge-dialog">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="top" class="rule-form-orange">
      <el-form-item label="债务人类型" prop="debtorIdType">
        <el-select v-model="ruleForm.debtorIdType" :disabled="disabled" placeholder="请选择债务人类型">
          <el-option
            v-for="item in constant.idType"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="债务人名称" prop="debtorName">
        <el-input v-model="ruleForm.debtorName" :disabled="disabled" placeholder="请输入债务人名称" clearable />
      </el-form-item>
      <el-form-item label="联系方式" prop="debtorPhone">
        <el-input v-model="ruleForm.debtorPhone" :disabled="disabled" placeholder="请输入联系方式" clearable />
      </el-form-item>
      <el-form-item label="住址地（身份证地址）" prop="debtorIdAddress">
        <el-input v-model="ruleForm.debtorIdAddress" :disabled="disabled" placeholder="请输入住址地（身份证地址）" clearable />
      </el-form-item>
      <el-form-item label="实际地址（实际住址）" prop="debtorActualAddress">
        <el-input v-model="ruleForm.debtorActualAddress" :disabled="disabled" placeholder="请输入实际地址（实际住址）" clearable />
      </el-form-item>
      <el-form-item label="附件" prop="approvalConclusion">
        <cy-upload
          ref="fileStorageList"
          :upload-params="{}"
          :file-data="fileStorageList"
          :upload-from-orange-status="true"
          placeholder="请上传附件"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item label="最高额担保标识" prop="maxGuar">
        <el-radio-group v-model="ruleForm.maxGuar" :disabled="disabled">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <cy-info-title>质押信息</cy-info-title>
      <el-form-item label="出质人身份类型" prop="mortgagorIdType">
        <el-select v-model="ruleForm.mortgagorIdType" :disabled="disabled" placeholder="请选择出质人身份类型">
          <el-option
            v-for="item in constant.idType"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出质人名称" prop="mortgagorName">
        <el-input v-model="ruleForm.mortgagorName" :disabled="disabled" placeholder="请输入出质人名称" clearable />
      </el-form-item>
      <el-form-item label="出质人身份标识类型" prop="mortgagorCertType">
        <el-select v-model="ruleForm.mortgagorCertType" :disabled="disabled" placeholder="请选择出质人身份标识类型">
          <el-option
            v-for="item in arlpTypeList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出质人身份标识号码" prop="mortgagorCertNum">
        <el-input v-model="ruleForm.mortgagorCertNum" :disabled="disabled" placeholder="请输入出质人身份标识号码" clearable />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactNumber">
        <el-input v-model="ruleForm.contactNumber" :disabled="disabled" placeholder="请输入联系方式" clearable />
      </el-form-item>
      <el-form-item label="住址地（身份证地址）" prop="address">
        <el-input v-model="ruleForm.address" :disabled="disabled" placeholder="请输入住址地（身份证地址）" clearable />
      </el-form-item>
      <el-form-item label="实际地址（实际住址）" prop="actualAddress">
        <el-input v-model="ruleForm.actualAddress" :disabled="disabled" placeholder="请输入实际地址（实际住址）" clearable />
      </el-form-item>
      <template v-if="ruleForm.mortgagorIdType === 'idType_1'">
        <el-form-item label="证照正面" prop="approvalConclusion">
          <cy-upload
            ref="cardFrontFileStorage"
            :upload-params="{}"
            :file-data="cardFrontFileStorage"
            :upload-from-orange-status="true"
            placeholder="请上传证照正面"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="证照反面" prop="approvalConclusion">
          <cy-upload
            ref="cardReverseFileStorage"
            :upload-params="{}"
            :file-data="cardReverseFileStorage"
            :upload-from-orange-status="true"
            placeholder="请上传证照反面"
            :disabled="disabled"
          />
        </el-form-item>
      </template>
      <el-form-item v-if="ruleForm.mortgagorIdType === 'idType_2'" label="法定代表人" prop="legalRepresentative">
        <el-input v-model="ruleForm.legalRepresentative" :disabled="disabled" placeholder="请输入法定代表人" clearable />
      </el-form-item>
      <el-form-item style="width: 100%">
        <cy-comm-table
          ref="commTable"
          :columns="columns"
          :data="tableData"
          :count="0"
        />
      </el-form-item>
      <el-form-item label="金额合计" prop="approvalComments" class="one-form-item">
        <el-input v-model="approvalComments" disabled placeholder="请输入金额合计" clearable />
      </el-form-item>
      <el-form-item label="币种" prop="currency" class="one-form-item">
        <el-select v-model="ruleForm.currency" :disabled="disabled" placeholder="请选择币种">
          <el-option
            v-for="item in constant.currencyType"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    detailsInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      ruleForm: {},
      rules: {
        debtorIdType: [
          { required: true, message: '请选择债务人类型', trigger: 'change' }
        ],
        debtorName: [
          { required: true, message: '请选择债务人名称', trigger: 'blur' }
        ],
        debtorPhone: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        debtorIdAddress: [
          { required: true, message: '请输入住址地（身份证地址）', trigger: 'blur' }
        ],
        debtorActualAddress: [
          { required: true, message: '请输入实际地址（实际住址）', trigger: 'blur' }
        ],
        maxGuar: [
          { required: true, message: '请输入最高额担保标识', trigger: 'blur' }
        ],
        mortgagorIdType: [
          { required: true, message: '请选择抵押人身份类型', trigger: 'blur' }
        ],
        mortgagorName: [
          { required: true, message: '请输入抵押人名称', trigger: 'blur' }
        ],
        mortgagorCertType: [
          { required: true, message: '请选择抵押人身份标识类型', trigger: 'change' }
        ],
        mortgagorCertNum: [
          { required: true, message: '请输入抵押人身份标识号码', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入住所地(身份证地址)', trigger: 'blur' }
        ],
        actualAddress: [
          { required: true, message: '请输入实际地址(实际住址)', trigger: 'blur' }
        ],
        legalRepresentative: [
          { required: true, message: '请输入法定代表人', trigger: 'blur' }
        ],
        currency: [
          { required: true, message: '请选择币种', trigger: 'change' }
        ]
      },
      tableObj: {
        serNo: '',
        pleType: '',
        pleCurrency: '',
        pleValue: '',
        company: '',
        equityRatio: '',
        shareNumber: '',
        fileStorageList: [],
        id: ''
      },
      tableData: [],
      fileStorageList: [],
      cardFrontFileStorage: [],
      cardReverseFileStorage: []
    }
  },
  computed: {
    ...mapGetters(['constant']),
    arlpTypeList() {
      return this.constant.certType.filter(item => item.code.includes(this.ruleForm.mortgagorIdType))
    },
    approvalComments() {
      return this.tableData.reduce((one, two) => {
        return one + +two.pleValue
      }, 0)
    },
    ispledgeTypeEquity() {
      return this.tableData.some(item => item.pleType === 'pledgeType_equity')
    },
    columns() {
      return [
        {
          label: '序号',
          index: true
        },
        {
          label: '质押物种类',
          showTooltip: true,
          render: (h, row) => {
            const optionDom = this.constant.pledgeType.map(item => (<el-option
              key={item.code}
              label={item.name}
              value={item.code}
            ></el-option>))
            return (
              <el-select disabled={this.disabled} v-model={row.pleType} placeholder='请选择'>
                {optionDom}
              </el-select>
            )
          }
        },
        {
          label: '标的公司',
          prop: 'company',
          show: this.ispledgeTypeEquity,
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.company} placeholder='请输入标的公司'/>
          }
        },
        {
          label: '股权比例（%）',
          prop: 'equityRatio',
          show: this.ispledgeTypeEquity,
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.equityRatio} placeholder='请输入股权比例'/>
          }
        },
        {
          label: '股数（万股）',
          prop: 'shareNumber',
          show: this.ispledgeTypeEquity,
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.shareNumber} placeholder='请输入股数（万股）'/>
          }
        },
        {
          label: '质押物价值',
          prop: 'userTypeName',
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.pleValue} placeholder='请输入质押物价值'/>
          }
        },
        {
          label: '币种',
          showTooltip: true,
          render: (h, row) => {
            const optionDom = this.constant.currencyType.map(item => (<el-option
              key={item.code}
              label={item.name}
              value={item.code}
            ></el-option>))
            return (
              <el-select disabled={this.disabled} v-model={row.pleCurrency} placeholder='请选择'>
                {optionDom}
              </el-select>
            )
          }
        },

        {
          label: '附件',
          prop: 'userTypeName',
          render: (h, row, index) => {
            return <cy-upload
              ref={`fileStorage${index}`}
              upload-params={{}}
              file-data={row.fileStorageList}
              defaultDesc='请上传附件'
              disabled={this.disabled}
            />
          }
        },
        {
          label: '操作',
          show: !this.disabled,
          render: (h, row, index) => {
            const btnList = [
              {
                msg: '新增',
                category: 'add'
              },
              {
                msg: '删除',
                category: 'delete'
              }
            ]
            const options = btnList.map(item => {
              return (
                (item.category === 'delete' && this.tableData.length === 1) ? '' : <span class='table-icon-box' style='font-size: 14px;' onClick={() => { this.handlerOperate(item.category, row, index) }}>
                  { item.msg }
                </span>
              )
            })
            return <div>{ options }</div>
          },
          width: 130
        }
      ]
    }
  },
  watch: {
    detailsInfo: {
      handler(newV) {
        if (newV === undefined) {
          this.tableData = [this.tableObj]
          return
        }
        const { mortgagePledgeInfoList, fileStorageList, cardFrontFileStorage, cardReverseFileStorage } = JSON.parse(JSON.stringify(newV))
        this.tableData = mortgagePledgeInfoList?.length ? mortgagePledgeInfoList : [this.tableObj]
        this.ruleForm = {
          ...JSON.parse(JSON.stringify(newV))
        }
        this.fileStorageList = fileStorageList || []
        this.cardFrontFileStorage = this.getFileType(cardFrontFileStorage)
        this.cardReverseFileStorage = this.getFileType(cardReverseFileStorage)
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['idType', 'certType', 'quotaDisburseArlpType', 'currencyType', 'collateralType', 'pledgeType'])
  },
  methods: {
    getFileType(type) {
      if (Object.prototype.toString.call(type) === '[object Object]') {
        return [type]
      } else if (Object.prototype.toString.call(type) === '[object Array]') {
        return type
      } else {
        return []
      }
    },
    handlerOperate(type, row, index) {
      if (type === 'add') {
        this.tableData.push(JSON.parse(JSON.stringify(this.tableObj)))
      } else {
        this.tableData.splice(index, 1)
      }
    },
    getParams() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            const mortgagePledgeInfoList = this.tableData.map((item, index) => {
              const fileStorage = this.$refs.commTable.$refs[`fileStorage${index}`].getFileLists
              return {
                ...item,
                fileStorageList: fileStorage
              }
            })
            if (!mortgagePledgeInfoList.length) {
              this.$message.warning('请填写质押物详情')
              return
            }
            var params = {
              ...this.ruleForm,
              guarType: 2,
              fileStorageList: this.$refs.fileStorageList.getFileLists,
              mortgagePledgeInfoList,
              cardFrontFileStorage: [],
              cardReverseFileStorage: []
            }
            if (this.ruleForm.mortgagorIdType === 'idType_1') {
              params.cardFrontFileStorage = this.$refs.cardFrontFileStorage.getFileLists
              params.cardReverseFileStorage = this.$refs.cardReverseFileStorage.getFileLists
            }
            resolve(params)
          } else {
            reject()
            return false
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
