<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { DrawerProps, FormProps } from "element-plus";
import { editListApi } from "@/api/indexData";
import dayjs from "dayjs";
// getIndexInfo,
// postUpdate,
import {
  postUpdateAssessmentQuotaDetails,
  postUpdateAssessmentFormulas
} from "@/api/assessment";
import { conditionVerify } from "@/api/formula";
import jishuanqi from "@/views/evaluate/children/change/components/jishuanqi.vue";
import manyFormula from "@/components/formula/manyFormula.vue";
import { formulaParamsChange, echoParamsChange } from "@/utils/business";
const emit = defineEmits(["updateDialog", "getAssessmentQuotaDetailsApi"]);
const formRef = ref();
const drawer = ref(false);
// 延迟组件传递数据
const showData = ref(false);
const direction = ref<DrawerProps["direction"]>("rtl");
// 表单
const formulaOne = ref();
const formLabelAlign = reactive({
  relationId: "",
  targetValue: 0,
  finalValue: 0,
  addValue: 0,
  decValue: 0,
  challengeValue: 0,
  startValue: 0,
  upperValue: 0,
  agupperValue: 0,
  dataSource: "",
  score: 0,
  assessmentObjectId: "",
  assessmentModelId: "",
  id: "",
  dimId: "",
  assessmentId: "",
  formulaType: 0,
  formula: ""
});
// 抽屉逻辑
const open = row => {
  console.log(row, "------");
  Object.assign(formLabelAlign, JSON.parse(JSON.stringify(row)));
  let dataJSon = null;
  if (row.formulaType === 0) {
    dataJSon = row.formula;
  } else if (row.formulaType === 1) {
    dataJSon = echoParamsChange(row.formulaParamsList);
  }
  formulaOne.value = dataJSon || "";
  drawer.value = true;
  showData.value = true;
};
const jishuanqiRef = ref();
// 公式
const countNoConditionFormulaClick = (data: any) => {
  console.log(data, "data");
  formulaOne.value = data;
};
defineExpose({
  open
});
const handleClose = () => {
  showData.value = false;
  drawer.value = false;
  Object.assign(formLabelAlign, {
    relationId: "",
    targetValue: 0,
    finalValue: 0,
    addValue: 0,
    decValue: 0,
    challengeValue: 0,
    startValue: 0,
    upperValue: 0,
    agupperValue: 0,
    dataSource: "",
    score: 0,
    assessmentObjectId: "",
    assessmentModelId: "",
    id: "",
    dimId: "",
    assessmentId: "",
    formulaType: 0,
    formula: ""
  });
};
// 公式验证
const dialogFormVisibleFormula = ref(false);
const formulaForm = ref([]);
const grade = ref();
const conditionVerifyApi = async () => {
  grade.value = null;
  formulaForm.value = [];
  dialogFormVisibleFormula.value = true;
  try {
    formulaForm.value = [];
    grade.value = "";
    const keywords = [
      "完成值",
      "目标值",
      "门槛值",
      "挑战值",
      "增幅",
      "降幅",
      "上期完成值",
      "上上期完成值"
    ];
    let str = formulaOne.value;
    // 创建一个正则表达式，匹配这些关键词
    const regex = new RegExp(keywords.join("|"), "g");
    // 提取字符串中的所有关键词
    let matches = str.match(regex);
    matches.forEach(matchItem => {
      formulaForm.value.push({
        name: matchItem,
        value: ""
      });
    });
    let result = str.replace(regex, match => {
      return `${match}`;
    });
  } catch (err) {
    //
  }
};
// 取消计算
const quxiaoCmputed = () => {
  formulaForm.value = [];
  dialogFormVisibleFormula.value = false;
};
const countComputed = async () => {
  try {
    if (formLabelAlign.formulaType == 0) {
      // const formula = JSON.stringify({
      //   noConditionFormula: formulaOne.value
      // });
      const { code, msg } = await conditionVerify({
        formulaType: formLabelAlign.formulaType,
        formula: formulaOne.value
      });
      if (code == 200) {
        const keywords = [
          "完成值",
          "目标值",
          "门槛值",
          "挑战值",
          "增幅",
          "降幅",
          "上期完成值",
          "上上期完成值"
        ];
        let str = formulaOne.value;
        // 创建一个正则表达式，匹配这些关键词
        const regex = new RegExp(keywords.join("|"), "g");
        let result = str.replace(regex, match => {
          // 在 formulaForm.value 中查找匹配的项
          let matchedItem = formulaForm.value.find(item => item.name === match);

          // 如果找到匹配项，返回其 value，否则返回原始匹配值
          if (matchedItem) {
            return matchedItem.value; // 替换为对应的值
          }
          return match; // 如果没有匹配项，返回原始匹配值
        });
        // calculator.calculate(result);
        // grade.value = calculator.get();
        grade.value = eval(result).toFixed(2);
      } else {
        ElMessageBox.confirm(
          "如果不修改将无法计算得分",
          "公式计算错误,修改后确认",
          {
            type: "warning"
          }
        ).then(() => {
          dialogFormVisibleFormula.value = false;
        });
      }
    }
  } catch (err) {
    console.log(err);
  }
};
// 确认
const confirmClick = () => {
  if (formLabelAlign.formulaType == 0 && formLabelAlign.scoreStandard === 1) {
    countNoConditionFormulaClick(jishuanqiRef.value.exposeData());
  }
  postUpdateApi();
};
// 更新模板指标关联
const postUpdateApi = async () => {
  let params: any = {
    relationId: formLabelAlign.relationId,
    targetValue: formLabelAlign.targetValue,
    finalValue: formLabelAlign.finalValue,
    addValue: formLabelAlign.addValue,
    decValue: formLabelAlign.decValue,
    challengeValue: formLabelAlign.challengeValue,
    startValue: formLabelAlign.startValue,
    upperValue: formLabelAlign.upperValue,
    agupperValue: formLabelAlign.agupperValue,
    dataSource: formLabelAlign.dataSource,
    score: formLabelAlign.score,
    assessmentObjectId: formLabelAlign.assessmentObjectId,
    assessmentModelId: formLabelAlign.assessmentModelId,
    id: formLabelAlign.id,
    dimId: formLabelAlign.dimId,
    assessmentId: formLabelAlign.assessmentId,
    formulaType: formLabelAlign.formulaType
    // formula: formLabelAlign.formula,
  };
  // Object.assign(params, formLabelAlign);
  // params.formula = JSON.stringify({
  //   noConditionFormula: formulaOne.value
  // });
  if (formLabelAlign.formulaType == 0) {
    params.formula = formulaOne.value;
  } else if (formLabelAlign.formulaType == 1) {
    console.log(formulaOne.value, "aaaa");
    params.formulaParamsList = formulaParamsChange(formulaOne.value);
  }
  const { code, msg } = await postUpdateAssessmentFormulas(params);
  if (code === 200) {
    ElMessage.success("修改成功");
    setTimeout(() => {
      emit("getAssessmentQuotaDetailsApi");
    }, 800);
    drawer.value = false;
  } else {
    // ElMessage.error(msg);
  }
};
// 切换公式类型
// 监听formulaType变化
const watchFormulaType = value => {
  console.log("formulaOne", formulaOne);
};
</script>

<template>
  <div>
    <el-drawer
      v-model="drawer"
      :direction="direction"
      :before-close="handleClose"
      size="700px"
    >
      <template #header>
        <h4>公式设置</h4>
      </template>
      <template #default>
        <div>
          <el-form
            ref="formRef"
            label-position="top"
            label-width="auto"
            :model="formLabelAlign"
          >
            <el-form-item
              label="考核对象"
              label-position="top"
              prop="sourceValue"
            >
              <el-input
                v-model="formLabelAlign.assessmentObjectName"
                disabled
              />
            </el-form-item>
            <el-form-item
              label="考核模板"
              label-position="top"
              prop="sourceValue"
            >
              <el-input v-model="formLabelAlign.assessmentModelName" disabled />
            </el-form-item>
            <el-form-item
              label="指标名称"
              label-position="top"
              prop="sourceValue"
            >
              <el-input v-model="formLabelAlign.name" disabled />
            </el-form-item>
            <el-form-item
              label="完成值录入人"
              label-position="top"
              prop="sourceValue"
            >
              <el-select v-model="formLabelAlign.valueInput" disabled>
                <el-option label="被考核人" :value="0" />
                <!-- <el-option label="上级" :value="1" /> -->
                <el-option label="指定人员" :value="2" />
                <el-option label="考核管理员" :value="3" />
                <el-option label="指标自动采集" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item
              label="评分方式"
              label-position="top"
              prop="sourceValue"
            >
              <el-select v-model="formLabelAlign.scoreStandard" disabled>
                <el-option label="手动输入" :value="0" />
                <el-option label="公式自动计算" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="formLabelAlign.scoreStandard === 1"
              label="公式类型"
              label-position="top"
              prop="sourceValue"
            >
              <el-select
                v-model="formLabelAlign.formulaType"
                @change="watchFormulaType"
              >
                <el-option label="无条件公式" :value="0" />
                <el-option label="多条件公式" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="
                formLabelAlign.formulaType == 0 &&
                formLabelAlign.scoreStandard === 1
              "
              label="设置"
              label-position="top"
              prop="sourceValue"
            >
              <div class="w-full flex item-center">
                <div class="mr-4"><el-text>得分 =</el-text></div>
                <jishuanqi
                  v-if="showData && drawer"
                  ref="jishuanqiRef"
                  :outerConditionValue="formulaOne"
                  @handClick="countNoConditionFormulaClick"
                />
                <div class="ml-8">
                  <el-button type="primary" @click="conditionVerifyApi">
                    公式验证
                  </el-button>
                </div>
              </div>
            </el-form-item>
            <el-form-item
              v-if="
                formLabelAlign.formulaType == 1 &&
                formLabelAlign.scoreStandard === 1
              "
              label="设置"
              label-position="top"
              prop="sourceValue"
            >
              <div class="w-full flex item-center">
                <manyFormula
                  v-if="showData"
                  :formulaJSON="formulaOne"
                  @handUpdataClick="countNoConditionFormulaClick"
                />
              </div>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 公式验证 -->
    <el-dialog
      v-model="dialogFormVisibleFormula"
      title="完成值"
      width="500"
      :before-close="quxiaoCmputed"
    >
      <el-form :model="formulaForm">
        <div v-for="(itemF, indexF) in formulaForm" :key="indexF">
          <el-form-item :label="itemF.name">
            <el-input v-model="itemF.value" autocomplete="off" />
          </el-form-item>
        </div>
        <el-form-item label="得分">
          <el-input v-model="grade" class="ml-3" autocomplete="off" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="quxiaoCmputed">取消</el-button>
          <el-button type="primary" @click="countComputed"> 计算 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
