<script setup lang="ts">
import { ref, reactive, watch, onMounted, nextTick } 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 "@/views/evaluate/children/change/components/jishuanqi.vue";
import {
  postListTreeWithUser,
  postListTree,
  postListTreeWithUserApi,
  treeDept
} from "@/api/department";
import type { DrawerProps, FormItemProps, FormProps } from "element-plus";
import { formulaParamsChange } from "@/utils/business";
const $props = defineProps({
  formulaJSON: {
    type: Object
  }
});
onMounted(() => {
  if ($props.formulaJSON) {
    nextTick(() => {
      if (typeof $props.formulaJSON === "string") {
        Object.assign(addmanyChange, JSON.parse($props.formulaJSON));
      } else {
        Object.assign(addmanyChange, $props.formulaJSON);
      }
      console.log(
        "多公式",
        addmanyChange,
        "$props.formulaJSON",
        $props.formulaJSON
      );
    });
    // let a = JSON.parse($props.formulaJSON);
  }
});
const $emit = defineEmits(["handUpdataClick"]);
const keywords = [
  "目标值",
  "完成值",
  "挑战值",
  "门槛值",
  "增幅",
  "降幅",
  "上期完成值",
  "上上期完成值"
];
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 jishuanqiRef = ref();
const countNoConditionFormula = item => {
  addmanyChange.outerConditionValue = item;
  changeAddMay();
};
const countNoConditionFormula1 = (item, index) => {
  addmanyChange.innerConditionExpression[index].endValue = item;
  changeAddMay();
};
const countNoConditionFormula2 = (item, index) => {
  // innerConditionValue
  addmanyChange.innerConditionExpression[
    index
  ].scoreRuleMoreInnerVO[0].innerConditionValue = item;
  changeAddMay();
};
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 changeAddMay = () => {
  let addmanyChangeOldVal = JSON.parse(JSON.stringify(addmanyChange));
  addmanyChange.innerConditionExpression.forEach((item, index, arr) => {
    if (index + 1 <= arr.length) {
      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);
  $emit("handUpdataClick", addmanyChange);
};
const deleteItem = index => {
  addmanyChange.innerConditionExpression.splice(index, 1);
  changeAddMay();
};
const dataleListItemAll = (item, index) => {
  item.scoreRuleMoreInnerVO = [];
  changeAddMay();
};
const dataleListItem = (index, indexList) => {
  addmanyChange.innerConditionExpression[
    index
  ].scoreRuleMoreInnerVO[0].scoreRules.splice(indexList, 1);
  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 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 addNewItemOldValue = item => {
  addmanyChange.innerConditionExpression.push({
    startValue: item.endValue,
    select: null,
    endValue: null,
    comparisonStart: item.comparisonEnd == ">" ? "≥" : ">",
    comparisonEnd: null,
    scoreRuleMoreInnerVO: []
  });
  changeAddMay();
};
const addNewItem = () => {
  addmanyChange.innerConditionExpression.push({
    startValue: null,
    endValue: null,
    select: null,
    comparisonStart: null,
    comparisonEnd: null,
    scoreRuleMoreInnerVO: []
  });
  changeAddMay();
};
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 grade = ref();
const formulaForm = ref([]);
const dialogFormVisibleFormula = ref(false);
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);
            }
          });
        }
      }
    });
  }
};
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 quxiaoCmputed = () => {
  formulaForm.value = [];
  dialogFormVisibleFormula.value = false;
};
const countComputed = async () => {
  try {
    let oldValue = JSON.parse(JSON.stringify(addmanyChange));
    // Object.assign(oldValue, addmanyChange);
    // const formulaPar = JSON.stringify(oldValue);
    const params1 = {
      formulaType: 1,
      formulaParams: formulaParamsChange(oldValue)
    };
    const res = await conditionVerify(params1);
    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({
        ...params1,
        calculateScore: formulaForm.value.reduce((map, item) => {
          map[item.name] = item.value !== null ? item.value : 0; // 用 0 替代 null
          return map;
        }, {})
      });
      if (code == 200) {
        grade.value = data;
      }
    } else {
      ElMessageBox.confirm(
        "如果不修改将无法计算得分",
        "公式计算错误,修改后确认",
        {
          type: "warning"
        }
      ).then(() => {
        dialogFormVisibleFormula.value = false;
      });
    }
  } catch (err) {
    console.log(err);
  }
};
</script>

<template>
  <div class="w-full">
    <div class="flex items-center">
      <el-text>条件值 = </el-text>
      <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"
                @blur="changeAddMay"
              />
            </div>
            <el-text v-if="item.scoreRuleMoreInnerVO.length == 0"
              >得分 =
            </el-text>
            <div>
              <jishuanqi
                v-if="item.scoreRuleMoreInnerVO.length == 0"
                ref="jishuanqiRef"
                :index="index"
                :outerConditionValue="item.innerScore"
                :testString="index + 1"
                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>
              <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"
                    @blur="changeAddMay"
                  />
                </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>
    <!-- 公式验证 -->
    <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>
