<template>
  <div style="margin:10px">
    <a-divider style="border-color: #7cb305" dashed></a-divider>
    <blockquote>
      <template v-if="existHistory">
        <a-button type="link" @click="handleShowHistory" v-show="!showHistory">显示历史记录</a-button>
        <a-button type="link" @click="handleHideHistory" v-show="showHistory">隐藏历史记录</a-button>
      </template>

      <template v-if="existFillDes">
        <a-button type="link" @click="handleShowFillDes" v-show="!showFillDes">查看填报说明</a-button>
        <a-button type="link" @click="handleHidenFillDes" v-show="showFillDes">隐藏填报说明</a-button>
      </template>

      <template v-if="existDataValid">
        <a-button type="link" @click="handleShowValidResult" v-show="!showDataValid">显示校验结果</a-button>
        <a-button type="link" @click="handleHidenValidResult" v-show="showDataValid">隐藏校验结果</a-button>
      </template>
    </blockquote>
  </div>

  <div v-if="showHistory" style="width:90%">
    <vxe-table
      keep-source
      ref="refActTable"
      size="small"
      show-overflow
      min-height="100"
      max-height="300"
      :data="historyDataList"
      :show-radio="true"
      :row-config="{ isCurrent: true, isHover: true }"
      @cell-click="rowChangeEvent"
      :columnConfig="{ resizable: true }"
      :scroll-y="{ enabled: true, gt: 50 }"
      :radio-config="{ labelField: 'name', highlight: true }"
    >
      <vxe-column type="seq" width="10%" />
      <vxe-column field="createTime" sortable type="html" title="填报时间" />
      <vxe-column field="content" sortable type="html" title="填报内容" />
      <vxe-column field="createBy" sortable type="html" title="填写人" />
      <vxe-column field="rind" sortable type="html" title="行号" />
      <vxe-column field="id" title="" :visible="false" />
    </vxe-table>
  </div>

  <div v-if="showFillDes" style="margin: 20px 0px; width:90%; line-height: 40px;">
    {{ curTplItem?.des }}
  </div>

  <div v-if="showDataValid" style="margin: 10px 0px; width:90%;">
    <a-result :status="resultStatus">
      <template #title>
          {{ resultStatus=="warning"?"缺少参数值":"" }}
      </template>
      <div v-if="formulaDataList.length > 0">
        <vxe-table  :show-header="false" border stripe :data="formulaDataList" :column-config="{ resizable: true }">
          <vxe-column field="name" title="项目" width="100"></vxe-column>
          <vxe-column field="content" title="内容"></vxe-column>
        </vxe-table>
      </div>
    </a-result>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { evaluate } from 'mathjs';


// 响应式状态
const existHistory = ref(false);
const existFillDes = ref(false);
const existDataValid = ref(false);

const showHistory = ref(false);
const showFillDes = ref(false);
const showDataValid = ref(false);

const resultStatus = ref<"success" | "error" | "warning">("warning");

// 数据
const historyDataList = ref<any[]>([]);
const validFormula = ref<any>(null);
const curTplItem = ref<any>(null);
const curTask = ref<any>(null);
const formulaDataList = ref<{ name: string; content: string }[]>([]);

// API URLs
const histroyUrl = '/baosong/baosongTaskRecord/queryRecord';
const tplItemUrl = '/baosong/baosongTplItem/queryById';
const validDataUrl = '/baosong/baosongDataValid/validData';

// 初始化数据
const iniData = async (tplItem: any, task: any) => {
  // 重置状态
  historyDataList.value = [];
  existHistory.value = false;
  showFillDes.value = false;
  existFillDes.value = false;
  curTplItem.value = {};
  showHistory.value = false;
  existDataValid.value = false;
  showDataValid.value = false;
  formulaDataList.value = [];

   

  if (!tplItem || !task) return;

  curTplItem.value = tplItem;
  curTask.value = task;

  try {
    // 获取历史记录
    historyDataList.value = await defHttp.get({ url: histroyUrl, params: { itemid: tplItem.id } });
    existHistory.value = historyDataList.value.length>0?true:false;
    // 获取模板项详情
    curTplItem.value = await defHttp.get({ url: tplItemUrl, params: { id: tplItem.id } });
    existFillDes.value = !!curTplItem.value?.des;

    // 获取验证公式
    validFormula.value = await defHttp.get({
      url: validDataUrl,
      params: {
        taskId: task.id,
        tplItemId: tplItem.id,
        fillContent: ""
      }
    });

    if(validFormula.value?.formula?.length > 0) {
      existDataValid.value = true;
      await iniValidata();
    }
  } catch (error) {
    console.error("初始化数据失败:", error);
  }
};

// 初始化验证数据
const iniValidata = async () => {
  formulaDataList.value = [];
  const { formula, codeVal,noFillCnt} = validFormula.value;

  formula.forEach((element: any) => {
    formulaDataList.value.push(
      { name: "验证公式", content: element.formula },
      { name: "验证规则", content: element.des }
    );
  });

  //formulaDataList.value.push({ name: "参数值", content: formatCodeVal(codeVal)})
  if(noFillCnt==0){
    await validata(codeVal[curTplItem.value.code]);
    //formulaDataList.value.push({ name: "参数值", content:resultStatus.value ? "正确" : "错误"})
  } else {
    //formulaDataList.value.push({ name: "参数值", content:"未验证"})
    resultStatus.value = "warning"
  }
 
};

// 格式化参数值
const formatCodeVal = (codeVal: Record<string, any>) => {
  return Object.entries(codeVal).map(([key, value]) => `${key}:${value}`).join(', ');
};

// 验证数据
const validata = async (val: any) => {
  if (!validFormula.value) return;
  const { codeVal, formula,tplItemList } = validFormula.value;
  codeVal[curTplItem.value.code] = val;
  const valCnt = Object.keys(codeVal).length;
  const paramsCnt =tplItemList.length


  let retVal = false;
  if (formula.length > 0) {
    retVal = await validateRule(formula[0].formula, codeVal);
  }
  await setParamcValue(codeVal, retVal);

  
  if(valCnt < paramsCnt){
    resultStatus.value =  "warning";
  } else {
    resultStatus.value = retVal ? "success" : "error";
  }

 
};

// 设置参数值和验证结果
const setParamcValue = async (codeVal: Record<string, any>, result?: boolean) => {
  const newDataList = [...formulaDataList.value];
  
  newDataList[2] = {
    name: "参数值",
    content: formatCodeVal(codeVal)
  };

  if (result !== undefined) {
    newDataList[3] = {
      name: "验证结果",
      content: result ? "正确" : "错误"
    };
  }

  formulaDataList.value = newDataList;
};


const validateRule = async (formula: string, codeVal: Record<string, any>) => {
  try {
   
    let processedFormula = formula;
    for (const [key, value] of Object.entries(codeVal)) {
      const paramRegex = new RegExp(key, 'g');
      processedFormula = processedFormula.replace(paramRegex, value);
    }
    return eval(processedFormula);
  } catch (e) {
    console.error("验证规则执行失败:", e);
    return false;
  }

};

const rowChangeEvent = async ({ row }: { row: any }) => {
  emit('callback', row);
};

const handleShowHistory = () => {
  showHistory.value = true;
  showDataValid.value = false;
  showFillDes.value = false;
};

const handleHideHistory = () => {
  showHistory.value = false;
};

const handleShowFillDes = () => {
  showFillDes.value = true;
  showDataValid.value = false;
  showHistory.value = false;
};

const handleHidenFillDes = () => {
  showFillDes.value = false;
};

const handleShowValidResult = () => {
  showDataValid.value = true;
  showFillDes.value = false;
  showHistory.value = false;
};

const handleHidenValidResult = () => {
  showDataValid.value = false;
};

// 暴露方法
defineExpose({
  iniData,
  validata,
});

// 事件发射
const emit = defineEmits(['callback']);
</script>

<style scope>
  blockquote {
    padding: 0px 5px;
    color: black;
    cursor: pointer;
  }

  .ant-result {
    padding: 0px 32px;
  }
  .ant-result-icon {
    margin-bottom: 10px;
    text-align: center;
  }

  .ant-result-icon>.anticon {
    font-size: 36px;
  }

  .ant-result-content {
    margin-top: 5px;
    padding: 10px 0px;
    background-color: #fafafa;
  }
 
</style>