<template>
  <div class="mortgage-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="附件">
        <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 style="margin-top: 20px;">抵押信息</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="证照正面" class="form-required">
          <cy-upload
            ref="cardFrontFileStorage"
            :upload-params="{}"
            :file-data="cardFrontFileStorage"
            :upload-from-orange-status="true"
            placeholder="请上传证照正面"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="证照反面" class="form-required">
          <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"
        :rules="[
          { required: ruleForm.mortgagorIdType === 'idType_2', message: '请输入法定代表人', trigger: 'blur' }
        ]"
      >
        <el-input v-model="ruleForm.legalRepresentative" :disabled="disabled" placeholder="请输入法定代表人" clearable />
      </el-form-item>
      <template v-if="isCollateralTypeJQSB">
        <el-form-item label="债务履行开始日" prop="startDate">
          <el-date-picker
            v-model="ruleForm.startDate"
            type="datetime"
            placeholder="请选择债务履行开始日"
            value-format="yyyy-MM-dd"
            :disabled="disabled"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="债务履行到期日" prop="endDate">
          <el-date-picker
            v-model="ruleForm.endDate"
            type="datetime"
            placeholder="请选择债务履行到期日"
            value-format="yyyy-MM-dd"
            :disabled="disabled"
          >
          </el-date-picker>
        </el-form-item>
      </template>
      <el-form-item style="width: 100%;margin-top: 20px">
        <cy-comm-table
          ref="commTable"
          :columns="columns"
          :data="tableData"
          :count="0"
        />
      </el-form-item>
      <el-form-item label="金额合计" prop="approvalComments" class="one-form-item form-required">
        <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 {
      fileStorageList: [],
      cardFrontFileStorage: [],
      cardReverseFileStorage: [],
      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' }
        ],
        startDate: [
          { required: true, message: '请选择债务履行开始日', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择债务履行到期日', trigger: 'change' }
        ],
        currency: [
          { required: true, message: '请选择币种', trigger: 'change' }
        ]
      },
      tableObj: {
        serNo: '',
        collType: '',
        collIdType: '',
        collCertId: '',
        collDistrictStr: [],
        collValue: '',
        collCurrency: '',
        evaluateOrgType: '',
        collEvaluateDate: '',
        collDesc: '',
        collateralName: '',
        number: '',
        collateralType: '',
        engineNumber: '',
        trackNumber: '',
        fileStorageList: [],
        id: ''
      },
      tableData: []
    }
  },
  computed: {
    ...mapGetters(['constant']),
    arlpTypeList() {
      return this.constant.certType.filter(item => item.code.includes(this.ruleForm.mortgagorIdType))
    },
    isCollateralTypeJQSB() {
      return this.tableData.some(item => item.collType === 'collateralType_JQSB')
    },
    columns() {
      return [
        {
          label: '序号',
          index: true
        },
        {
          label: '抵押物种类',
          showTooltip: true,
          width: 180,
          render: (h, row) => {
            const optionDom = this.constant.collateralType.map(item => (<el-option
              key={item.code}
              label={item.name}
              value={item.code}
            ></el-option>))
            return (
              <el-select disabled={this.disabled} v-model={row.collType} placeholder='请选择'>
                {optionDom}
              </el-select>
            )
          }
        },
        {
          label: '抵押物名称',
          prop: 'userTypeName',
          width: 180,
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.collateralName} placeholder='请输入抵押物名称'/>
          }
        },
        {
          label: '抵押物识别号类型',
          showTooltip: true,
          width: 160,
          render: (h, row) => {
            const optionDom = this.constant.collateralIdType.map(item => (<el-option
              key={item.code}
              label={item.name}
              value={item.code}
            ></el-option>))
            return (
              <el-select disabled={this.disabled} v-model={row.collIdType} placeholder='请选择'>
                {optionDom}
              </el-select>
            )
          }
        },
        {
          label: '抵押物唯一识别号',
          prop: 'userTypeName',
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.collCertId} placeholder='请输入最终现金流'/>
          },
          width: 160
        },
        {
          label: '数量',
          show: this.isCollateralTypeJQSB,
          prop: 'number',
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.number} placeholder='请输入数量'/>
          },
          width: 160
        },
        {
          label: '型号',
          show: this.isCollateralTypeJQSB,
          prop: 'collateralType',
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.collateralType} placeholder='请输入型号'/>
          },
          width: 160
        },
        {
          label: '发动机号',
          show: this.isCollateralTypeJQSB,
          prop: 'engineNumber',
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.engineNumber} placeholder='请输入发动机号'/>
          },
          width: 160
        },
        {
          label: '履带号',
          show: this.isCollateralTypeJQSB,
          prop: 'trackNumber',
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.trackNumber} placeholder='请输入履带号'/>
          },
          width: 160
        },
        {
          label: '抵押物位置所在行政区划',
          prop: 'userTypeName',
          render: (h, row) => {
            return <el-cascader
              props={{
                props: {
                  value: 'deptCode', label: 'name', children: 'children'
                }
              }}
              disabled={this.disabled}
              v-model={row.collDistrictStr}
              options={this.constant.regionList}
              placeholder='请选择抵押物位置所在行政区划'>
            </el-cascader>
          },
          width: 180
        },
        {
          label: '抵押评估价值',
          prop: 'userTypeName',
          width: 180,
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.collValue} placeholder='请输入抵押评估价值'/>
          }
        },
        {
          label: '币种',
          showTooltip: true,
          width: 120,
          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.collCurrency} placeholder='请选择币种'>
                {optionDom}
              </el-select>
            )
          }
        },
        {
          label: '评估机构类型',
          showTooltip: true,
          width: 180,
          render: (h, row) => {
            const optionDom = [{ label: '自评估', value: 1 }, { label: '第三方评估机构', value: 2 }].map(item => (<el-option
              key={item.value}
              label={item.label}
              value={item.value}
            ></el-option>))
            return (
              <el-select disabled={this.disabled} v-model={row.evaluateOrgType} placeholder='请选择'>
                {optionDom}
              </el-select>
            )
          }
        },
        {
          label: '抵押物评估日期',
          prop: 'postName',
          width: 180,
          render: (h, row) => {
            return (
              <el-date-picker
                disabled={this.disabled}
                v-model={row.collEvaluateDate}
                type='date'
                value-format='yyyy-MM-dd'
                placeholder='选择日期'>
              </el-date-picker>
            )
          }
        },
        {
          label: '附件',
          prop: 'userTypeName',
          width: 180,
          render: (h, row, index) => {
            return <cy-upload
              disabled={this.disabled}
              ref={`fileStorage${index}`}
              upload-params={{}}
              file-data={row.fileStorageList}
              defaultDesc='请上传附件'
            />
          }
        },
        {
          label: '抵押物说明',
          prop: 'userTypeName',
          width: 180,
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.collDesc} placeholder='请输入最终现金流'/>
          }
        },

        {
          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
        }
      ]
    },
    approvalComments() {
      return this.tableData.reduce((one, two) => {
        return one + +two.collValue
      }, 0)
    }

  },
  watch: {
    detailsInfo: {
      handler(newV) {
        if (newV === undefined) {
          this.tableData = [this.tableObj]
          return
        }
        const { mortgageCollateralInfoList, fileStorageList, cardFrontFileStorage, cardReverseFileStorage } = JSON.parse(JSON.stringify(newV))
        this.tableData = mortgageCollateralInfoList?.length ? mortgageCollateralInfoList : [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', 'collateralType', 'collateralIdType', 'currencyType', 'regionList'])
  },
  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 mortgageCollateralInfoList = this.tableData.map((item, index) => {
              const fileStorage = this.$refs.commTable.$refs[`fileStorage${index}`].getFileLists
              return {
                ...item,
                fileStorageList: fileStorage
              }
            })
            if (!mortgageCollateralInfoList.length) {
              this.$message.warning('请填写抵押物详情')
              return
            }
            var params = {
              ...this.ruleForm,
              guarType: 1,
              fileStorageList: this.$refs.fileStorageList.getFileLists,
              mortgageCollateralInfoList,
              cardFrontFileStorage: [],
              cardReverseFileStorage: []
            }
            if (this.ruleForm.mortgagorIdType === 'idType_1') {
              params.cardFrontFileStorage = this.$refs.cardFrontFileStorage.getFileLists
              if (!params.cardFrontFileStorage.length) {
                this.$message.warning('请上传证照正面')
                return
              }
              params.cardReverseFileStorage = this.$refs.cardReverseFileStorage.getFileLists
              if (!params.cardReverseFileStorage.length) {
                this.$message.warning('请上传证照反面')
                return
              }
            }

            resolve(params)
          } else {
            reject()
            return false
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
