<template>
  <el-dialog title="新增个人利率定价流程" :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="loanPurpose">
            <el-select v-model="form.loanPurpose" placeholder="请选择贷款用途" style="width: 100%">
              <el-option label="消费" value="consumer"/>
              <el-option label="经营" value="business"/>
            </el-select>
          </el-form-item>
        </el-col>
        <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-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否有经营佐证" prop="bizProof">
            <el-switch v-model="form.bizProof"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="循环功能" prop="loanLoop">
            <el-switch v-model="form.loanLoop"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 抵质押信息 -->
      <el-divider v-if="isCollateralGuarantee" content-position="left">抵质押信息</el-divider>
      <el-row v-if="isCollateralGuarantee">
        <el-col :span="12">
          <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-row>
    </el-form>
    <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 {createPersonalWorkflow} from "@/api/loanPricing/workflow"

export default {
  name: "PersonalCreateDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    customerMap: {
      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()
        }
      }
    }

    return {
      loanTermOptions: [
        '1', '2', '3', '4', '5', '6'
      ],
      submitting: false,
      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,
        loanPurpose: undefined,
        loanTerm: undefined,
        bizProof: false,
        loanLoop: false,
        collType: undefined,
        collThirdParty: false
      },
      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"}
        ],
        loanPurpose: [
          {required: true, message: "请选择贷款用途", trigger: "change"}
        ],
        loanTerm: [
          {required: true, message: "请选择借款期限", trigger: "change"}
        ]
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    isCollateralGuarantee() {
      return this.form.guarType === '抵押' || this.form.guarType === '质押'
    },
    collateralTypeOptions() {
      if (this.form.guarType === '抵押') {
        return ['一类', '二类', '三类', '四类', '其他']
      }
      if (this.form.guarType === '质押') {
        return ['存单质押', '其他']
      }
      return []
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.reset()
      }
    },
    'form.guarType'(val, oldVal) {
      if (val !== oldVal) {
        this.resetCollateralFields()
      }
    }
  },
  methods: {
    /** 表单重置 */
    reset() {
      this.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,
        loanPurpose: undefined,
        loanTerm: undefined,
        bizProof: false,
        loanLoop: false,
        collType: undefined,
        collThirdParty: false
      }
      this.submitting = false
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    /** 对话框关闭处理 */
    handleClose() {
      this.cancel()
    },
    /** 取消按钮 */
    cancel() {
      this.dialogVisible = false
      this.reset()
    },
    /** 清空抵质押字段 */
    resetCollateralFields() {
      this.form.collType = undefined
      this.form.collThirdParty = false
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate(['collType', 'collThirdParty'])
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submitting = true
          // 转换开关值为字符串
          const data = {
            ...this.form,
            bizProof: this.form.bizProof ? '1' : '0',
            loanLoop: this.form.loanLoop ? '1' : '0'
          }
          if (this.isCollateralGuarantee) {
            data.collThirdParty = this.form.collThirdParty ? '1' : '0'
          } else {
            delete data.collType
            delete data.collThirdParty
          }

          createPersonalWorkflow(data).then(response => {
            this.$modal.msgSuccess("新增成功")
            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;
}

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