<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { calculator } from "./evaluate";
import {
  getIndexInfo,
  postUpdate,
  calculateScoreByConditionMoCondition
} from "@/api/templateInfo";
import { conditionVerify } from "@/api/formula";
import jishuanqi from "./jishuanqi.vue";
import {
  postListTreeWithUser,
  postListTree,
  postListTreeWithUserApi,
  treeDept
} from "@/api/department";
import type { DrawerProps, FormItemProps, FormProps } from "element-plus";
// const itemLabelPosition = ref<FormItemProps["labelPosition"]>("");
const drawer = ref(false);
const disabledValue = ref(true);
const GONG_SHI = [
  "完成值",
  "目标值",
  "门槛值",
  "挑战值",
  "增幅",
  "降幅",
  "上期完成值",
  "上上期完成值"
];
// 判断 score 字符串是否包含 GONG_SHI 中的关键字
function containsKeywordInScore(score, keywordss) {
  // 确保 score 是字符串，keywords 是数组
  if (score && typeof score == "string") {
    const cleanedScore = score.replace(/[\s\-]/g, ""); // 去除空格和破折号
    const cleanedKeywords = keywordss.map(keyword =>
      keyword.replace(/[\s\-]/g, "")
    );
    return cleanedKeywords.some(keyword => cleanedScore.includes(keyword));
    // 遍历 keywords 数组，检查 score 是否包含其中的任何一个关键字
  } else {
    return false;
  }
}
const direction = ref<DrawerProps["direction"]>("rtl");
const formLabelAlign = reactive({
  name: "",
  region: "",
  grade: "",
  compute: "1",
  type: ""
});
const params = reactive({
  id: "",
  tpId: "",
  dimId: "",
  indId: "",
  valueInput: "",
  scoreStandard: 0,
  designatedPersonnel: "",
  remark: "",
  scoreRule: "",
  targetValue: "",
  finalValue: "",
  formulaType: 0,
  challengeValue: "",
  startValue: "",
  datasoure: "",
  weight: "",
  scoreValue: "",
  formula: {
    noConditionFormula: ""
  }
});
// 详情信息
const getIndexInfoApi = async id => {
  const { data, code, msg } = await getIndexInfo(id);
  // console.log("1111", data);
  if (code === 200) {
    Object.assign(params, data);
    if (data.designatedPersonnel) {
      params.personList = data.designatedPersonnel.split(",");
    }
    if (isValidJSON(data.formula)) {
      if (params.formulaType == 0) {
        params.formula = JSON.parse(data.formula);
      } else if (params.formulaType == 1) {
        let aa = JSON.parse(data.formula);
        let bb = JSON.parse(aa.noConditionFormula);
        Object.assign(addmanyChange, bb);
      }
    }
    if (!data.formula) {
      params.formula = {
        noConditionFormula: ""
      };
    } else {
    }
    if (!data.formulaType) {
      params.formulaType = 0;
    }
  } else {
    ElMessage.error(msg);
  }
};
const $emit = defineEmits(["refresh"]);
// 更新指标
const postUpdateApi = async () => {
  if (params.formulaType == 0) {
    params.formula = JSON.stringify(params.formula);
  } else {
    params.formula = {
      noConditionFormula: ""
    };
    // 判断是公式还是数字
    if (containsKeywordInScore(addmanyChange.outerConditionValue, GONG_SHI)) {
      addmanyChange.outerConditionValueExpress =
        addmanyChange.outerConditionValue;
    }
    addmanyChange.innerConditionExpression.map(inn => {
      if (containsKeywordInScore(inn?.startValue, GONG_SHI)) {
        inn.startExpress = inn.startValue;
      }
      if (containsKeywordInScore(inn?.endValue, GONG_SHI)) {
        inn.endExpress = inn.endValue;
      }
      if (containsKeywordInScore(inn?.innerScore, GONG_SHI)) {
        inn.innerScoreExpress = inn.innerScore;
      }
      if (
        containsKeywordInScore(
          inn?.scoreRuleMoreInnerVO[0]?.innerConditionValue,
          GONG_SHI
        )
      ) {
        inn.scoreRuleMoreInnerVO[0].innerConditionValueExpress =
          inn.scoreRuleMoreInnerVO[0].innerConditionValue;
      }
      inn?.scoreRuleMoreInnerVO[0]?.scoreRules.map(isc => {
        if (containsKeywordInScore(isc?.score, GONG_SHI)) {
          isc.scoreExpress = isc.score;
        }
        if (containsKeywordInScore(isc?.startValue, GONG_SHI)) {
          isc.startExpress = isc.startValue;
        }
        if (containsKeywordInScore(isc?.endValue, GONG_SHI)) {
          isc.endExpress = isc.endValue;
        }
      });
    });
    params.formula.noConditionFormula = JSON.stringify(addmanyChange);
    params.formula = JSON.stringify(params.formula);
  }
  const { msg, code } = await postUpdate(params);
  if (code === 200) {
    ElMessage({
      message: "编辑成功",
      type: "success"
    });
    $emit("refresh");
    disabledValue.value = true;
    editShow.value = true;
    drawer.value = !drawer.value;
  } else {
    ElMessage.error(msg);
  }
};
// 公式验证
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 = "";
    console.log("params", params);

    const keywords = [
      "完成值",
      "目标值",
      "门槛值",
      "挑战值",
      "增幅",
      "降幅",
      "上期完成值",
      "上上期完成值"
    ];
    let str = params.formula.noConditionFormula;
    // 创建一个正则表达式，匹配这些关键词
    const regex = new RegExp(keywords.join("|"), "g");
    // 提取字符串中的所有关键词
    let matches = str.match(regex);
    console.log("匹配到的关键词:", matches);
    matches.forEach(matchItem => {
      formulaForm.value.push({
        name: matchItem,
        value: ""
      });
    });
    let result = str.replace(regex, match => {
      return `${match}`;
    });
  } catch (err) {
    //
  }
};
// 计算
// 多条件公式计算
function reverseReplace(oldValue, dataObject) {
  // 确保 formulaForm 是一个数组
  if (!Array.isArray(oldValue)) {
    throw new Error("formulaForm 应该是一个数组");
  }
  oldValue.forEach(item => {
    // 遍历外部条件和内部条件的表达式
    for (const key in dataObject) {
      const value = dataObject[key];

      if (typeof value === "string") {
        // 如果字符串中包含当前name，则替换该值
        if (value.includes(item.name)) {
          dataObject[key] = value.replace(item.name, item.value);
        }
      } else if (Array.isArray(value)) {
        // 如果是数组，递归替换数组中的每个对象
        value.forEach(innerObj => {
          for (const innerKey in innerObj) {
            const innerValue = innerObj[innerKey];
            if (
              typeof innerValue === "string" &&
              innerValue.includes(item.name)
            ) {
              innerObj[innerKey] = innerValue.replace(item.name, item.value);
            }
          }
        });
      }
    }
  });
  return dataObject;
}
function calculateScore(inputString) {
  // 将 formulaForm.value 转换为一个键值对映射，方便替换
  const valueMap = formulaForm.value.reduce((map, item) => {
    map[item.name] = item.value !== null ? item.value : 0; // 用 0 替代 null
    return map;
  }, {});

  // 替换字符串中的关键字为对应的 value 值
  let formula = inputString;
  for (const [key, value] of Object.entries(valueMap)) {
    if (formula.includes(key)) {
      // 使用正则替换所有匹配的关键字
      const regex = new RegExp(key, "g");
      formula = formula.replace(regex, value);
    }
  }

  try {
    // 使用 eval 计算公式
    const result = eval(formula);
    return result;
  } catch (error) {
    console.error("公式计算出错:", error);
    return null;
  }
}

const countComputed = async () => {
  try {
    if (params.formulaType == 0) {
      const formula = JSON.stringify(params.formula);
      // const aa = JSON.stringify(formula);
      // console.log("formula", aa);
      const { code, msg } = await conditionVerify({
        formulaType: params.formulaType,
        formula
      });
      if (code == 200) {
        const keywords = [
          "完成值",
          "目标值",
          "门槛值",
          "挑战值",
          "增幅",
          "降幅",
          "上期完成值",
          "上上期完成值"
        ];
        let str = params.formula.noConditionFormula;
        // 创建一个正则表达式，匹配这些关键词
        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;
        });
      }
    } else if (params.formulaType == 1) {
      let oldValue = JSON.parse(JSON.stringify(addmanyChange));
      // Object.assign(oldValue, addmanyChange);
      const formulaPar = JSON.stringify(oldValue);
      const res = await conditionVerify({
        formulaType: params.formulaType,
        formula: formulaPar
      });
      if (res.code == 200) {
        if (oldValue.outerConditionValue) {
          oldValue.outerConditionValue = calculateScore(
            oldValue.outerConditionValue
          );
        }
        if (oldValue.innerConditionExpression.length > 0) {
          oldValue.innerConditionExpression.map(itEx => {
            if (itEx.startValue) {
              itEx.startValue = calculateScore(itEx.startValue);
            }
            if (itEx.endValue) {
              itEx.endValue = calculateScore(itEx.endValue);
            }
            if (itEx.innerScore) {
              itEx.innerScore = calculateScore(itEx.innerScore);
            }
            if (itEx?.scoreRuleMoreInnerVO[0]?.innerConditionValue) {
              itEx.scoreRuleMoreInnerVO[0].innerConditionValue = calculateScore(
                itEx.scoreRuleMoreInnerVO[0].innerConditionValue
              );
            }
            if (itEx?.scoreRuleMoreInnerVO[0]?.scoreRules.length > 0) {
              itEx.scoreRuleMoreInnerVO[0].scoreRules.map(itRule => {
                if (itRule.score) {
                  itRule.score = calculateScore(itRule.score);
                }
                if (itRule.startValue) {
                  itRule.startValue = calculateScore(itRule.startValue);
                }
                if (itRule.endValue) {
                  itRule.endValue = calculateScore(itRule.endValue);
                }
              });
            }
          });
        }
        // let newValue = reverseReplace(formListNum, oldValue);
        const { code, msg, data } =
          await calculateScoreByConditionMoCondition(oldValue);
        if (code == 200) {
          grade.value = data;
        }
      } else {
        ElMessageBox.confirm(
          "如果不修改将无法计算得分",
          "公式计算错误,修改后确认",
          {
            type: "warning"
          }
        ).then(() => {
          dialogFormVisibleFormula.value = false;
        });
      }
    }
  } catch (err) {
    console.log(err);
  }
};
// 判断是否为json
function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true; // 如果解析成功，返回true
  } catch (e) {
    return false; // 如果解析失败，返回false
  }
}
const handleClose = (done: () => void) => {
  drawer.value = false;
  disabledValue.value = true;
  editShow.value = true;
  // ElMessageBox.confirm("配置项未保存，确认关闭", {
  //   type: "warning"
  // }).then(() => {

  // });
};
function cancelClick() {
  drawer.value = false;
  Object.assign(params, {
    id: "",
    tpId: "",
    dimId: "",
    indId: "",
    valueInput: "",
    scoreStandard: 0,
    remark: "",
    scoreRule: "",
    targetValue: "",
    finalValue: "",
    formulaType: 0,
    challengeValue: "",
    startValue: "",
    datasoure: "",
    weight: "",
    scoreValue: "",
    formula: {
      noConditionFormula: ""
    }
  });
  disabledValue.value = true;
  editShow.value = true;
}
function confirmClick() {
  postUpdateApi();
}
const open = row => {
  drawer.value = true;
  params.designatedPersonnel = "";
  Object.assign(params, {
    id: "",
    tpId: "",
    dimId: "",
    indId: "",
    valueInput: "",
    designatedPersonnel: "",
    scoreStandard: 0,
    remark: "",
    scoreRule: "",
    targetValue: "",
    finalValue: "",
    formulaType: 0,
    challengeValue: "",
    startValue: "",
    datasoure: "",
    weight: "",
    scoreValue: "",
    personList: "",
    formula: {
      noConditionFormula: ""
    }
  });
  Object.assign(addmanyChange, {
    outerConditionValue: "",
    outerConditionValueExpress: "",
    innerConditionExpression: [
      {
        startValue: null,
        endValue: null,
        select: null,
        comparisonStart: null,
        comparisonEnd: null,
        innerScore: null,
        innerScoreExpress: null,
        scoreRuleMoreInnerVO: []
      }
    ]
  });
  getIndexInfoApi(row.id);
  calculatorShow.value = true;
};
const editShow = ref(true);
defineExpose({
  open
});
const timer = ref("");
// 公式计算
const compute = [
  {
    value: 0,
    label: "无条件公式"
  },
  {
    value: 1,
    label: "多条件公式"
  }
];
const bgColor = ref(null);
const rolesList = reactive({
  data: [
    { name: "完成值 / 目标值", id: 1 },
    { name: "完成值 - 目标值", id: 2 },
    { name: "目标值 - 完成值", id: 3 },
    { name: "门槛值", id: 4 },
    { name: "目标值", id: 5 },
    { name: "挑战值", id: 6 },
    { name: "完成值", id: 7 },
    { name: "增幅", id: 8 },
    { name: "降幅", id: 9 },
    { name: "上期完成值", id: 10 },
    { name: "上上期完成值", id: 11 }
  ],
  value: "",
  num: null
});
// 监听formulaType变化
const watchFormulaType = value => {
  if (value == 0 && typeof params.formula == "string") {
    let aa = JSON.parse(params.formula);
    params.formula = aa;
    params.formula.noConditionFormula = "";
  }
};
const lookRoles = item => {
  if (isValidJSON(params.formula)) {
    params.formula = JSON.parse(params.formula);
  }
  bgColor.value = item.id;
  params.formula.noConditionFormula =
    params.formula.noConditionFormula + item.name;
};
// 字符拼接
const countNumber = (item: string) => {
  params.formula.noConditionFormula = params.formula.noConditionFormula + item;
};
// 清除
const remove = () => {
  if (params.formula.noConditionFormula.length > 0) {
    params.formula.noConditionFormula = params.formula.noConditionFormula.slice(
      0,
      -1
    );
  }
};
// 清空
const removeVoid = () => {
  params.formula.noConditionFormula = "";
};
// 计算确认
//
const calculatorShow = ref(true);
const count = item => {
  ElMessageBox.confirm("配置项确认保存？确认关闭", {
    type: "warning"
  }).then(() => {
    calculatorShow.value = false;
  });
  // try {
  //   calculator.calculate(rolesList.value);
  //   rolesList.num = calculator.get();
  // } catch (error) {
  //   ElMessage({
  //     message: "计算错误",
  //     type: "warning"
  //   });
  //   console.log(error);
  // }
};
// 多条件公式
const addmanyChange = reactive({
  outerConditionValue: "",
  outerConditionValueExpress: "",
  innerConditionExpression: [
    {
      startValue: null,
      endValue: null,
      select: null,
      comparisonStart: null,
      comparisonEnd: null,
      innerScore: null,
      innerScoreExpress: null,
      scoreRuleMoreInnerVO: [
        // {
        //   innerConditionValue: null,
        //   scoreRules: [
        //     {
        //       score: null,
        //       startValue: null,
        //       select: "",
        //       endValue: null,
        //       comparisonStart: null,
        //       comparisonEnd: null
        //     }
        //   ]
        // }
      ]
    }
  ]
});
// 添加子条件
const addItemFormulaList = (item, index) => {
  addmanyChange.innerConditionExpression[index].scoreRuleMoreInnerVO = [
    {
      innerConditionValue: null,
      innerConditionValueExpress: null,
      scoreRules: [
        {
          score: null,
          scoreExpress: null,
          startValue: null,
          startExpress: null,
          endValue: null,
          endExpress: null,
          select: null,
          comparisonStart: null,
          comparisonEnd: null
        }
      ]
    }
  ];
  addmanyChange.innerConditionExpression[index].innerScore = "";
  changeAddMay();
};

const deleteItem = index => {
  addmanyChange.innerConditionExpression.splice(index, 1);
  changeAddMay();
};
const dataleListItem = (index, indexList) => {
  addmanyChange.innerConditionExpression[
    index
  ].scoreRuleMoreInnerVO[0].scoreRules.splice(indexList, 1);
  changeAddMay();
};
// 条件变量
const dataleListItemAll = (item, index) => {
  item.scoreRuleMoreInnerVO = [];
  changeAddMay();
};
const addNewItem = () => {
  addmanyChange.innerConditionExpression.push({
    startValue: null,
    endValue: null,
    select: null,
    comparisonStart: null,
    comparisonEnd: null,
    scoreRuleMoreInnerVO: []
  });
  changeAddMay();
};
const addNewItemOldValue = item => {
  addmanyChange.innerConditionExpression.push({
    startValue: item.endValue,
    select: null,
    endValue: null,
    comparisonStart: item.comparisonEnd == ">" ? "≥" : ">",
    comparisonEnd: null,
    scoreRuleMoreInnerVO: []
  });
  changeAddMay();
};
const addItemDataList = (
  index: number,
  itemList: any,
  indexList: number,
  item
) => {
  addmanyChange.innerConditionExpression[
    index
  ].scoreRuleMoreInnerVO[0].scoreRules.push({
    select: null,
    score: null,
    scoreExpress: null,
    startValue: itemList.endValue,
    endValue: null,
    comparisonStart: itemList.comparisonEnd,
    comparisonEnd: null
  });
  addmanyChange.innerConditionExpression[index].innerScore = "";
  changeAddMay();
};
// 多条件公式验证
const keywords = [
  "目标值",
  "完成值",
  "挑战值",
  "门槛值",
  "增幅",
  "降幅",
  "上期完成值",
  "上上期完成值"
];
// 处理字符串，提取关键词
function extractKeywords(value) {
  // 如果是字符串，处理包含的关键词
  if (typeof value === "string") {
    // 提取所有关键词
    keywords.forEach(keyword => {
      if (value.includes(keyword)) {
        formulaForm.value.push({
          name: keyword,
          value: null // 可以根据需求赋值
        });
      }
    });
  }
}
// 遍历对象并处理
function traverseObject(obj) {
  if (obj && typeof obj === "object") {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        const value = obj[key];

        // 如果值是字符串，调用提取函数
        if (typeof value === "string") {
          extractKeywords(value);
        }

        // 如果值是数组，递归处理
        if (Array.isArray(value)) {
          value.forEach(item => traverseObject(item));
        }
      }
    }
  }
}
function extractKeywordsAndPush(keywordsList, inputString) {
  keywords.forEach(keyword => {
    if (
      inputString?.includes(keyword) && // 检查字符串是否包含关键字
      !formulaForm.value.some(item => item.name === keyword) // 确保没有重复
    ) {
      // 如果包含且未重复，构造对象并push到formulaForm.value
      formulaForm.value.push({
        name: keyword,
        value: null // 根据需求赋值
      });
    }
  });

  return formulaForm;
}
const manyConditions = () => {
  grade.value = null;
  dialogFormVisibleFormula.value = true;
  formulaForm.value = [];
  // 提取 addmanyChange 对象中的条件值
  let oldValue = addmanyChange;
  if (oldValue.outerConditionValue) {
    extractKeywordsAndPush(keywords, oldValue.outerConditionValue);
  }
  if (oldValue.innerConditionExpression.length > 0) {
    oldValue.innerConditionExpression.map(itemExp => {
      if (itemExp.startValue) {
        extractKeywordsAndPush(keywords, itemExp.startValue);
      }
      if (itemExp.endValue) {
        extractKeywordsAndPush(keywords, itemExp.endValue);
      }
      if (itemExp.innerScore) {
        extractKeywordsAndPush(keywords, itemExp.innerScore);
      }
      if (itemExp?.scoreRuleMoreInnerVO[0]?.innerConditionValue) {
        extractKeywordsAndPush(
          keywords,
          itemExp.scoreRuleMoreInnerVO[0].innerConditionValue
        );
      }
      if (itemExp?.scoreRuleMoreInnerVO.length > 0) {
        if (itemExp?.scoreRuleMoreInnerVO[0]?.scoreRules.length > 0) {
          itemExp?.scoreRuleMoreInnerVO[0]?.scoreRules.map(itSc => {
            if (itSc.score) {
              extractKeywordsAndPush(keywords, itSc.score);
            }
            if (itSc.startValue) {
              extractKeywordsAndPush(keywords, itSc.startValue);
            }
            if (itSc.endValue) {
              extractKeywordsAndPush(keywords, itSc.endValue);
            }
          });
        }
      }
    });
  }
};
// 计算器
const jishuanqiRef = ref();
const countNoConditionFormula = item => {
  addmanyChange.outerConditionValue = item;
  changeAddMay();
};
const jishuanqiRef1 = ref();
const countNoConditionFormula1 = (item, index) => {
  addmanyChange.innerConditionExpression[index].endValue = item;
  changeAddMay();
};
const jishuanqiRef2 = ref();
const countNoConditionFormula2 = (item, index) => {
  // innerConditionValue
  addmanyChange.innerConditionExpression[
    index
  ].scoreRuleMoreInnerVO[0].innerConditionValue = item;
  changeAddMay();
};
const jishuanqiRef3 = ref();
const countNoConditionFormula3 = (item, index, indexList) => {
  addmanyChange.innerConditionExpression[
    index
  ].scoreRuleMoreInnerVO[0].scoreRules[indexList].endValue = item;
  changeAddMay();
};
const countNoConditionFormula4 = (item, index, indexList) => {
  addmanyChange.innerConditionExpression[
    index
  ].scoreRuleMoreInnerVO[0].scoreRules[indexList].score = item;
  changeAddMay();
};
const countNoConditionFormulaInnerScore = (item, index, indexList) => {
  addmanyChange.innerConditionExpression[index].innerScore = item;
  changeAddMay();
};

// 转换函数 --- 人员
const convertDepartmentDataRecursive_Person = data => {
  return data.map(department => {
    const { userNameNew, userCodeNew, children } = department;
    return {
      value: userCodeNew,
      label: userNameNew,
      children:
        children.length > 0
          ? children.map(
              child => convertDepartmentDataRecursive_Person([child])[0]
            )
          : []
    };
  });
};
postListTreeWithUserApi();
const assessmentTypeRef = ref();
const handleRreeSelect = () => {
  const arr = assessmentTypeRef.value.getCheckedNodes().filter(item => {
    return item.children.length == 0;
  });
  params.designatedPersonnel = arr.map(item => item.value).join(",");
};
// 取消计算
const quxiaoCmputed = () => {
  formulaForm.value = [];
  dialogFormVisibleFormula.value = false;
};
// 监听数据变化
const changeAddMay = () => {
  let addmanyChangeOldVal = JSON.parse(JSON.stringify(addmanyChange));
  addmanyChange.innerConditionExpression.forEach((item, index, arr) => {
    if (index + 1 <= arr.length) {
      console.log("12312", addmanyChangeOldVal.innerConditionExpression);
      if (item.endValue) {
        if (addmanyChangeOldVal.innerConditionExpression.length > 1) {
          addmanyChangeOldVal.innerConditionExpression[index + 1].startValue =
            item?.endValue;
          addmanyChangeOldVal.innerConditionExpression[index + 1].startExpress =
            item?.endExpress;
          addmanyChangeOldVal.innerConditionExpression[
            index + 1
          ].comparisonStart = item?.comparisonEnd == "≥" ? ">" : "≥";
        }
      }
      if (item.scoreRuleMoreInnerVO.length > 0) {
        if (item.scoreRuleMoreInnerVO[0].scoreRules.length > 0) {
          item.scoreRuleMoreInnerVO[0].scoreRules.map((it, id, arrChild) => {
            if (id + 1 <= arrChild.length) {
              if (it.endValue) {
                // if (
                //   addmanyChangeOldVal.innerConditionExpression[index + 1]
                //     .scoreRuleMoreInnerVO.length > 0
                // ) {
                addmanyChangeOldVal.innerConditionExpression[
                  index
                ].scoreRuleMoreInnerVO[0].scoreRules[id + 1].startValue =
                  it?.endValue;
                addmanyChangeOldVal.innerConditionExpression[
                  index
                ].scoreRuleMoreInnerVO[0].scoreRules[id + 1].startExpress =
                  it?.startExpress;
                addmanyChangeOldVal.innerConditionExpression[
                  index
                ].scoreRuleMoreInnerVO[0].scoreRules[id + 1].comparisonStart =
                  it?.comparisonEnd == "≥" ? ">" : "≥";
                // }
              }
            }
          });
        }
      }
    }
  });
  Object.assign(addmanyChange, addmanyChangeOldVal);
};
const formulaFocus = () => {
  calculatorShow.value = true;
};
// { deep: true };
</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 label-position="top" label-width="auto" :model="params">
            <el-form-item label="完成值录入人" label-position="top">
              <el-select v-model="params.valueInput" placeholder="请选择">
                <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-tree-select
                v-if="params.valueInput == 2"
                ref="assessmentTypeRef"
                v-model="params.personList"
                multiple
                :data="convertDepartmentDataRecursive_Person(treeDept)"
                :render-after-expand="false"
                show-checkbox
                style="margin-top: 10px"
                @check-change="handleRreeSelect()"
              />
            </el-form-item>
            <el-form-item label="评分方式" label-position="top">
              <el-select v-model="params.scoreStandard" placeholder="请选择">
                <el-option label="手动输入" :value="0" />
                <el-option label="公式自动计算" :value="1" />
              </el-select>
            </el-form-item>
            <div v-if="params.scoreStandard === 1">
              <el-form-item label="公式类型" label-position="top">
                <el-select
                  v-model="params.formulaType"
                  placeholder="请选择"
                  @change="watchFormulaType"
                >
                  <el-option
                    v-for="item in compute"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                v-if="params.formulaType === 0"
                label="公式设置"
                label-position="top"
              >
                <div>
                  <div>
                    <el-text>得分 =</el-text>
                    <el-input
                      v-model="params.formula.noConditionFormula"
                      class="ml-2 mr-2"
                      style="width: 240px"
                      @focus="formulaFocus"
                    />
                    <el-text>
                      <el-button type="primary" @click="conditionVerifyApi"
                        >公式验证</el-button
                      >
                    </el-text>
                  </div>
                  <div
                    v-if="calculatorShow"
                    class="w-[500px] compute h-64 mt-1 ml-12 flex justify-evenly items-center"
                    style="user-select: none"
                  >
                    <div class="w-1/3 h-60 pl-1 bg-white rounded-md">
                      <div class="w-[100%] text-xs mt-2">
                        <div><el-text type="info">:::变量</el-text></div>
                      </div>
                      <el-scrollbar height="200px">
                        <div v-for="item in rolesList.data" :key="item.id">
                          <div
                            :class="[
                              'cursor-pointer text-xs mt-1',
                              { bgBack: bgColor === item.id }
                            ]"
                            @click="lookRoles(item)"
                          >
                            <el-text class="">{{ item.name }}</el-text>
                          </div>
                        </div>
                      </el-scrollbar>
                    </div>
                    <div class="w-3/5 ml-2 h-60 flex flex-col">
                      <div class="w-[100%] text-xs h-24 bg-white rounded-md">
                        <div class="p-1"><el-text>得分 = </el-text></div>
                        <!-- style="height: 95px" -->
                        <el-input
                          v-model="params.formula.noConditionFormula"
                          :rows="3"
                          disabled
                          type="textarea"
                          placeholder='示例:"完成值" / "目标值" * 100'
                        />
                      </div>
                      <div class="w-[100%] h-32 mt-2 rounded-md flex flex-col">
                        <div class="flex justify-between h-8">
                          <div
                            class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="countNumber('1')"
                          >
                            1
                          </div>
                          <div
                            class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="countNumber('2')"
                          >
                            2
                          </div>
                          <div
                            class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="countNumber('3')"
                          >
                            3
                          </div>
                          <div
                            class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="countNumber('+')"
                          >
                            +
                          </div>
                          <div
                            class="h-full w-[50px] text-white bg-orange-400 mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="remove"
                          >
                            x
                          </div>
                        </div>
                        <div class="flex justify-between h-8 mt-1">
                          <div
                            class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="countNumber('4')"
                          >
                            4
                          </div>
                          <div
                            class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="countNumber('5')"
                          >
                            5
                          </div>
                          <div
                            class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="countNumber('6')"
                          >
                            6
                          </div>
                          <div
                            class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="countNumber('-')"
                          >
                            -
                          </div>
                          <div
                            class="text-xs h-full w-[50px] text-white bg-orange-400 mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                            @click="removeVoid"
                          >
                            清空
                          </div>
                        </div>
                        <div class="flex justify-between h-16 mt-1">
                          <div>
                            <div class="flex justify-between">
                              <div
                                class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                                @click="countNumber('7')"
                              >
                                7
                              </div>
                              <div
                                class="h-full ml-1 w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                                @click="countNumber('8')"
                              >
                                8
                              </div>
                              <div
                                class="h-full ml-2 w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                                @click="countNumber('9')"
                              >
                                9
                              </div>
                              <div
                                class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                                @click="countNumber('*')"
                              >
                                *
                              </div>
                            </div>
                            <div class="flex mt-1 justify-between">
                              <div
                                class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                                @click="countNumber('0')"
                              >
                                0
                              </div>
                              <div
                                class="h-full ml-1 w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                                @click="countNumber('.')"
                              >
                                .
                              </div>
                              <div
                                class="h-full ml-2 w-[50px] bg-white mx-1 flex justify-between items-center rounded-lg cursor-pointer"
                              >
                                <div
                                  class="w-1/2 h-full text-center border-r text-gray-100"
                                  @click="countNumber('(')"
                                >
                                  <span class="text-black"> (</span>
                                </div>
                                <div
                                  class="w-1/2 h-full text-center"
                                  @click="countNumber(')')"
                                >
                                  )
                                </div>
                              </div>
                              <div
                                class="h-full w-[50px] bg-white mx-1 flex justify-center items-center rounded-lg cursor-pointer"
                                @click="countNumber('/')"
                              >
                                /
                              </div>
                            </div>
                          </div>
                          <div
                            class="h-full mr-1 w-[50px] text-white flex justify-center items-center rounded-lg cursor-pointer areYouOK"
                            @click="count"
                          >
                            确认
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item v-else label="公式设置">
                <div class="w-full">
                  <div class="flex items-center">
                    <el-text>条件值 = </el-text>
                    <!-- <el-input
                      v-model="addmanyChange.outerConditionValue"
                      class="ml-2"
                      style="width: 240px"
                    /> -->
                    <jishuanqi
                      ref="jishuanqiRef"
                      :outerConditionValue="addmanyChange.outerConditionValue"
                      @handClick="countNoConditionFormula"
                    />
                  </div>
                  <div class="w-full mt-2">
                    <div
                      v-for="(
                        item, index
                      ) in addmanyChange.innerConditionExpression"
                      :key="index"
                    >
                      <div class="mt-3">
                        <div class="flex">
                          <el-text class="w-[15px]" type="primary">
                            {{ index + 1 }}
                          </el-text>
                          <div class="w-[40px] ml-4">
                            {{ item.startValue }}
                          </div>
                          <div class="mr-2">
                            {{ item.comparisonStart }}
                          </div>
                          <div class="mr-2">条件值</div>
                          <el-select
                            v-model="item.comparisonEnd"
                            style="width: 60px"
                            placeholder=""
                            :disabled="
                              index + 1 ==
                                addmanyChange.innerConditionExpression.length &&
                              index >= 1
                                ? true
                                : false
                            "
                          >
                            <el-option label=">" value=">" />
                            <el-option label="≥" value="≥" />
                          </el-select>
                          <el-select
                            v-model="item.select"
                            class="ml-2"
                            style="width: 80px"
                            placeholder=""
                            :disabled="
                              index + 1 ==
                                addmanyChange.innerConditionExpression.length &&
                              index >= 1
                                ? true
                                : false
                            "
                          >
                            <el-option label="数值" value="数值" />
                            <el-option label="公式" value="公式" />
                          </el-select>
                          <el-input
                            v-if="
                              index + 1 ==
                                addmanyChange.innerConditionExpression.length &&
                              index >= 1
                            "
                            disabled
                            class="ml-2 mr-5"
                            style="width: 80px"
                          />
                          <div v-else>
                            <jishuanqi
                              v-if="item.select == '公式'"
                              ref="jishuanqiRef"
                              :index="index"
                              :outerConditionValue="item.endValue"
                              class="ml-2 mr-5"
                              style="width: 80px"
                              @handClick="countNoConditionFormula1"
                            />
                            <el-input
                              v-else
                              v-model="item.endValue"
                              class="ml-2 mr-5"
                              style="width: 80px"
                            />
                          </div>
                          <el-text v-if="item.scoreRuleMoreInnerVO.length == 0"
                            >得分 =
                          </el-text>
                          <!-- <el-input
                            v-if="
                              index + 1 ==
                                addmanyChange.innerConditionExpression.length &&
                              index >= 1
                            "
                            disabled
                            class="ml-2 mr-5"
                            style="width: 100px"
                          /> -->
                          <div>
                            <jishuanqi
                              v-if="item.scoreRuleMoreInnerVO.length == 0"
                              ref="jishuanqiRef"
                              :index="index"
                              :outerConditionValue="item.innerScore"
                              class="ml-2 mr-6"
                              style="width: 100px"
                              @handClick="countNoConditionFormulaInnerScore"
                            />
                          </div>
                          <el-text type="danger" @click="deleteItem(index)">
                            <el-icon>
                              <Delete />
                            </el-icon>
                          </el-text>
                        </div>
                        <div
                          v-for="(itemVO, indexOV) in item.scoreRuleMoreInnerVO"
                          :key="indexOV"
                        >
                          <div class="flex mt-2 ml-20">
                            <div class="mr-2">条件值{{ index + 1 }} =</div>
                            <!-- <el-input v-if="
                              index + 1 ==
                              addmanyChange.innerConditionExpression
                                .length && index >= 1
                            " disabled class="ml-2 mr-6" style="width: 208px" /> -->
                            <jishuanqi
                              ref="jishuanqiRef"
                              :index="index"
                              :outerConditionValue="itemVO.innerConditionValue"
                              class="ml-2 mr-6"
                              style="width: 208px"
                              @handClick="countNoConditionFormula2"
                            />
                            <!-- <el-input v-model="itemVO.innerConditionValue" class="ml-2 mr-6" style="width: 208px" /> -->
                            <el-text
                              type="danger"
                              @click="dataleListItemAll(item, index)"
                            >
                              <el-icon>
                                <Delete />
                              </el-icon>
                            </el-text>
                          </div>
                          <div
                            v-for="(itemList, indexList) in itemVO.scoreRules"
                            :key="indexList"
                            class="ml-3"
                          >
                            <div class="flex mt-2 ml-16 items-center">
                              <div class="text_border">{{ indexList + 1 }}</div>
                              <!-- manyChange.dataList[index].dataList -->
                              <div class="w-[40px] ml-2">
                                {{ itemList.startValue }}
                              </div>
                              <div class="mr-2">
                                {{ itemList.comparisonStart }}
                              </div>
                              <div class="mr-2">条件值{{ index + 1 }}</div>
                              <el-select
                                v-model="itemList.comparisonEnd"
                                style="width: 60px"
                                placeholder=""
                                :disabled="
                                  indexList + 1 == itemVO.scoreRules.length
                                    ? true
                                    : false
                                "
                              >
                                <el-option label=">" value=">" />
                                <el-option label="≥" value="≥" />
                              </el-select>
                              <el-select
                                v-model="itemList.select"
                                class="ml-2"
                                style="width: 80px"
                                placeholder=""
                                :disabled="
                                  indexList + 1 == itemVO.scoreRules.length
                                    ? true
                                    : false
                                "
                              >
                                <el-option label="数值" value="数值" />
                                <el-option label="公式" value="公式" />
                              </el-select>
                              <el-input
                                v-if="indexList + 1 == itemVO.scoreRules.length"
                                disabled
                                class="ml-2"
                                style="width: 80px"
                              />
                              <div v-else>
                                <jishuanqi
                                  v-if="itemList.select == '公式'"
                                  ref="jishuanqiRef"
                                  :index="index"
                                  :indexList="indexList"
                                  :outerConditionValue="itemList.endValue"
                                  class="ml-2"
                                  style="width: 80px"
                                  @handClick="countNoConditionFormula3"
                                />
                                <el-input
                                  v-else
                                  v-model="itemList.endValue"
                                  class="ml-2"
                                  style="width: 80px"
                                />
                              </div>
                              <div
                                class="w-[150px] ml-2 mr-2 flex justify-between items-center"
                              >
                                <div>得分</div>
                                <div>=</div>
                                <!-- <el-input v-if="
                                  indexList + 1 == itemVO.scoreRules.length &&
                                  index >= 1
                                " disabled class="ml-2" style="width: 80px" /> -->
                                <jishuanqi
                                  ref="jishuanqiRef"
                                  :index="index"
                                  :indexList="indexList"
                                  :outerConditionValue="itemList.score"
                                  class="ml-2"
                                  style="width: 80px"
                                  @handClick="countNoConditionFormula4"
                                />
                                <!-- <el-input
                                  v-model="itemList.score"
                                  class="ml-2"
                                  style="width: 80px"
                                /> -->
                              </div>
                              <el-text
                                type="danger"
                                @click="dataleListItem(index, indexList)"
                              >
                                <el-icon>
                                  <Delete />
                                </el-icon>
                              </el-text>
                            </div>
                            <div
                              v-if="indexList + 1 == itemVO.scoreRules.length"
                              class="ml-16 mt-2 text-xs cursor-pointer"
                            >
                              <el-text
                                type="primary"
                                @click="
                                  addItemDataList(
                                    index,
                                    itemList,
                                    indexList,
                                    item
                                  )
                                "
                              >
                                <el-icon>
                                  <Plus />
                                </el-icon>
                                添加子条件
                              </el-text>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div
                        v-if="item?.scoreRuleMoreInnerVO?.length == 0"
                        class="ml-20 mt-2 text-xs cursor-pointer"
                      >
                        <el-text
                          type="primary"
                          @click="addItemFormulaList(item, index)"
                        >
                          <el-icon>
                            <Plus />
                          </el-icon>
                          添加子条件
                        </el-text>
                      </div>
                      <div
                        v-if="
                          addmanyChange.innerConditionExpression.length >= 1 &&
                          index + 1 ==
                            addmanyChange.innerConditionExpression.length
                        "
                        class="mt-5 text-xs cursor-pointer"
                      >
                        <el-text
                          type="primary"
                          @click="addNewItemOldValue(item)"
                        >
                          <el-icon>
                            <Plus />
                          </el-icon>
                          添加条件
                        </el-text>
                      </div>
                    </div>
                    <div
                      v-if="addmanyChange.innerConditionExpression.length < 1"
                      class="mt-5 text-xs cursor-pointer"
                    >
                      <el-text type="primary" @click="addNewItem">
                        <el-icon>
                          <Plus />
                        </el-icon>
                        添加条件
                      </el-text>
                    </div>
                    <div class="float-right mr-8">
                      <el-button type="primary" @click="manyConditions"
                        >公式验证</el-button
                      >
                    </div>
                  </div>
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div>
          <el-button @click="cancelClick">取消</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>
<style lang="scss" scoped>
.compute {
  // border: 1px solid #f3f3f3;
  background-color: #f3f3f3;
  border-radius: 5px;
}

.text-color {
  color: #f3f3f3;
}

.areYouOK {
  background-color: #409eff;
}

.bgBack {
  background-color: #f3f3f3;
}

.text_border {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  // margin-top: 5px;
  margin-right: 5px;
  font-size: 12px;
  border: 1px solid gray;
  border-radius: 50%;
}
</style>
