<template>
  <!-- <div class="bg-[#f0f2f5] sticky z-10 top-0 h-4"></div> -->
  <div
    class="bg-white p-4 sticky z-10 top-4 flex items-center flex-wrap space-x-2 mr-4 border border-gray-100 rounded"
  >
    <span class="text-sm text-gray-600">关键检查查询:</span>
    <el-select
      v-model="filter.nodes"
      class="mb-2"
      multiple
      filterable
      clearable
      collapse-tags
    >
      <el-option
        v-for="(item, index) in nodes"
        :key="index"
        :label="item.name"
        :value="item.id"
      ></el-option>
    </el-select>
    <div class="mb-2">
      <el-date-picker
        v-model="filterDate"
        type="daterange"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
        start-placeholder="请选择"
        end-placeholder="请选择"
      />
    </div>

    <el-button type="primary" class="mb-2" @click="search">搜索</el-button>
    <el-button type="warning" class="mb-2" plain @click="reset">重置</el-button>
  </div>
  <div class="mt-6 mr-4">
    <div
      v-for="(item, index) in list"
      :key="index"
      class="bg-white p-4 mb-4 border shadow-sm border-gray-100 rounded"
    >
      <!-- <div>
        <span>{{ item.name }}</span>
      </div> -->
      <div v-if="item.isBodyMatter" class="h-64">
        <Chart
          :ref="
            r => {
              chartRefs[index] = r;
            }
          "
        />
      </div>
      <div v-else class="w-full overflow-x-auto">
        <table class="min-w-full 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"
              :key="index"
            >
              {{ dayjs(col.date * 1000).format("YYYY-MM-DD") }}
            </td>
          </tr>
          <tr>
            <td
              class="border border-solid border-gray-100 p-2 whitespace-nowrap"
            >
              {{ item.name }}
            </td>
            <td
              v-for="(col, colIdx) in item.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>
    <el-empty v-if="!list.length"></el-empty>
  </div>
</template>

<script setup>
import {
  computed,
  watch,
  ref,
  reactive,
  inject,
  nextTick,
  onMounted,
  defineAsyncComponent
} from "vue";
import dayjs from "dayjs";
import { useRoute, useRouter } from "vue-router";
import { QuestionFilled, ArrowUp, ArrowDown } from "@element-plus/icons-vue";

import { request, formateArchivesModuleValue, deepClone } from "@/utils";
import Chart from "@/components/Chart.vue";

const route = useRoute();
const router = useRouter();

const props = defineProps({
  nodeId: {
    type: String,
    default: ""
  }
});

const filter = ref({
  nodes: []
});
const defaultNodes = ref([]);
const filterDate = ref([]);

const nodes = ref([]);
const searchNodes = async () => {
  const { data } = await request.post(
    "/idcService/mechanism/medicalData/transferItem/primaryIndicatorCharts/query",
    {
      archivesId: route.query.archivesId,
      nodeIds: [],
      dates: [],
      needCharts: false
    }
  );
  nodes.value = data.list;
  // filter.value.nodes = data.list.map(v => v.id);
  // filter.value.nodes = [
  //   "4:aad18a76-6ee3-48a0-bec9-4f7e0bb822dc:357",
  //   ...data.list.map(v => v.id)
  // ];
};
const list = ref([]);
const search = async () => {
  const { data } = await request.post(
    "/idcService/mechanism/medicalData/transferItem/primaryIndicatorCharts/query",
    {
      archivesId: route.query.archivesId,
      nodeIds: filter.value.nodes,
      dates: filterDate.value || [],
      needCharts: true
    }
  );
  list.value = data.list;
  chartRefs.value = Array(data.list.length).fill(null);
  nextTick(() => {
    list.value.forEach((v, i) => {
      v.isBodyMatter && setOption(chartRefs.value[i], v);
    });
  });
};

const init = async () => {
  await searchNodes()
  await searchRelateNodes(props.nodeId);
  search();
};
const chartRefs = ref([]);
const setOption = (cRef, item) => {
  console.log(cRef, item);
  const opt = {
    title: {
      text: item.name,
      top: "10",
      left: "10"
    },
    grid: {
      left: "5%",
      right: "5%",
      bottom: "20%"
    },
    legend: {
      top: "bottom"
    },
    xAxis: {
      type: "category",
      data: []
    },
    tooltip: {
      formatter(param) {
        return `${param.seriesName}: ${param.value}${param.data?.unit}`;
      }
    },
    yAxis: {
      type: "value",
      axisLine: { show: false },
      axisTick: { show: false }
      // axisLabel: { show: false }
    },
    series: []
  };
  if (item.name == "血压") {
    const arr1 = [];
    const arr2 = [];
    item.list.forEach(v => {
      const val = v.value.split("/");
      arr1.push({
        ...v,
        value: val[0]
      });
      arr2.push({
        ...v,
        value: val[1]
      });
    });

    opt.series = [
      {
        name: "收缩压",
        data: arr1,
        type: "line",
        label: {
          show: true
        },
        smooth: true
      },
      {
        name: "舒张压",
        data: arr2,
        type: "line",
        label: {
          show: true
        },
        smooth: true
      }
    ];
  } else {
    opt.series = [
      {
        name: item.name,
        data: item.list,
        type: "line",
        label: {
          show: true
        },
        smooth: true
      }
    ];
  }
  opt.series.forEach(v => {
    v.data = v.data.map(d => {
      const val = /(\d+(\.\d+)?)/.exec(String(d.value));
      if (val) {
        d.value = val[0] || d.value;
      }
      if (isNaN(Number(d.value))) {
        d.value = null
      }
      return d
    }).filter(d => d.value != null);
  });
  opt.xAxis.data = opt.series[0].data.map(d => dayjs(d.date * 1000).format("YYYY-MM-DD"))
  console.log(opt);

  cRef && cRef.setOption(opt);
};
onMounted(() => {
  init();
});

const searchRelateNodes = async id => {
  console.log(id);
  if (!id) return;
  const { data } = await request.get(`/graphService/open/node/related`, {
    params: {
      id,
      relationship: "关键指标"
    }
  });
  defaultNodes.value = (data || []).map(v => v.id).filter(v => nodes.value.find(v2 => v2.id == v));
  filter.value.nodes = defaultNodes.value;
};
const reset = () => {
  filter.value.nodes = defaultNodes.value;
  search();
};
</script>

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