<template>
  <div>
    <Auth value="healthManage">
      <el-button type="primary" @click="handleAddPlan">添加管理计划</el-button>
    </Auth>
    <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">
                <h3>管理疾病名称: {{ item.disease }}</h3>
              </div>
              <div class="flex items-center">
                <div v-if="!item.status">
                  <h4
                    v-if="
                      moment().format('YYYY-MM-DD') ==
                      item?.nextTime?.split(' ')[0]
                    "
                    class="text-green-500"
                  >
                    今天（{{ item.nextTime?.split(" ")[0] }}）需要进行评估
                  </h4>
                  <h4
                    v-else-if="
                      moment().valueOf() >
                      moment(item?.nextTime?.split(' ')[0].valueOf())
                    "
                    class="text-red-500"
                  >
                    已超时{{
                      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>
                <el-button
                  class="ml-3"
                  type="primary"
                  @click="emits('onEvaluate', index)"
                  >评估</el-button
                >
              </div>
            </div>
          </template>
          <div>
            <el-row :gutter="10">
              <el-col :span="12">
                <template v-if="item.etiologies.length">
                  <h4>目前主要病因</h4>
                  <div>
                    <el-tag
                      v-for="(tag, tagIdx) in item.etiologies"
                      :key="tagIdx"
                      class="m-1"
                      type="danger"
                      size="large"
                      >{{ tag.label }}</el-tag
                    >
                  </div>
                </template>
                <h4>健康综合评分趋势</h4>
                <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>
                  <div v-if="!item.status" v-html="item.target" />
                  <el-empty v-else description="该管理已暂停" />
                </div>
              </el-col>
            </el-row>
          </div>
          <template #footer>
            <div class="flex justify-between">
              <div>
                <Auth value="healthManage">
                  <el-button
                    type="primary"
                    link
                    :icon="Setting"
                    @click="handleEditItem(index)"
                    >修改下次评估日期</el-button
                  >
                </Auth>
                <el-button
                  type="primary"
                  link
                  :icon="User"
                  @click="handleUserPortrait(index)"
                  >健康画像</el-button
                >
                <el-button
                  type="primary"
                  link
                  :icon="Clock"
                  @click="handleHistory(index)"
                  >评估历史详情</el-button
                >
                <el-button
                  v-if="pptNode"
                  type="primary"
                  link
                  :icon="VideoPlay"
                  @click="toPPT"
                  >讲解</el-button
                >
              </div>
              <div class="flex-right">
                <Auth value="healthManage">
                  <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>
                </Auth>
              </div>
            </div>
          </template>
        </el-card>
      </div>
    </div>
    <ComponentDialogSelectIllness
      v-model:show="state.visibleAdd"
      nodeTag="功能医学管理"
      :confirmFn="
        (diseaseId, name) =>
          router.push({
            name: 'healthPlanDetail',
            query: {
              archivesId: route.query.archivesId,
              name,
              diseaseId
            }
          })
      "
    />
    <el-dialog title="健康画像" v-model="userPortraitVisible" width="85%">
      <div v-if="userPortraitVisible">
        <component :is="HealthPortrait" />
      </div>
    </el-dialog>
    <el-dialog title="评估历史详情" v-model="state.visibleHistory" width="85%">
      <div>
        <DialogHealthManageEvaluationHistory
          :list="transformDataExpand([state.currentItem], 'histories')"
          ref="historyRef"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  ref,
  reactive,
  defineProps,
  defineEmits,
  defineAsyncComponent,
  provide,
  inject
} from "vue";
import * as echarts from "echarts";
import { nextTick } from "process";
import moment from "moment";
// import dayjs from "dayjs";
import { useRoute, useRouter } from "vue-router";
import ComponentDialogSelectIllness from "./DialogSelectIllness.vue";
import DialogHealthManageEvaluationHistory from "./DialogHealthManageEvaluationHistory.vue";
import Chart from "@/components/Chart.vue";

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

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

const pptNode = inject("pptNode");
const [route, router] = [useRoute(), useRouter()];
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 initChart = index => {
  props.list.map((item, i) => {
    const list = transformDataExpand([item], "histories");
    chartRef.value[i].setOption({
      title: {
        text: "",
        top: "10",
        left: "10"
      },
      grid: {
        left: "5%",
        right: "5%",
        bottom: "15%"
      },
      xAxis: {
        type: "category",
        data: list.map(v => v.createdAt).reverse(),
        axisTick: { show: false },
        axisLabel: {
          formatter: params => {
            return params?.split(" ")[0];
          }
        }
      },
      yAxis: {
        type: "value",
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false }
      },
      series: [
        {
          data: list.map(v => Number(v.score)).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 `${params.value}分`;
            }
          },
          smooth: true
        }
      ]
    });
  });
};
const diffTime = (end, start) => {
  return moment(end).diff(moment(start), "day");
};
const handleAddPlan = () => {
  state.visibleAdd = true;
};
const handleBacklog = () => {
  state.visibleBacklog = true;
};

const HealthPortrait = defineAsyncComponent(() =>
  import("../healthPlan/HealthPortrait.vue")
);
const userHealthPortraitState = ref();
const userPortraitVisible = ref(false);
const handleUserPortrait = index => {
  const current = props.list[index];
  console.log(current);
  userHealthPortraitState.value = { ...current };
  userHealthPortraitState.value.etiologies =
    userHealthPortraitState.value.etiologies.map(v => {
      return typeof v == "string" ? { label: v } : v;
    });
  initDisease(current.diseaseId);
  userPortraitVisible.value = true;
};
provide("parentState", userHealthPortraitState);
const diseaseMangeNode = ref();
const initDisease = async diseaseId => {
  const nodes = await getNodeRelationship(diseaseId, "功能医学管理");
  diseaseMangeNode.value = nodes[0].mId;
};
provide("diseaseMangeNode", diseaseMangeNode);
const getNodes = async query => {
  const { data } = await request.get(`/graphService/open/node/paginate`, {
    params: {
      page: 1,
      pageSize: 9999,
      pagesize: 9999,
      ...query
    }
  });
  return data;
};
provide("getNodes", getNodes);
const getNodeRelationship = async (id, tag, reverse = undefined) => {
  const { data } = await request.get(`/graphService/open/node/relationship`, {
    params: {
      id,
      rName: tag,
      reverse
    }
  });
  return data;
};
provide("getNodeRelationship", getNodeRelationship);
const getBatchNodeRelationships = async (ids, tag, reverse = undefined) => {
  const { data } = await request.get(`/graphService/open/node/relationships`, {
    params: {
      ids,
      rName: tag,
      reverse
    }
  });
  return data;
};
provide("getBatchNodeRelationships", getBatchNodeRelationships);
const handleHistory = index => {
  state.currentItem = props.list[index];
  state.visibleHistory = true;
  console.log(historyRef.value, state.currentItem);

  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);

const toPPT = () => {
  const url = `${location.origin}${location.pathname}#/healthManagement/ppt?archivesId=${route.query.archivesId}`;
  console.log(url);
  const newWindow = window.open(url);
  if (newWindow) {
    newWindow.addEventListener("load", () => {
      newWindow.postMessage("goFullscreen", "*");
    });
  }
};
</script>
<style scoped lang="scss">
.left-chart {
  width: 500px;
  height: 400px;
}
</style>
