<template>
  <div>
    <el-button type="primary" @click="handleAddPlan">添加管理计划</el-button>
    <!-- <el-button type="primary" @click="handleBacklog">待办事件管理</el-button> -->
    <div class="mt-4">
      <div v-for="(item, index) in props.list" :key="index" class="mb-2">
        <el-card>
          <template #header>
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <el-tag class="mr-2" v-if="item.levelName">{{
                  formatLevel(item.levelName)
                }}</el-tag>
                <!-- <h3>管理疾病名称: {{ item.disease }}</h3> -->
                <h3>{{ item.groupName }}</h3>
              </div>
              <div class="flex items-center">
                <div v-if="!item.status">
                  <h4
                    v-if="
                      moment().format('YYYY-MM-DD') ==
                      item?.nextTime?.split(' ')[0]
                    "
                    style="color: #67c23a"
                  >
                    今天（{{ item.nextTime?.split(" ")[0] }}）需要进行评估
                  </h4>
                  <h4
                    v-else-if="
                      moment().valueOf() >
                      moment(item?.nextTime?.split(' ')[0].valueOf())
                    "
                    style="color: #f56c6c"
                  >
                    已超时{{
                      Number(0 - timeDiffer(item?.nextTime?.split(" ")[0]))
                    }}天（{{ item.nextTime?.split(" ")[0] }} ）请尽快评估
                  </h4>
                  <h4 v-else>
                    {{ timeDiffer(item?.nextTime?.split(" ")[0]) }}天后（{{
                      item?.nextTime?.split(" ")[0]
                    }}）将进行下一次评估
                  </h4>
                </div>
                <div v-else>
                  <h3>管理已暂停</h3>
                </div>

                <Auth value="healthManage">
                  <el-button
                    class="ml-3"
                    type="primary"
                    @click="emits('onEvaluate', index)"
                    >评估</el-button
                  >
                </Auth>
              </div>
            </div>
          </template>
          <div>
            <el-row :gutter="10">
              <el-col :span="12">
                <h4>健康状况趋势</h4>
                <!-- <div class="left-chart" :id="`chart-${index}`"></div> -->
                <div class="bg-white h-64 rounded shadow">
                  <Chart ref="chartRef" />
                </div>
              </el-col>
              <el-col :span="12">
                <h4>
                  {{ item.createdAt.split(" ")[0] }}
                  至
                  {{ item.nextTime?.split(" ")[0] }} 期间（共{{
                    diffTime(
                      item.nextTime?.split(" ")[0],
                      item.createdAt.split(" ")[0]
                    ) || 1
                  }}天）管理目标
                </h4>
                <div>
                  <el-text v-if="!item.status">{{ item.target }}</el-text>
                  <el-empty v-else description="该管理已暂停" />
                </div>
              </el-col>
            </el-row>
            <el-row class="mt-4" v-if="item.indicator?.length">
              <el-col :span="24">
                <h4>关键指标追踪</h4>

                <div class="py-4 space-y-4 pr-4">
                  <div
                    v-for="(item, index) in item.indicator"
                    :key="index"
                    class="shadow"
                  >
                    <div
                      class="cursor-pointer py-2 px-4 flex items-center justify-between"
                      :class="{
                        'bg-gray-50': !item.expand,
                        'bg-blue-50 text-blue-700': item.expand
                      }"
                      @click="item.expand = !item.expand"
                    >
                      <span>{{ item.name }}</span>
                      <ArrowUp class="w-4 text-gray-500" v-if="!item.expand" />
                      <ArrowDown class="w-4 text-gray-500" v-else />
                    </div>
                    <div class="w-full overflow-x-auto">
                      <table
                        v-if="item.expand"
                        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 whitespace-nowrap"
                          >
                            项目
                          </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[0].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">
                              <div
                                v-for="(subCol, subColIdx) in col"
                                :key="subColIdx"
                                class="inline-flex items-center"
                              >
                                <span class="align-middle"
                                  >{{ subCol.value
                                  }}{{
                                    subCol.unit && subCol.unit != "-"
                                      ? subCol.unit
                                      : ""
                                  }}
                                </span>
                                <!-- {{  subCol }} -->
                                <el-icon
                                  v-if="subCol.mark > 0"
                                  class="inline-block align-middle w-4 text-red-600"
                                  ><Top />
                                </el-icon>
                                <el-icon
                                  v-if="subCol.mark < 0"
                                  class="inline-block align-middle w-4 text-green-600"
                                  ><Bottom />
                                </el-icon>
                                <template v-if="subCol.reference">
                                  <el-tooltip>
                                    <QuestionFilled
                                      class="w-4 h-4 inline align-middle ml-1 cursor-pointer opacity-50"
                                    />
                                    <template #content>
                                      <div class="text-sm">
                                        参考范围：{{ subCol.reference }}
                                      </div>
                                    </template>
                                  </el-tooltip>
                                </template>
                              </div>
                            </div>
                          </td>
                        </tr>
                      </table>
                    </div>
                  </div>
                  <el-empty v-if="!list.length" />
                </div>
              </el-col>
            </el-row>
          </div>
          <template #footer>
            <div class="flex justify-between">
              <div>
                <el-button
                  type="primary"
                  link
                  :icon="Setting"
                  @click="handleEditItem(index)"
                  >阶段管理设置</el-button
                >
                <el-button
                  type="primary"
                  link
                  :icon="Clock"
                  @click="handleHistory(index)"
                  >评估历史详情</el-button
                >
              </div>
              <div class="flex-right">
                <el-button
                  v-if="item.status"
                  type="primary"
                  link
                  :icon="VideoPlay"
                  style="color: green"
                  @click="handleChangeStatus(item)"
                  >恢复管理</el-button
                >
                <el-button
                  v-else
                  type="primary"
                  link
                  :icon="VideoPause"
                  style="color: red"
                  @click="handleChangeStatus(item)"
                  >暂停管理</el-button
                >

                <el-popconfirm
                  title="确定要删除此管理计划吗"
                  @confirm="emits('onDelete', index)"
                >
                  <template #reference>
                    <el-button
                      type="primary"
                      link
                      :icon="Delete"
                      style="color: red"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </template>
        </el-card>
      </div>
    </div>
    <ComponentDialogSelectIllness v-model:show="state.visibleAdd" />
    <ComponentDialogBacklog v-model:show="state.visibleBacklog" />
    <el-dialog title="评估历史详情" v-model="state.visibleHistory">
      <div>
        <ComponentAssessmentHistory
          :list="transformDataExpand([state.currentItem], 'histories')"
          ref="historyRef"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits } from "vue";
import * as echarts from "echarts";
import { nextTick } from "process";
import moment from "moment";
import dayjs from "dayjs";
import {
  QuestionFilled,
  ArrowUp,
  ArrowDown,
  Top,
  Bottom
} from "@element-plus/icons-vue";

import ComponentDialogSelectIllness from "./DialogSelectIllness.vue";
// import ComponentDialogBacklog from "./DialogBacklog.vue";
import ComponentAssessmentHistory from "./AssessmentHistory.vue";
import Chart from "@/components/Chart.vue";

import { ElMessage, ElMessageBox } from "element-plus";

import {
  Setting,
  Clock,
  VideoPause,
  VideoPlay,
  Delete
} from "@element-plus/icons-vue";
import { request, transformDataExpand, timeDiffer } from "@/utils";

const props = defineProps({
  list: Array,
  default: () => []
});
const emits = defineEmits("onChangeStatus", "onEdit", "onEvaluate", "onDelete");
const state = reactive({
  visibleAdd: false,
  visibleBacklog: false,
  visibleHistory: false,
  currentItem: {}
});
const chartRef = ref();
const historyRef = ref();
const formatLevel = level => {
  const map = new Map([
    ["一级预防", "1级预防"],
    ["二级预防", "2级预防"],
    ["三级预防", "3级预防"],
    ["四级预防", "4级预防"]
  ]);
  return map.get(level);
};
const initChart = index => {
  props.list.map((item, i) => {
    const list = transformDataExpand([item], "histories");
    // list.forEach(v => {
    //   if (v.effect?.name == "缺乏评估数据") {
    //     v.effect["程度"] = 5;
    //   }
    // });
    chartRef.value[i]?.setOption({
      title: {
        text: "",
        top: "10",
        left: "10"
      },
      grid: {
        left: "5%",
        right: "5%",
        bottom: "15%"
      },
      // dataZoom: [
      //   {
      //     type: "slider", //slider表示有滑动块的，
      //     show: true,
      //     xAxisIndex: [0], //表示x轴折叠
      //     start: 1, //数据窗口范围的起始百分比,表示1%
      //     end: 35, //数据窗口范围的结束百分比,表示35%坐标
      //     bottom: "20"
      //   }
      // ],
      xAxis: {
        type: "category",
        data: list.map(v => v.createdAt).reverse(),
        axisLabel: {
          formatter: params => {
            return params?.split(" ")[0] + "\n" + params?.split(" ")[1];
          }
        }
      },
      yAxis: {
        type: "value",
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false }
      },
      series: [
        {
          data: list.map(v => Number(v.effect["程度"])).reverse(),
          type: "line",
          itemStyle: {
            normal: {
              // 这里就可以实现，配置柱状图的颜色
              color: function (params) {
                const colorList = [
                  "#ccc",
                  "#c101c1",
                  "#FCCE10",
                  "#E87C25",
                  "#27727B",
                  "#D7504B"
                ];
                return colorList[params.value];
              }
            }
          },
          label: {
            show: true,
            position: "top",
            formatter: params => {
              return list.find(v => v.effect["程度"] == params.value)?.effect
                ?.name;
            }
          },
          smooth: true
        }
      ]
    });
  });
};
const diffTime = (end, start) => {
  return moment(end).diff(moment(start), "day");
};
const handleAddPlan = () => {
  state.visibleAdd = true;
};
const handleBacklog = () => {
  state.visibleBacklog = true;
};
const handleHistory = index => {
  state.currentItem = props.list[index];
  state.visibleHistory = true;
  console.log(historyRef.value);

  historyRef.value?.initChart();
};
const handleChangeStatus = row => {
  ElMessageBox.confirm(
    row.status
      ? "确定继续次疾病的管理？"
      : "确定要暂停这个管理吗？暂停后不可再进行评估",
    "",
    {
      distinguishCancelAndClose: true,
      confirmButtonText: "确定",
      cancelButtonText: "取消"
    }
  )
    .then(async () => {
      emits("onChangeStatus", row);
    })
    .catch(err => {});
};
const handleEditItem = index => {
  emits("onEdit", index);
};
nextTick(initChart);
</script>
<style scoped lang="scss">
.left-chart {
  width: 500px;
  height: 400px;
}
</style>
