<template>
  <div class="space-y-4">
    <slot name="title"></slot>
    <p class="text-gray-600 font-bold mb-2">公式设置：</p>
    <div class="space-y-4">
      <div
        v-for="(item, index) in conditions"
        :key="index"
        class="flex flex-wrap space-x-2"
      >
        <el-select-v2
          v-model="item.nodeId"
          placeholder="请选择项目"
          filterable
          :options="nodes"
          @change="val => projectChange(item, val)"
        ></el-select-v2>

        <el-select v-model="item.operator" placeholder="运算符" class="w-24">
          <el-option
            v-for="(operator, operatorIndex) in operators"
            :key="operatorIndex"
            :label="operator.value"
            :value="operator.value"
          ></el-option>
        </el-select>

        <el-input
          v-model="item.value"
          placeholder="请输入达标值"
          class="w-40"
          clearable
        ></el-input>

        <el-select v-model="item.unit" placeholder="单位" class="w-24">
          <el-option
            v-for="(unit, unitIndex) in item.units"
            :key="unitIndex"
            :label="unit"
            :value="unit"
          ></el-option>
        </el-select>

        <el-select
          v-if="!index"
          v-model="item.condition"
          class="w-40"
          placeholder="(选填)附加条件"
          clearable
          @change="v => v && conditions.length === 1 && addCondition(0)"
          @clear="conditions.splice(1, 1)"
        >
          <el-option
            v-for="(condition, conditionIdx) in addConditions"
            :key="conditionIdx"
            :label="condition.label"
            :value="condition.value"
          ></el-option>
        </el-select>
        <!-- <el-button type="primary" link @click="addCondition(index)">
          <Plus class="w-4" />
          <span>添加条件</span>
        </el-button>
        <el-button
          v-if="conditions.length > 1"
          type="danger"
          link
          @click="removeCondition(index)"
        >
          <Delete class="w-4" />
          <span>删除</span>
        </el-button> -->
      </div>
    </div>
    <p class="text-gray-600 font-bold mb-2">设置数据时间范围：</p>
    <el-date-picker
      v-model="date"
      type="daterange"
      start-placeholder="请选择日期"
      end-placeholder="请选择日期"
      format="YYYY-MM-DD"
      value-format="YYYY-MM-DD"
      clearable
    />
    <div class="flex items-center justify-center">
      <el-button class="w-full" type="primary" size="large" @click="startCalc"
        >开始计算</el-button
      >
    </div>
    <template v-if="calcResult.visible">
      <p class="text-gray-600 font-bold mb-2">计算结果：</p>
      <div class="text-sm text-gray-800 space-y-2">
        <div>
          <span>时间范围：</span>
          <span>{{ calcResult.date.join("至") }}</span>
        </div>
        <div>
          <span>达标条件：</span>
          <span>{{ calcResult.condition }}</span>
        </div>
        <div>
          <span>找到数据：</span>
          <span>{{ calcResult.total }}条</span>
        </div>
        <div>
          <span>达标率为：</span>
          <span class="text-blue-600">{{ calcResult.rate }}%</span>
        </div>
      </div>
      <div class="overflow-x-auto w-full">
        <div v-for="(item, index) in list" :key="index">
          <table class="bg-white text-gray-700 table-fixed">
            <tr class="font-bold">
              <td class="border border-solid border-gray-100 p-2">项目</td>
              <td
                class="border border-solid border-gray-100 p-2 whitespace-nowrap"
                v-for="(col, index) in item.list[0].list"
                :key="index"
              >
                {{ dayjs(col.date * 1000).format("YYYY-MM-DD HH:mm:ss") }}
              </td>
            </tr>
            <tr v-for="(child, childIdx) in item.list" :key="childIdx">
              <td
                class="border border-solid border-gray-100 p-2 whitespace-nowrap"
              >
                {{ child.name }}
              </td>
              <td
                v-for="(col, colIdx) in child.list"
                :key="colIdx"
                class="border border-solid border-gray-100"
              >
                <div class="p-2 text-sm">
                  <span class="align-middle"
                    >{{ col.value
                    }}{{ col.unit && col.unit != "-" ? col.unit : "" }}
                  </span>
                  <template v-if="col.reference">
                    <el-tooltip>
                      <QuestionFilled
                        class="w-4 h-4 inline align-middle ml-1 cursor-pointer opacity-50"
                      />
                      <template #content>
                        <div class="text-sm">参考范围：{{ col.reference }}</div>
                      </template>
                    </el-tooltip>
                  </template>
                </div>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, shallowRef } from "vue";
import { ElMessage } from "element-plus";
import {
  Plus,
  ArrowUp,
  ArrowDown,
  Delete,
  QuestionFilled
} from "@element-plus/icons-vue";
import { request } from "@/utils";
import { useRoute, useRouter } from "vue-router";
import dayjs from "dayjs";
const [route, router] = [useRoute(), useRouter()];

const conditions = ref([
  {
    operator: "",
    condition: "",
    value: "",
    unit: "",
    nodeId: "",
    units: []
  }
]);
const date = ref([
  dayjs(Date.now()).subtract(365, "day").format("YYYY-MM-DD"),
  dayjs(Date.now()).add(1, "day").format("YYYY-MM-DD")
]);
const operators = [
  { label: "大于", value: ">" },
  { label: "大于等于", value: "≥" },
  { label: "小于", value: "<" },
  { label: "小于等于", value: "≤" },
  { label: "等于", value: "=" }
];
const addConditions = [
  {
    label: "并且",
    value: "and"
  }
];

const addCondition = index => {
  conditions.value.splice(index + 1, 0, {
    operator: "",
    condition: "",
    value: "",
    unit: "",
    nodeId: "",
    units: []
  });
};
const removeCondition = index => {
  conditions.value.splice(index, 1);
};

const nodes = shallowRef([]);
const searchNodes = async () => {
  const { data } = await request.get(`/graphService/open/node/paginate`, {
    params: {
      page: 1,
      pageSize: 9999,
      tag: "身体物质"
    }
  });
  nodes.value = (data.list || []).map(v => ({
    value: v.id,
    label: v.properties?.name
  }));
};
searchNodes();

const searchRelateNodes = async (id, relationship) => {
  if (!id) return;
  const { data } = await request.get(`/graphService/open/node/related`, {
    params: {
      id,
      relationship
    }
  });
  return data;
};
const projectChange = async (item, id) => {
  const scope = await searchRelateNodes(id, "默认单位与范围");
  if (scope?.length) {
    item.units = scope.map(v => v.properties?.name).filter(v => v);
    item.unit = item.units[0] || "";
  } else {
    item.units = [];
    item.unit = "";
  }
};

const list = ref([]);
const calcResult = ref({
  date: [],
  condition: "",
  total: 0,
  rate: 0,
  visible: false
});
const countSatisfyingData = (data, conditions) => {
  let count = 0;
  console.log("数据", data);
  console.log("条件", conditions);
  // 遍历数据
  data.forEach(item => {
    let satisfyGroupConditions = {}; // 记录每个组内的条件是否满足

    // 遍历条件
    let satisfyAllConditions = true; // 标记是否满足所有条件
    conditions.forEach((condition, conditionIdx) => {
      // 获取条件的操作符
      const operator = operators.find(
        op => op.value === condition.operator
      ).value;

      // 获取当前项目的值
      const subItem = item.find(subItem => subItem.id === condition.nodeId);
      console.log(`操作符:${operator};当前值`, subItem?.value, condition);
      if (subItem && subItem.value !== undefined) {
        // 检查条件
        switch (operator) {
          case ">":
            if (!(parseFloat(subItem.value) > parseFloat(condition.value))) {
              satisfyAllConditions = false;
            }
            break;
          case "≥":
            if (!(parseFloat(subItem.value) >= parseFloat(condition.value))) {
              satisfyAllConditions = false;
            }
            break;
          case "<":
            if (!(parseFloat(subItem.value) < parseFloat(condition.value))) {
              satisfyAllConditions = false;
            }
            break;
          case "≤":
            if (!(parseFloat(subItem.value) <= parseFloat(condition.value))) {
              satisfyAllConditions = false;
            }
            break;
          case "=":
            if (!(parseFloat(subItem.value) === parseFloat(condition.value))) {
              satisfyAllConditions = false;
            }
            break;
          default:
            break;
        }
      } else {
        satisfyAllConditions = false; // 如果项目或值不存在，条件不满足
      }
      console.log("本次结果:", satisfyAllConditions);
    });
    // 如果满足所有条件，计数加一
    if (satisfyAllConditions) {
      count++;
    }
  });

  return count;
};
const formatCalcResult = () => {
  try {
    calcResult.value.date = date.value;
    let s = "";
    conditions.value.forEach(v => {
      const node = nodes.value.find(v2 => v.nodeId == v2.value);
      s += `${node.label}${v.operator}${v.value}${v.unit}${
        v.condition ? "并且" : ";"
      }`;
    });
    calcResult.value.condition = s;
    let count = 0;
    const tmpList = [];
    list.value.forEach(v1 => {
      v1.list.forEach(v2 => {
        count = v2.list.length;
        v2.list.forEach((v3, k3) => {
          if (!tmpList[k3]) {
            tmpList[k3] = [v3];
          } else {
            tmpList[k3].push(v3);
          }
        });
      });
    });
    calcResult.value.total = count;
    console.log(calcResult.value);
    const c = countSatisfyingData(tmpList, conditions.value);
    calcResult.value.rate = count ? (c / count).toFixed(2) * 100 : 0;
    calcResult.value.visible = true;
  } catch (error) {
    ElMessage.error("计算结果异常：" + error.message);
  }
};
const startCalc = async () => {
  const req = {
    archivesId: route.query.archivesId,
    nodeIds: conditions.value.map(v => v.nodeId),
    dates: date.value,
    querys: conditions.value.map(v => ({
      nodeId: v.nodeId,
      unit: v.unit
    }))
  };
  console.log(req);
  const { data } = await request.post(
    "/idcService/mechanism/medicalData/transferItem/query",
    req
  );
  const temp = [];
  data.list.forEach(v => {
    if (v.list.length > 1) {
      v.list.forEach((v2, k2) => {
        v2.list = v2.list.filter(v3 => v3.value || v3.value === 0);
      });
      // v.list.sort((a, b) => b.list.length - a.list.length);
      v.list.forEach((v2, k2) => {
        // 过滤重复 取最大值
        const dateVal = {};
        v2.list = v2.list
          .filter(v3 => {
            if (!dateVal[v3.date]) {
              dateVal[v3.date] = v3.value;
              return true;
            } else {
              dateVal[v3.date] = Math.max(dateVal[v3.date], v3.value);
              return false;
            }
          })
          .map(v3 => {
            v3.value = dateVal[v3.date] || v3.value;
            return v3;
          });
      });
      v.list.forEach((v2, k2) => {
        const dates = {};
        const filterDates = v.list
          .map(v2 => v2.list.map(v3 => v3.date))
          .flat()
          .map(v2 => {
            if (!dates[v2]) {
              dates[v2] = 1;
            } else {
              dates[v2]++;
            }
            return v2;
          })
          .filter(v2 => dates[v2] > 1);

        v2.list = v2.list.filter(v3 => filterDates.includes(v3.date));
      });
    }
  });
  console.log(data.list);
  list.value = data.list;
  formatCalcResult();
};
</script>

<style lang="scss" scoped></style>
