<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <!-- 规则类型下拉选择 -->
      <el-form-item label="规则类型" prop="ruleType">
        <el-select
          v-model="ruleForm.ruleType"
          placeholder="请选择规则类型"
          style="width: 100%"
        >
          <el-option
            v-for="item in ruleTypeList"
            :key="item.typeCode"
            :label="item.typeName"
            :value="item.typeCode"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 字段类型下拉选择 -->
      <el-form-item label="字段类型" prop="ruleField">
        <el-select
          v-model="ruleForm.ruleField"
          placeholder="请选择字段类型"
          style="width: 100%"
        >
          <el-option
            v-for="item in fieldTypeList"
            :key="item.fieldName"
            :label="item.fieldComment"
            :value="item.fieldName"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 规则描述文本域 -->
      <el-form-item label="规则描述" prop="ruleDesc">
        <el-input
          type="textarea"
          v-model="ruleForm.ruleDesc"
          placeholder="请输入规则描述"
          :rows="3"
        ></el-input>
      </el-form-item>

      <!-- 风险提示话术输入框 -->
      <el-form-item label="风险提示话术" prop="riskScript">
        <el-input
          v-model="ruleForm.riskScript"
          placeholder="请输入风险提示话术"
        ></el-input>
      </el-form-item>

      <!-- 校验内容类型 -->
      <!--      <el-form-item label="校验内容类型" prop="checkType">-->
      <!--        <el-select -->
      <!--          v-model="ruleForm.checkType" -->
      <!--          placeholder="请选择校验内容类型" -->
      <!--          style="width: 100%"-->
      <!--        >-->
      <!--          <el-option label="表单信息" :value="1"></el-option>-->
      <!--          <el-option label="文本文件" :value="2"></el-option>-->
      <!--          <el-option label="图片" :value="3"></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <!--      &lt;!&ndash; 风险类型 &ndash;&gt;-->
      <!--      <el-form-item label="风险类型" prop="riskType">-->
      <!--        <el-select -->
      <!--          v-model="ruleForm.riskType" -->
      <!--          placeholder="请选择风险类型" -->
      <!--          style="width: 100%"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="item in riskTypeList"-->
      <!--            :key="item.riskTypeCode"-->
      <!--            :label="item.riskType"-->
      <!--            :value="item.riskTypeCode">-->
      <!--          </el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <!--      &lt;!&ndash; 运行类型 &ndash;&gt;-->
      <!--      <el-form-item label="运行类型" prop="runType">-->
      <!--        <el-radio-group v-model="ruleForm.runType">-->
      <!--          <el-radio label="ai">AI</el-radio>-->
      <!--          <el-radio label="func">函数</el-radio>-->
      <!--        </el-radio-group>-->
      <!--      </el-form-item>-->
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        @click="handleSubmit"
        :loading="submitLoading"
        size="medium"
        >确 定</el-button
      >
      <el-button @click="handleClose" size="medium">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { createRule, updateRule, queryRuleDetail } from '@/api/riskCheck/rule'

export default {
  name: 'RuleEditDialog',
  props: {
    // 对话框是否可见
    visible: {
      type: Boolean,
      default: false
    },
    // 是否为编辑模式
    isEdit: {
      type: Boolean,
      default: false
    },
    // 当前规则数据
    ruleData: {
      type: Object,
      default: () => ({})
    },
    // 规则类型选项列表
    ruleTypeOptions: {
      type: Array,
      default: () => []
    },
    // 字段类型选项列表
    fieldTypeOptions: {
      type: Array,
      default: () => []
    },
    // 风险类型选项列表
    riskTypeOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      submitLoading: false,
      // 表单数据
      ruleForm: {
        id: '',
        ruleType: '',
        ruleField: '',
        ruleDesc: '',
        riskScript: '',
        checkType: 1,
        riskType: '',
        ruleStatus: 0,
        runType: 'ai'
      },
      // 表单验证规则
      rules: {
        ruleType: [
          { required: true, message: '请选择规则类型', trigger: 'change' }
        ],
        ruleField: [
          { required: true, message: '请选择字段类型', trigger: 'change' }
        ],
        ruleDesc: [
          { required: true, message: '请输入规则描述', trigger: 'blur' }
        ],
        riskScript: [
          { required: true, message: '请输入风险提示话术', trigger: 'blur' }
        ],
        checkType: [
          { required: true, message: '请选择校验内容类型', trigger: 'change' }
        ],
        riskType: [
          { required: true, message: '请选择风险类型', trigger: 'change' }
        ],
        runType: [
          { required: true, message: '请选择运行类型', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 对话框标题
    dialogTitle() {
      return this.isEdit ? '编辑规则' : '新增规则'
    },
    // 对话框可见性
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    // 规则类型选项列表
    ruleTypeList() {
      return this.ruleTypeOptions.length > 0
        ? this.ruleTypeOptions
        : [
            { typeName: '基本信息', typeCode: 'basic_rule' },
            { typeName: '投保信息', typeCode: 'insurance_rule' }
          ]
    },
    // 字段类型选项列表
    fieldTypeList() {
      return this.fieldTypeOptions.length > 0
        ? this.fieldTypeOptions
        : [
            { fieldComment: '保险期限（天）', fieldName: 'insurance_period' },
            { fieldComment: '投保金额', fieldName: 'insurance_amount' }
          ]
    },
    // 风险类型选项列表
    riskTypeList() {
      return this.riskTypeOptions.length > 0
        ? this.riskTypeOptions
        : [
            {
              riskType: '费率与投保方案不合理风险',
              riskTypeCode: 'rate_plan_risk'
            },
            {
              riskType: '保险责任不明确风险',
              riskTypeCode: 'insurance_liability_risk'
            }
          ]
    }
  },
  watch: {
    // 监听规则数据变化
    ruleData: {
      handler(val) {
        if (val && Object.keys(val).length > 0) {
          this.ruleForm = Object.assign({}, val)
        } else {
          this.ruleForm = {
            id: '',
            ruleType: '',
            ruleField: '',
            ruleDesc: '',
            riskScript: '',
            checkType: 1,
            riskType: '',
            ruleStatus: 0,
            runType: 'ai'
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    // 关闭对话框
    handleClose() {
      this.$refs.ruleForm.resetFields()
      this.$emit('update:visible', false)
    },
    // 提交表单
    handleSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          // 根据是否为编辑模式调用不同接口
          const request = this.isEdit ? updateRule : createRule
          
          // 创建提交参数的副本
          const params = Object.assign({}, this.ruleForm)
          
          // 将ruleType的值转换为对应的中文typeName
          const selectedRuleType = this.ruleTypeList.find(
            item => item.typeCode === params.ruleType
          )
          if (selectedRuleType) {
            params.ruleType = selectedRuleType.typeName
          }
          
          // 将ruleField的值转换为对应的中文fieldComment
          const selectedFieldType = this.fieldTypeList.find(
            item => item.fieldName === params.ruleField
          )
          if (selectedFieldType) {
            params.ruleField = selectedFieldType.fieldComment
          }

          request(params)
            .then(response => {
              this.$message.success(`${this.dialogTitle}成功`)
              this.$emit('success', response)
              this.handleClose()
            })
            .catch(error => {
              this.$message.error(
                `${this.dialogTitle}失败: ` + (error.message || '未知错误')
              )
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>
