<template>
  <el-dialog :title="title" :visible.sync="dialogOpen" width="650px" :close-on-click-modal="true" append-to-body @opened="initData" @close="handleCancel">
    <el-descriptions v-if="options === 'info'" :column="1" border>
      <el-descriptions-item label="公式名称" label-class-name="my-label" content-class-name="my-content">{{formData.formulaName}}</el-descriptions-item>
      <el-descriptions-item label="公式简称">{{formData.formulaShortName}}</el-descriptions-item>
      <el-descriptions-item label="所属指标">{{formData.formulaIndicator = 0?'一级指标':formData.formulaIndicator=2?'二级指标':'三级指标'}}</el-descriptions-item>
      <el-descriptions-item label="原始公式">{{formData.originalFormula}}</el-descriptions-item>
      <el-descriptions-item label="说明">{{formData.remark}}</el-descriptions-item>
    </el-descriptions>
    <div v-else-if="options!== 'info'" class="warning">
      <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="公式名称" prop="formulaName">
          <el-input v-model="formData.formulaName" placeholder="请输入公式名称" />
        </el-form-item>
        <el-form-item label="公式简称" prop="formulaShortName">
          <el-input v-model="formData.formulaShortName" placeholder="请输入公式简称" />
        </el-form-item>
        <el-form-item label="所属指标" prop="formulaIndicator">
          <el-select v-model="formData.formulaIndicator" placeholder="请选择所属指标">
            <el-option
              v-for="item in formulaIndicator"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 公式组装区域（支持手动输入+参数选择） -->
        <el-form-item label="表达式" prop="originalFormula">
          <div class="formula-builder" >
            <!-- 公式输入框 -->
            <el-input
              v-model="formData.originalFormula"
              type="textarea"
              placeholder="请输入公式（支持 α^2 表示平方，使用括号分组）"
              @change="checkParentheses"
              rows="3"
              :class="{ 'is-error':!isBalanced }"
            ></el-input>
            <div v-if="!isBalanced" class="error-message">括号不匹配，请检查！</div>
          </div>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            maxlength="300"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { findInfoList, addFormulas, updateFormulas } from "@/api/eval/formulas";

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    options: {
      type: String,
      default: 'add'
    },
    dataInfo: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      availableParams: ['TP', 'TN', 'FP', 'FN'],
      formulaIndicator:[
        {'label': '一级指标','value' : '0'},
        {'label': '二级指标','value' : '1'},
        {'label': '三级指标','value' : '2'},
      ],
      formData: {
        formulaId: '',
        formulaName: '',
        originalFormula: '',
        formulaShortName: '',
        formulaIndicator:'',
        formulaStoredProcedure: '',
        remark: ''
      },
      rules: {
        formulaName: [
          { required: true, message: '请输入公式名称', trigger: 'blur' }
        ],
        formulaShortName:[
          { required: true, message: '请输入公式简称', trigger: 'blur' }
        ],
        originalFormula: [
          { required: true, message: '请输入公式表达式', trigger: 'blur' }
        ],
        formulaIndicator:[
          { required: true, message: '请选择归属指标', trigger: 'blur' }
        ]
      },
      procedureCode: null, // 生成的存储过程代码（可选显示）
      dialogOpen: false, // 本地缓存 open 状态
      isBalanced: true // 记录括号是否匹配的状态
    };
  },
  model: {
    prop: 'value',
    event: 'input'
  },
  watch: {
    value(newVal) {
      this.dialogOpen = newVal;
    }
  },
  computed: {
    // 自动提取公式中的参数（正则匹配字母、希腊字母等）
    paramList() {
      const regex = /[αA-Za-z_$]+/g; // 匹配参数（支持希腊字母α，字母，下划线）
      const params = this.formData.originalFormula.match(regex) || [];
      // 去重并排除非可用参数
      return [...new Set(params)].filter(p => this.availableParams.includes(p));
    },
    title() {
      if (this.options === 'add') {
        return '新增算法公式';
      }
      if (this.options === 'edit') {
        return '修改算法公式';
      }
      if (this.options === 'info') {
        return '查看算法公式详情';
      }
    },
    styles() {
      let style = {};
      if (this.minHeight) {
        style.minHeight = `${this.minHeight}px`;
      }
      if (this.height) {
        style.height = `${this.height}px`;
      }
      return style;
    }
  },
  methods: {
    initData() {
      if (this.options!== 'add') {
        this.formData = { ...this.dataInfo };
      }
      findInfoList().then(res => {
        console.log('参数输出',res)
        this.availableParams = { ...res,...this.availableParams};
      })
    },
    // 插入参数到公式输入框
    insertParam(param) {
      this.formData.originalFormula = this.formData.originalFormula + param.originalFormula;
      this.checkParentheses();
    },
    // 插入运算符或符号
    insertSymbol(symbol) {
      this.formData.originalFormula = this.formData.originalFormula + symbol;
      this.checkParentheses();
    },
    // 检查括号是否匹配
    isParenthesesBalanced(formula) {
      let stack = [];
      for (let i = 0; i < formula.length; i++) {
        let char = formula[i];
        if (char === '(') {
          stack.push(char);
        } else if (char === ')') {
          if (stack.length === 0) {
            return false;
          }
          stack.pop();
        }
      }
      return stack.length === 0;
    },
    // 检查括号并更新状态
    checkParentheses() {
      this.isBalanced = this.isParenthesesBalanced(this.formData.originalFormula);
    },
    // 提交表单
    handleSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid && this.isBalanced) {
          if (this.formData.formulaId) {
            updateFormulas(this.formData).then(response => {
              this.$message.success("修改成功");
              this.handleCancel()
            });
          } else {
            addFormulas(this.formData).then(response => {
              this.$message.success("新增成功");
              this.handleCancel()
            });
          }
        }
      });
    },
    // 关闭弹窗
    handleCancel() {
      // 重置表单数据
      this.formData = {
        formulaId: '',
        formulaName: '',
        originalFormula: '',
        formulaShortName: '',
        formulaStoredProcedure: '',
        remark: ''
      };
      this.procedureCode = null;
      this.isBalanced = true;
      this.$emit('input', false);
    }
  }
};
</script>

<style scoped>
.formula-builder {
  margin-bottom: 20px;
}

.param-buttons {
  margin-bottom: 10px;
}

.param-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.is-error {
  border-color: red;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}
</style>
