<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="900px" append-to-body
             @close="handleClose">
    <el-form ref="form" :model="form" :rules="rules" label-width="140px" class="workflow-create-form">
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户内码" prop="custIsn">
            <el-input v-model="form.custIsn" placeholder="请选择客户内码" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="custName">
            <el-input v-model="form.custName" placeholder="请选择客户名称" :readonly="true"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="证件类型" prop="idType">
            <el-select v-model="form.idType" placeholder="请选择证件类型" style="width: 100%">
              <el-option label="统一社会信用代码" value="统一社会信用代码"/>
              <el-option label="其他" value="其他"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证件号码" prop="idNum">
            <el-input v-model="form.idNum" placeholder="请输入证件号码"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 贷款信息 -->
      <el-divider content-position="left">贷款信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="担保方式" prop="guarType">
            <el-select v-model="form.guarType" placeholder="请选择担保方式" style="width: 100%">
              <el-option label="信用" value="信用"/>
              <el-option label="保证" value="保证"/>
              <el-option label="抵押" value="抵押"/>
              <el-option label="质押" value="质押"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请金额(元)" prop="applyAmt">
            <el-input v-model="form.applyAmt" placeholder="请输入申请金额"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="贷款期限(年)" prop="loanTerm">
            <el-select v-model="form.loanTerm" placeholder="请选择贷款期限" style="width: 100%">
              <el-option v-for="item in loanTermOptions" :key="item" :label="item" :value="item"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="余值覆盖" prop="resCover">
            <el-switch v-model="form.resCover"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="业务种类" prop="businessType">
            <el-select v-model="form.businessType" placeholder="请选择业务种类" style="width: 100%" @change="handleBusinessTypeChange">
              <el-option label="新增" value="新增"/>
              <el-option label="存量新增" value="存量新增"/>
              <el-option label="存量转贷" value="存量转贷"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="isStockTransfer">
          <el-form-item label="历史贷款利率" prop="loanRateHistory">
            <el-input :value="formatRate(form.loanRateHistory, '')" placeholder="请选择历史贷款合同" :readonly="true"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 企业标识 -->
      <el-divider content-position="left">企业标识</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="绿色贷款" prop="isGreenLoan">
            <el-switch v-model="form.isGreenLoan"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="贸易和建筑业企业" prop="isTradeBuildEnt">
            <el-switch v-model="form.isTradeBuildEnt"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 抵质押信息 -->
      <el-divider v-if="isCollateralGuarantee" content-position="left">抵质押信息</el-divider>
      <el-row v-if="isCollateralGuarantee">
        <template v-if="isMortgage">
          <el-col :span="12">
            <el-form-item label="抵押物性质" prop="collateralNature">
              <el-select v-model="form.collateralNature" placeholder="请选择抵押物性质" style="width: 100%">
                <el-option v-for="item in collateralNatureOptions" :key="item" :label="item" :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否属于九地" prop="isNineArea">
              <div class="nine-area-control">
                <el-select
                  v-model="form.isNineArea"
                  :disabled="!requiresNineArea"
                  :placeholder="requiresNineArea ? '请选择是否属于九地' : '无需选择'"
                >
                  <el-option label="是" value="是"/>
                  <el-option label="否" value="否"/>
                </el-select>
                <el-tooltip content="九地是指绍兴、杭州、宁波、上海、北京、广州、深圳、南京、苏州" placement="top">
                  <i class="el-icon-question nine-area-help" tabindex="0" aria-label="查看九地说明"></i>
                </el-tooltip>
              </div>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="12" v-if="isPledge">
          <el-form-item label="抵质押类型" prop="collType">
            <el-select v-model="form.collType" placeholder="请选择抵质押类型" style="width: 100%">
              <el-option v-for="item in collateralTypeOptions" :key="item" :label="item" :value="item"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抵质押物是否第三方所有" prop="collThirdParty">
            <el-switch v-model="form.collThirdParty"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="isCertificatePledge">
          <el-form-item label="存单票面利率" prop="couponRate">
            <el-input v-model="form.couponRate" placeholder="请输入存单票面利率"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <history-contract-selector
      :visible.sync="showHistorySelector"
      :contracts="historyContracts"
      :loading="historyLoading"
      @select="handleHistoryContractSelect"
    />
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="submitting" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {createCorporateWorkflow, queryHistoryContracts, updateCorporateWorkflow} from "@/api/loanPricing/workflow"
import HistoryContractSelector from "./HistoryContractSelector"
import {formatRate} from "@/utils/rate"

export default {
  name: "CorporateCreateDialog",
  components: {
    HistoryContractSelector
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    customerMap: {
      type: Object,
      default: null
    },
    editData: {
      type: Object,
      default: null
    }
  },
  data() {
    // 金额验证
    const validateApplyAmt = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入申请金额'))
      } else {
        const num = parseFloat(value)
        if (isNaN(num) || num <= 0) {
          callback(new Error('请输入有效的金额'))
        } else if (num > 999999999.99) {
          callback(new Error('金额不能超过 999999999.99'))
        } else {
          callback()
        }
      }
    }

    const validateCouponRate = (rule, value, callback) => {
      if (this.isCertificatePledge && !value) {
        callback(new Error('存单票面利率不能为空'))
        return
      }
      callback()
    }

    const validateCollateralType = (rule, value, callback) => {
      if (this.isPledge && !value) {
        callback(new Error('请选择抵质押类型'))
        return
      }
      callback()
    }

    const validateCollateralNature = (rule, value, callback) => {
      if (this.isMortgage && !value) {
        callback(new Error('请选择抵押物性质'))
        return
      }
      callback()
    }

    const validateNineArea = (rule, value, callback) => {
      if (this.requiresNineArea && !value) {
        callback(new Error('请选择是否属于九地'))
        return
      }
      callback()
    }

    // 贷款期限验证
    const validateLoanTerm = (rule, value, callback) => {
      if (!value && value !== 0) {
        callback(new Error('请输入贷款期限'))
      } else {
        const num = parseInt(value)
        if (isNaN(num) || num <= 0) {
          callback(new Error('请输入有效的贷款期限'))
        } else {
          callback()
        }
      }
    }

    return {
      loanTermOptions: [
        '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'
      ],
      submitting: false,
      resettingForm: false,
      showHistorySelector: false,
      historyLoading: false,
      historyContracts: [],
      selectedHistoryContract: null,
      form: {
        orgCode: '892000',
        runType: '1',
        custIsn: this.customerMap ? this.customerMap.cust_isn : undefined,
        custName: this.customerMap ? this.customerMap.cust_name : undefined,
        idType: undefined,
        idNum: this.customerMap ? (this.customerMap.cust_id || '').substring(3) : undefined,
        guarType: undefined,
        applyAmt: undefined,
        loanTerm: undefined,
        businessType: undefined,
        loanRateHistory: undefined,
        resCover: false,
        isGreenLoan: false,
        isTradeBuildEnt: false,
        collType: undefined,
        collateralNature: undefined,
        isNineArea: undefined,
        collThirdParty: false,
        couponRate: undefined
      },
      rules: {
        custIsn: [
          {required: true, message: "客户内码不能为空", trigger: "blur"},
          {min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur"}
        ],
        custName: [
          {required: true, message: "客户名称不能为空", trigger: "blur"},
          {min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur"}
        ],
        idType: [
          {required: true, message: "请选择证件类型", trigger: "change"}
        ],
        idNum: [
          {required: true, message: "证件号码不能为空", trigger: "blur"}
        ],
        guarType: [
          {required: true, message: "请选择担保方式", trigger: "change"}
        ],
        applyAmt: [
          {required: true, validator: validateApplyAmt, trigger: "blur"}
        ],
        loanTerm: [
          {required: true, validator: validateLoanTerm, trigger: "change"}
        ],
        businessType: [
          {required: true, message: "请选择业务种类", trigger: "change"}
        ],
        loanRateHistory: [
          {required: true, message: "请选择历史贷款合同", trigger: "change"}
        ],
        collType: [
          {validator: validateCollateralType, trigger: "change"}
        ],
        collateralNature: [
          {validator: validateCollateralNature, trigger: "change"}
        ],
        isNineArea: [
          {validator: validateNineArea, trigger: "change"}
        ],
        couponRate: [
          {validator: validateCouponRate, trigger: "blur"}
        ]
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    isCollateralGuarantee() {
      return this.form.guarType === '抵押' || this.form.guarType === '质押'
    },
    isMortgage() {
      return this.form.guarType === '抵押'
    },
    isPledge() {
      return this.form.guarType === '质押'
    },
    requiresNineArea() {
      return this.isMortgage && ['普通住宅、土地、厂房', '商业性质不动产'].includes(this.form.collateralNature)
    },
    isStockTransfer() {
      return this.form.businessType === '存量转贷'
    },
    isCertificatePledge() {
      return this.form.guarType === '质押' && this.form.collType === '存单质押'
    },
    isEdit() {
      return !!(this.editData && this.editData.serialNum)
    },
    dialogTitle() {
      return this.isEdit ? '编辑企业利率定价流程' : '新增企业利率定价流程'
    },
    collateralTypeOptions() {
      if (this.isPledge) {
        return ['存单质押', '股权质押', '其他质押']
      }
      return []
    },
    collateralNatureOptions() {
      return ['普通住宅、土地、厂房', '商业性质不动产', '排污权', '其他不动产']
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.reset()
      }
    },
    'form.guarType'(val, oldVal) {
      if (this.resettingForm) {
        return
      }
      if (val !== oldVal) {
        this.resetCollateralFields()
      }
    },
    'form.collType'() {
      if (this.resettingForm) {
        return
      }
      this.resetCouponRateIfNotCertificatePledge()
    },
    'form.collateralNature'(val, oldVal) {
      if (this.resettingForm || val === oldVal) {
        return
      }
      this.handleCollateralNatureChange()
    }
  },
  methods: {
    formatRate,
    /** 表单重置 */
    reset() {
      this.resettingForm = true
      this.form = this.buildForm()
      this.submitting = false
      this.showHistorySelector = false
      this.historyLoading = false
      this.historyContracts = []
      this.selectedHistoryContract = null
      this.$nextTick(() => {
        this.resettingForm = false
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    buildForm() {
      if (this.isEdit) {
        return {
          orgCode: this.editData.orgCode || '892000',
          runType: this.editData.runType || '1',
          custIsn: this.editData.custIsn,
          custName: this.editData.custName,
          idType: this.editData.idType,
          idNum: this.editData.idNum,
          guarType: this.editData.guarType,
          applyAmt: this.editData.applyAmt,
          loanTerm: this.editData.loanTerm,
          businessType: this.editData.businessType,
          loanRateHistory: this.editData.loanRateHistory,
          resCover: this.isOne(this.editData.resCover),
          isGreenLoan: this.isOne(this.editData.isGreenLoan),
          isTradeBuildEnt: this.isOne(this.editData.isTradeBuildEnt),
          collType: this.editData.guarType === '质押' ? this.editData.collType : undefined,
          collateralNature: undefined,
          isNineArea: undefined,
          collThirdParty: this.isOne(this.editData.collThirdParty),
          couponRate: this.editData.couponRate
        }
      }
      return {
        orgCode: '892000',
        runType: '1',
        custIsn: this.customerMap ? this.customerMap.cust_isn : undefined,
        custName: this.customerMap ? this.customerMap.cust_name : undefined,
        idType: undefined,
        idNum: this.customerMap ? (this.customerMap.cust_id || '').substring(3) : undefined,
        guarType: undefined,
        applyAmt: undefined,
        loanTerm: undefined,
        businessType: undefined,
        loanRateHistory: undefined,
        resCover: false,
        isGreenLoan: false,
        isTradeBuildEnt: false,
        collType: undefined,
        collateralNature: undefined,
        isNineArea: undefined,
        collThirdParty: false,
        couponRate: undefined
      }
    },
    isOne(value) {
      return value === true || value === 'true' || value === '1'
    },
    /** 对话框关闭处理 */
    handleClose() {
      this.cancel()
    },
    /** 取消按钮 */
    cancel() {
      this.dialogVisible = false
      this.reset()
    },
    /** 清空抵质押字段 */
    resetCollateralFields() {
      this.form.collType = undefined
      this.form.collateralNature = undefined
      this.form.isNineArea = undefined
      this.form.collThirdParty = false
      this.resetCouponRateIfNotCertificatePledge()
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate(['collType', 'collateralNature', 'isNineArea', 'collThirdParty', 'couponRate'])
        }
      })
    },
    handleCollateralNatureChange() {
      this.form.isNineArea = undefined
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate(['isNineArea'])
        }
      })
    },
    resolveMortgageCollateralType() {
      if (this.form.collateralNature === '普通住宅、土地、厂房') {
        return this.form.isNineArea === '是' ? '一类' : '二类'
      }
      if (this.form.collateralNature === '商业性质不动产') {
        return this.form.isNineArea === '是' ? '二类' : '三类'
      }
      if (this.form.collateralNature === '排污权') {
        return '排污权抵押'
      }
      if (this.form.collateralNature === '其他不动产') {
        return '其他不动产抵押'
      }
    },
    resetCouponRateIfNotCertificatePledge() {
      if (!this.isCertificatePledge) {
        this.form.couponRate = undefined
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate(['couponRate'])
          }
        })
      }
    },
    handleBusinessTypeChange(value) {
      this.clearHistoryContract()
      if (value === '存量转贷') {
        this.queryHistoryContracts()
      }
    },
    queryHistoryContracts() {
      if (!this.form.custIsn) {
        this.$modal.msgWarning("客户内码不能为空")
        return
      }
      this.historyLoading = true
      queryHistoryContracts(this.form.custIsn).then(response => {
        this.historyContracts = response.data || []
        if (this.historyContracts.length === 0) {
          this.$modal.msgWarning("未查询到历史贷款合同")
          return
        }
        this.showHistorySelector = true
      }).finally(() => {
        this.historyLoading = false
      })
    },
    handleHistoryContractSelect(row) {
      if (!row.loan_rate_history) {
        this.$modal.msgWarning("历史贷款利率不能为空")
        return
      }
      this.selectedHistoryContract = row
      this.form.loanRateHistory = row.loan_rate_history
    },
    clearHistoryContract() {
      this.selectedHistoryContract = null
      this.form.loanRateHistory = undefined
      this.historyContracts = []
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate(['loanRateHistory'])
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isStockTransfer && !this.form.loanRateHistory) {
            this.$modal.msgWarning("请选择历史贷款合同")
            return
          }
          if (this.isCertificatePledge && !this.form.couponRate) {
            this.$modal.msgWarning("存单票面利率不能为空")
            return
          }
          this.submitting = true
          // 转换开关值为字符串
          const data = {
            ...this.form,
            resCover: this.form.resCover ? '1' : '0',
            isGreenLoan: this.form.isGreenLoan ? '1' : '0',
            isTradeBuildEnt: this.form.isTradeBuildEnt ? '1' : '0'
          }
          if (this.isMortgage) {
            data.collType = this.resolveMortgageCollateralType()
          }
          delete data.collateralNature
          delete data.isNineArea
          if (this.isCollateralGuarantee) {
            data.collThirdParty = this.form.collThirdParty ? '1' : '0'
          } else {
            delete data.collType
            delete data.collThirdParty
          }
          if (!this.isStockTransfer) {
            delete data.loanRateHistory
          }
          if (!this.isCertificatePledge) {
            delete data.couponRate
          }

          const submitRequest = this.isEdit
            ? updateCorporateWorkflow(this.editData.serialNum, data)
            : createCorporateWorkflow(data)
          submitRequest.then(response => {
            this.$modal.msgSuccess(this.isEdit ? "编辑成功" : "新增成功")
            this.dialogVisible = false
            this.$emit('success')
          }).catch(error => {
            // 保留表单，显示错误信息
            console.error('创建失败:', error)
          }).finally(() => {
            this.submitting = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.workflow-create-form .el-divider {
  margin: 8px 0 16px 0;
  font-weight: 500;
  font-size: 14px;
}

.nine-area-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.nine-area-control .el-select {
  flex: 1;
  min-width: 0;
}

.nine-area-help {
  flex: 0 0 auto;
  color: #909399;
  cursor: help;
  font-size: 16px;
}

@media screen and (max-width: 768px) {
  .workflow-create-form .el-col {
    width: 100% !important;
    max-width: 100% !important;
    flex: 0 0 100% !important;
  }
}
</style>
