<template>
  <div class="psychological-container">
    <van-nav-bar :title="emoName + '监测'" :border="true" :left-arrow="true" @click-left="onNavBack" v-if="isShowLeft">
      <template #left>
        <van-icon name="arrow-left" size="24" style="padding: 0" />
        <span>返回</span>
      </template>
    </van-nav-bar>
    <div class="tab-bar" v-if="isshowTab">
      <div class="date-tab-con">
        <div class="date-tab-list">
          <div :class="[
            'date-tab-item',
            { active: current === index, notClick: false },
          ]" @click="onTabClick(item.value, index)" v-for="(item, index) in dateList" :key="index">
            <img :src="tabImgUrl" alt v-if="index == 3" />
            <span>{{ item.text }}</span>
            <img class="more" :src="selectDownImg" alt v-if="index == 3" />
          </div>
        </div>
      </div>
    </div>
    <div class="main" v-show="current !== 3">
      <div class="top">
        <!-- 日期选择 -->
        <!-- 标题 -->
        <div class="title">
          <div class="title-left">
            {{ titleLeft }}<van-icon name="question-o" @click="onHelp" />
          </div>
          <div class="title-right" v-show="currentDays === 0">
            <p @click="onHistory">历史监测</p>
          </div>
        </div>
        <!-- 日历 -->

        <van-dialog class="calenddar-dialog" v-model="calendarDialogShow" :show-confirm-button="false"
          :show-cancle-button="false" :close-on-click-overlay="true" ref="calenddarDialog">
          <template #default>
            <div class="calendar" ref="calendarCon">
              <van-calendar v-model="calendarShow" :min-date="minDate" :max-date="maxDate" :default-date="defaultDate"
                :round="false" :poppable="false" color="#62BD48" :show-confirm="false" :show-title="false"
                :show-subtitle="false" :formatter="formatter" @select="onSelect" />
            </div>
          </template>
        </van-dialog>

        <!-- 监测次数 -->
        <div class="monitoring-count">
          <p>监测次数：{{ monitoringCount || "0" }}次</p>
        </div>

        <!-- 折线图-非日报 -->

        <div class="pie-chart-con">
          <div class="pie-chart-left">
            <div id="pieChartDay" ref="pieChartDay"></div>
          </div>

          <div class="pie-chart-right">
            <div class="list">
              <div class="item" v-for="(item, index) in pieRightList" :key="index">
                <div class="item-left">
                  <div class="circle" :style="{ backgroundColor: item.color }"></div>

                  <span class="text">{{ item.text || "--" }}</span>
                </div>

                <div class="item-right">
                  <span :style="{ color: item.color }">{{
                    item.count ? item.count + "次" : "0次"
                  }}</span>
                  <label :style="{ color: item.color }">{{
                    item.percentage ? "(" + item.percentage + "%" + ")" : "(0%)"
                  }}</label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 统计 -->

        <div class="statistics">
          <div class="list">
            <div class="item" v-for="(item, index) in statisticsList" :key="index">
              <div class="top">
                <span>{{ item.label || "--" }}</span>
              </div>

              <div class="middle">
                <span :style="{ color: calcResultColor(item.level) }">{{
                  item.value || "--"
                }}</span>
              </div>

              <div class="bottom">
                <span>{{ item.time || "--" }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 分割线 -->
      <div class="line"></div>
      <!-- 底部 -->
      <!-- 情绪切换 -->
      <div class="psy-tab-bar">
        <div class="psy-tab-con">
          <div class="psy-tab-list">
            <div :class="[
              'psy-tab-item',
              { active: psyCurrent === index, notClick: false },
            ]" @click="onPsyTabClick(item.name, index)" v-for="(item, index) in psyList" :key="index">
              <span>{{ item.text }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="bottom">
        <div class="echart-container">
          <div class="echart" ref="dayCharts"></div>
        </div>

        <div class="line-gray"></div>

        <div class="result" v-if="monitoringCount == ''">
          <div class="result-con">
            <div class="title">
              <span class="title-no-data">结果解读</span>
              <div class="no-data">
                <img src="../../../../assets/img/no_data_01.png" alt />
                <p>暂无数据</p>
              </div>
            </div>
          </div>
        </div>

        <div class="result" v-else>
          <div class="result-con reminder" v-show="current === 0">
            <div class="title">
              <span class="title-reminder">结果解读</span>

              <p class="title-emo" :style="{ color: currentColor }">
                {{ this.$replaceAll(result, '抑郁', '忧郁') }}
              </p>

              <span class="font-28"><!-- 继续保持积极乐观，培养健康的生活习惯，预防消极事件对情绪带来的不良影响。 -->{{
                advice
              }}</span>
            </div>

            <div class="friendly-reminder" v-if="emoType === 2">
              <p :style="{ color: currentColor }">友情提示：</p>
              <span>如果您发现{{ anxietyText }}倾向分值升高或处于轻度水平，不需要过度紧张，这可能是由正常的情绪波动或者生活习惯（睡眠时间、运动量等）的改变造成的。如果您发现{{ anxietyText
                }}倾向分值连续7天及以上处于中度或重度水平，建议您寻求家人朋友或心理咨询师的帮助，及早进行干预。</span>
            </div>

            <div class="warm-reminder">
              <p :style="{ color: currentColor }">温馨提示：</p>
              <span>{{ warmTips }}</span>
            </div>
          </div>

          <div class="result-con" v-show="current > 0">
            <div class="title">
              <span class="title-text">{{ surveyTitle }}</span>
              <div class="mood-list" v-if="emotionList.length > 0">
                <div class="item" v-for="(item, index) in emotionList" :key="index">
                  <p>
                    <span :style="{ color: item.color }" class="day">{{
                      item.days
                    }}</span>
                    <span class="day-text">天</span>
                  </p>

                  <p>{{ item.text }}</p>
                </div>
              </div>
              <div class="mood-list-no-data" v-else>
                <div class="no-data">
                  <img src="../../../../assets/img/no_data_01.png" alt />
                  <p>暂无数据</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!--  -->
      </div>
    </div>
    <!-- 周报菜单 -->
    <div class="main-details" :class="{hideNav:!isShowLeft,hideTab:!isshowTab,hideNavTab:!isShowLeft && !isshowTab}" v-show="current == 3">
      <div class="report-details">
        <div class="overall-rating">
          <div class="con">
            <p class="space-between">
              <span class="bold">本周总评</span>
              <span class="time">{{
                resetDate(weekResult.StartDate, weekResult.EndDate) || "--"
              }}</span>
            </p>
            <p class="bold-pro" :style="{ color: calcResultColor(weekResult.SummaryLevel) || '--' }">
              {{ weekResult.Summary }}
            </p>
            <p class="normal">监测次数: {{ weekResult.Total || "--" }}次</p>
            <p class="normal">{{ weekResult.Explain || "--" }}</p>
          </div>

        </div>
        <!-- <div class="line"></div> -->
        <!-- 情绪切换 -->
        <div class="psy-tab-bar">
          <div class="psy-tab-con">
            <div class="psy-tab-list">
              <div :class="[
                'psy-tab-item',
                { active: psyCurrent === index, notClick: false },
              ]" @click="onPsyTabClick(item.name, index)" v-for="(item, index) in psyList" :key="index">
                <span>{{ item.text }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="pie-chart-top">
          <p class="bold">上周趋势对比</p>
          <p>{{ resetDate(weekResult.StartDate, weekResult.EndDate) || "--" }}</p>
        </div>
        <div class="count">
          <p>监测次数：{{ weekResult.LastTotal || "--" }}次</p>
        </div>
        <!-- 趋势对比-饼状图 -->
        <div class="pie-chart-con">
          <div class="pie-chart-left">
            <div id="pieChart" ref="pieChart"></div>
          </div>

          <div class="pie-chart-right">
            <div class="list">
              <div class="item" v-for="(item, index) in pieRightList" :key="index">
                <div class="item-left">
                  <div class="circle" :style="{ backgroundColor: item.color }"></div>
                  <span class="text">{{ item.text || "--" }}</span>
                </div>

                <div class="item-right">
                  <span :style="{ color: item.color }">{{
                    item.count ? item.count + "次" : "0次"
                    }}</span>
                  <label :style="{ color: item.color }">{{
                    item.percentage ? "(" + item.percentage + "%" + ")" : "(0%)"
                    }}</label>
                </div>

                <div class="status" v-if="isShowCompare">
                  <img :src="calcImg(item.percentage, item.lastPercentage)" alt="" />
                  <span :style="{
                    color:
                      calcImg(item.percentage, item.lastPercentage, true) != 0
                        ? item.color
                        : '',
                  }">{{
                  calcImg(item.percentage, item.lastPercentage, true)
                    ? Math.abs(
                      calcImg(item.percentage, item.lastPercentage, true)
                    ) + "%"
                    : "持平"
                }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="statistics">
          <div class="list">
            <div class="item" v-for="(item, index) in statisticsList" :key="index">
              <div class="top">
                <span>{{ item.label || "--" }}</span>
              </div>

              <div class="middle">
                <span :style="{ color: calcResultColor(item.level) }">{{
                  item.value || "--"
                  }}</span>
              </div>

              <div class="bottom">
                <span>{{ item.time || "--" }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="line"></div>
        <!-- 数据图-柱形图 -->
        <div class="bar-chart">
          <div class="echart" ref="charts"></div>
        </div>
        <div class="line"></div>
        <!-- 建议 -->
        <div class="advice">
          <div class="content">
            <p class="title">健康建议</p>
            <p>{{ weekResult.Advice || "--" }}</p>
          </div>
        </div>
        <!-- 概览 -->
        <div class="overview">
          <div class="content">
            <div class="title">
              <span class="title-text">{{ surveyTitle }}</span>
              <div class="mood-list">
                <div class="item" v-for="(item, index) in emotionList" :key="index">
                  <p>
                    <span :style="{ color: item.color }" class="day">{{
                      item.days
                      }}</span>
                    <span class="day-text">天</span>
                    <img :src="calcWeekImg(item.days, item.lastDay)" alt="" v-if="isShowCompare" />
                    <span class="day-text status" v-if="isShowCompare">{{
                      calcWeekImg(item.days, item.lastDay, true)
                      }}</span>
                  </p>
                  <p>{{ item.text }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
    <!-- 弹出层 -->
    <van-popup v-model="isPopup">
      <div class="popup">
        <div class="item science-tips first" v-if="emoType === 2">
          <div class="tips">
            <h5>小科普</h5>
          </div>
          <p>
            {{ anxietyText }}症是一种心理疾病，严重时可发展为精神障碍。然而当我们体会到了痛苦、悲伤、和郁闷等负面情绪，并不意味着我们就是{{ anxietyText
            }}症。日常的短时的喜、怒、哀、乐，都是正常的情绪变化，然而长期的低落情绪、兴趣缺失等可能会让我们有{{ anxietyText }}的风险。
          </p>
        </div>
        <div class="item">
          <h5 v-html="title1"></h5>
          <div v-html="article1"></div>
        </div>
        <div class="item">
          <h5 v-html="title2"></h5>
          <div v-html="article2"></div>
        </div>
        <van-button size="large" @click="onClose">返回</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { EmotionModel, PsyBaseUrl, } from "@/config/models";
import axios from "axios";
import { anxietyText } from "@/config/models";
import { isNotNull } from "@/utils/index";
import APICore from "@/api/core";
export default {
  name: "psychological-monitor",
  data() {
    return {
      isShowLeft:true,
      isshowTab:true,
      // 日期选择标签
      dateList: [
        { name: "today", text: "今天", value: 0 },
        { name: "week", text: "前7天", value: 7 },
        { name: "month", text: "前30天", value: 30 },
        { name: "weekReport", text: "周报", value: 49 },
      ],
      // 情绪tab
      psyList: [
        { name: "tiredness", text: "疲劳", value: 0 },
        { name: "stress", text: "压力", value: 1 },
        { name: "depression", text: this.$replaceAll('抑郁', '抑郁', '忧郁'), value: 2 },
      ],
      // 当前情绪下标
      psyCurrent: 0,
      current: 0, // 日期选择标签-当前选中的标签
      currentDays: 0, //日期选择标签-日期参数
      emotionData: [], //情绪数据，TODO 接口对接
      echarts: null, //折线图
      itemHeight: Number(((document.body.clientWidth / 750) * 95).toFixed()), // 日历组件item高度
      xAxisData: [], //图表x轴展示的数据
      monitoringCount: "", //监测次数
      pieEcharts: null, //饼状图
      pieData: [], //饼状图数据
      //饼状图右边数据,TODO 根据接口数据和 模块 重新封装数组
      pieRightList: [
        /* {
                    text: "无情绪倾向",
                    count: 12,
                    percentage: "80",
                    color: "#62BD48"
                },
                {
                    text: "轻度情绪倾向",
                    count: 2,
                    percentage: "80",
                    color: "#ffde00"
                },
                {
                    text: "中度情绪倾向",
                    count: 1,
                    percentage: "80",
                    color: "#ff8a00"
                },
                {
                    text: "重度情绪倾向",
                    count: 1,
                    percentage: "80",
                    color: "#d70d0d"
                } */
      ],
      // 情绪状态列表
      statisticsList: [
        /*  { label: "最大值", value: "75", time: "08:15" },
                { label: "最小值", value: "40", time: "10:15" },
                { label: "最近值", value: "50", time: "18:15" } */
      ],
      // 周报-情绪计算
      emotionList: [
        /*  { days: "5", text: "无情绪倾向", color: "#62BD48" },
                { days: "4", text: "轻度情绪倾向", color: "#ffde00" },
                { days: "3", text: "中度情绪倾向", color: "#ff8a00" },
                { days: "2", text: "重度情绪倾向", color: "#ACACAC" } */
      ],
      // 弹窗-日历是否显示
      calendarDialogShow: false,
      // 日历是否显示，默认为true
      calendarShow: true,
      // 日历 默认最小可选择日期，默认为最近1个月
      minDate: new Date(
        this.$dayjs()
          .month(this.$dayjs().month() - 1)
          .hour(0)
          .minute(0)
          .second(0)
          .format()
      ),
      // 日历 默认最小可选择日期，默认为当前时间
      maxDate: new Date(this.$dayjs().hour(0).minute(0).second(0).format()),
      // 默认日历日期时间
      defaultDate: new Date(this.$dayjs().hour(0).minute(0).second(0).format()),
      // 路由传过来的情绪参数
      emoName: "",
      // 默认折线图 Series 配置
      defaultSeries: null,
      // 非日报折线图 Series 配置
      weekAndMonthSeries: null,
      // 当前情绪类型
      emoType: "",
      // 结果解读
      result: "",
      // 需要高亮的日期数组
      highlightDates: [],
      // 选中的日历日期
      selectDate: "",
      uid: "",
      // 建议
      advice: "",
      // 底部天数标题
      surveyTitle: "" || "7天概览",
      // 路由中的日期
      routeDate: "",
      // 路由参数
      params: {},
      // 是否显示帮助
      isPopup: false,
      // 结果等级
      resultLevel: "",
      // 轻度级别颜色
      mildColor: "#ffde00",
      // 中度级别颜色
      severeColor: "#ff8a00",
      // 重度级别颜色
      moderateColor: "#d70d0d",
      // 7天和30天最大数据列表
      weekAndMonData: [],
      tabImgUrl: require("@/assets/img/psychological/statistical_form.png"),
      selectDownImg: require("@/assets/img/psychological/select_down.png"),
      weekImg: require("@/assets/img/psychological/week_report.png"),
      moreImg: require("@/assets/img/psychological/more.png"),
      noDataImg: require("@/assets/img/no_data_01.png"),
      weekList: [],
      startDate: "", //接口需要的开始时间
      endDate: "", //接口需要的结束时间
      currentEmoName: "", //当前情绪名称
      weekResultList: [], //周报新详情周报列表
      weekResult: {},
      isShowCompare: null, //是否显示周对比
      pieDayEcharts: null, //非周报饼状图
      pieDayData: [], //非周报饼状图
      dayEcharts: null
    };
  },
  computed: {
    // 页面类型，0 保持不动，1显示方式为新页面显示方式
    pageType() {
      return Number(this.$route.query.pageType) || 0
    },
    anxietyText() {
      const appTypeList = ['1'];
      return appTypeList.indexOf(this.$store.getters.appType) > -1 ? `忧郁` : `抑郁`
    },
    // 默认折线图配置，echarts 具体配置 见 https://echarts.apache.org/zh/option.html#title
    defaultOptions() {
      return {
        time: {
          useUTC: false,
        },
        title: {
          text: this.echartsTitle,
          left: 1,
          right: 25,
          bottom: 20,
          top: "3%",
          textStyle: {
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        legend: {
          width: "65%",
          orient: "horizontal",
          right: "5%",
          top: 1,
          bottom: "1%",
          itemHeight: 12,
          itemWidth: 12,
          itemGap: 10,
          align: "left",
          selectedMode: false,
          data: [
            {
              name: `无${this.emoName}倾向`,
              icon: "rect",

              itemStyle: {
                color: "#62BD48",
              },
              textStyle: {
                fontSize: 12,
              },
            },
            {
              name: `轻度${this.emoName}倾向`,
              icon: "rect",
              itemStyle: {
                color: "#ffde00",
              },
              textStyle: {
                fontSize: 12,
              },
            },
            {
              name: `中度${this.emoName}倾向`,
              itemStyle: {
                color: "#ff8a00",
              },
              icon: "rect",
              textStyle: {
                fontSize: 12,
              },
            },
            {
              name: `重度${this.emoName}倾向`,
              itemStyle: {
                color: "#d70d0d",
              },
              icon: "rect",
              textStyle: {
                fontSize: 12,
              },
            },
          ],
          formatter: function (name) {
            // 自定义显示内容
            if (name.length > 6) {
              return name.substring(0, 6) + "\n" + name.substring(6);
            } else {
              return name;
            }
          },
        },
        grid: {
          show: true,
          borderWidth: 1,
          top: "20%",
          left: "1%",
          right: "5%",
          bottom: "10%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          axisLine: {
            show: false,
          },
          textStyle: {
            fontSize: 10,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: "#ddd",
              width: 2,
            },
          },
          nameLocation: "center",
          axisLabel: {
            show: true,
            fontSize: 12,
            showMinLabel: true, //显示最小值
            showMaxLabel: true, //显示最大值
          },
          data: this.xAxisData,
        },
        dataZoom: [
          /*  {
                        type: "inside",
                        start: 0,
                        end: 100,
                    }, */
          {
            start: 0,
            end: 100,
            textStyle: {
              color: "#FFF",
              fontSize: 14,
            },
            show: true,
            height: 15,
            bottom: 5,
            handleStyle: {
              borderWidth: 1,
              borderCap: "square",
            },
          },
        ],
        tooltip: {
          trigger: "axis",
          textStyle: {
            fontSize: 14,
            align: "center",
          },
          formatter: function (params) {
            return (
              params[0].marker +
              params[0].name +
              "--" +
              params[0].value +
              "</br>"
            );
          },
        },
        yAxis: {
          type: "value",
          max: 100,
          min: 0,
          interval: 20,
          splitNumber: 1,
          boundaryGap: ["5%", "5%"],
          nameTextStyle: {
            fontSize: 13,
          },
          alignTicks: true,
          axisTick: {
            show: true,
          },
          axisLabel: {
            show: true,
            fontSize: 13,
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#ddd",
              width: 1,
            },
          },
        },
        series: [
          {
            name: `无${this.emoName}倾向`,
            type: "line",
            padding: 5,
            data: this.emotionData,
            symbol: "circle",
            symbolSize: 8,
          },
          {
            name: `轻度${this.emoName}倾向`,
            type: "line",
            data: "",
          },
          {
            name: `中度${this.emoName}倾向`,
            type: "line",
            data: "",
          },
          {
            name: `重度${this.emoName}倾向`,
            type: "line",
            data: "",
          },
        ],
      };
    },
    imei() {
      return this.$store.getters.serialNo;
    },
    // 饼状图配置
    pieOption() {
      return {
        tooltip: {
          trigger: "item",
          textStyle: {
            fontSize: 14,
          },
          position: "right",
        },
        legend: {
          top: "5%",
          left: "center",
          show: false,
        },
        series: [
          {
            type: "pie",
            radius: ["40%", "80%"],
            avoidLabelOverlap: false,
            startAngle: 270, // 设置逆时针渲染
            itemStyle: {
              borderRadius: 5,
              borderColor: "#fff",
              borderWidth: 2,
              fontSize: 16,
            },
            label: {
              show: false,
              position: "center",
              fontSize: 16,
            },
            emphasis: {
              label: {
                show: false,
                fontSize: 16,
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: this.pieData,
          },
        ],
      };
    },
    pieDayOption() {
      return {
        tooltip: {
          trigger: "item",
          textStyle: {
            fontSize: 14,
          },
          position: "right",
        },
        legend: {
          top: "5%",
          left: "center",
          show: false,
        },
        series: [
          {
            type: "pie",
            radius: ["40%", "80%"],
            avoidLabelOverlap: false,
            startAngle: 270, // 设置逆时针渲染
            itemStyle: {
              borderRadius: 5,
              borderColor: "#fff",
              borderWidth: 2,
              fontSize: 16,
            },
            label: {
              show: false,
              position: "center",
              fontSize: 16,
            },
            emphasis: {
              label: {
                show: false,
                fontSize: 16,
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: this.pieDayData,
          },
        ],
      };
    },
    titleLeft() {
      let text = this.emoName === "depression" ? "趋势" : "";
      let today = "";
      if (this.currentDays !== 0) {
        today = "";
      } else {
        today =
          this.$dayjs(this.selectDate || this.defaultDate).format(
            "YYYY-MM-DD"
          ) === this.$dayjs(new Date()).format("YYYY-MM-DD")
            ? "今天"
            : "";
      }
      return `${today}${this.emoName}倾向${text}`;
    },
    // 折线图标题
    echartsTitle() {
      let today = "";
      if (this.currentDays !== 0) {
        today = "";
      } else {
        today =
          this.$dayjs(this.selectDate || this.defaultDate).format(
            "YYYY-MM-DD"
          ) === this.$dayjs(new Date()).format("YYYY-MM-DD")
            ? "今天"
            : "";
      }
      return `${today}${this.emoName}数据图`;
    },
    warmTips() {
      return `正常连续佩戴腕表，每${this.emoType == 2 ? "一" : "半"
        }小时计算一个${this.emoName}分值。`;
      /* return `正常连续佩戴手表，每半小时计算一个${this.emoName}分值，睡眠期间不进行计算。` */
    },
    title1() {
      return this.params.name ? this.$replaceAll(EmotionModel[this.params.name].title1, '抑郁', '忧郁') : ''
    },
    article1() {
      return this.params.name ? this.$replaceAll(EmotionModel[this.params.name].article1, '抑郁', '忧郁') : ''
    },
    title2() {
      return this.params.name ? this.$replaceAll(EmotionModel[this.params.name].title2, '抑郁', '忧郁') : ''
    },
    article2() {
      return this.params.name ? this.$replaceAll(EmotionModel[this.params.name].article2, '抑郁', '忧郁') : ''
    },
    // 当前情绪颜色
    currentColor() {
      return this.calcResultColor(this.resultLevel) || "#62BD48";
    },
  },
  watch: {
    // 监听数据发生变化 初始化各项图表
    emotionData: {
      handler(n, o) {
        this.initEchart();
      },
      deep: true,
    },
    xAxisData: {
      handler(n, o) {
        this.initEchart();
      },
      deep: true,
    },
    pieData: {
      handler(n, o) {
        this.initPieEchart();
      },
      deep: true,
    },
    pieDayData: {
      handler(n, o) {
        this.initPieDayEchart();
      },
      deep: true,
    }
  },
  created() {},
  mounted() {
    this.initData();
    /* window.addEventListener("resize", this.onResize, false); */
  },
  destroyed(){
    /* window.removeEventListener("resize", this.onResize, false); */
},
  methods: {
    async initData(){
      // 读取路由传过来的参数，根据路由传过来的参数判断是哪种情绪
      await this.loadParams();
      this.initEchartText();
      this.getCalendarData();

      this.$nextTick(()=>{
        this.getWeekResult();
        this.getWeekResultDetail();
        if(this.params.current) {
          this.current = Number(this.params.current);
          this.currentDays = this.calcDaysByTabClick(
            Number(this.params.current)
          );
        } else {
          this.current = Number(this.$store.getters.tabClick) || 0;
          this.currentDays = this.calcDaysByTabClick(
            Number(this.$store.getters.tabClick)
          );
        }
        
        this.psyCurrent = this.calcPsyTabindex(EmotionModel[this.params.name].type);
        window.document.title = "心理监测";
      })
    },
    /* onResize(){
        if(this.pieEcharts){
          this.pieEcharts.resize();
        }
        if(this.echarts) {
          this.echarts.resize();
        }
    }, */
    calcWeekImg(cur, last, callBackText) {
      let imgurl = "";
      let text = "";
      if (isNotNull(cur) && isNotNull(last) && this.weekAndMonData.length > 0) {
        let curNumber = Number(cur);
        let latNumber = Number(last);
        if (curNumber - latNumber == 0) {
          text = "持平";
        } else {
          imgurl = curNumber < latNumber ? this.downImg : this.upImg;
          text = Math.abs(curNumber - latNumber) + "天";
        }
        if (callBackText) {
          return text;
        } else {
          return imgurl;
        }
      }
    },
    // 计算显示是上升or下降的图片
    /**
     *
     * @param { 本周情绪比例} current
     * @param { 上周情绪比例 } last
     * @param { 是否返回对比比例 } isCallBackCompare
     */
     calcImg(current, last, isCallBackCompare) {
        let imgUrl = "";
        let compare = "";
        if (isNotNull(current) && isNotNull(last)) {
          compare = Number(current) - Number(last);
          imgUrl = compare > 0 ? this.upImg : compare == 0 ? "" : this.downImg;
        }
        if (isCallBackCompare) {
          return compare;
        } else {
          return imgUrl;
        }
    },
    async loadParams() {
      let params = this.$route.query;
      if (params) {
        this.emoName = this.$replaceAll(EmotionModel[params.name].name, '抑郁', '忧郁');
        this.emoType = EmotionModel[params.name].type;
        this.uid = params.uid;
        this.routeDate = params.date;
        this.params = params;
        this.currentEmoName = params.name;

        if(params.isShowLeft === 'false'){
          this.isShowLeft = false
        }
        if(params.isshowTab === 'false'){
          this.isshowTab = false
        }

        if (params.date) {
          this.dateList[0].text =
            this.$dayjs(params.date).format("YYYY-MM-DD") ===
              this.$dayjs(new Date()).format("YYYY-MM-DD")
              ? "今天"
              : this.$dayjs(params.date).format("MM-DD");
          this.defaultDate = new Date(
            this.$dayjs(params.date).hour(0).minute(0).second(0).format()
          );
        }

        // 获取token
        if (!params.accessToken) {
          this.$toast.loading({
            message: "数据加载中",
          });
          let authToken = await this.getAuth();
          this.$toast.clear()
          this.$store.commit("ssjlToken", authToken);
        } else {
          this.$store.commit("ssjlToken", params.accessToken);
        }
      }
    },
    //   获取b端token
    getAuth() {
      let manufactorId = "5bf13062-a41e-4d00-ba14-1101aad12650";
      let that = this;
      return new Promise((resolve, reject) => {
        APICore.getAuth({ manufactorId: manufactorId }).then((res) => {
          let data = res.data;
          if (data.code === 0) {
            resolve(res.data.data);
          } else {
            this.$toast.fail(`${data.message}`);
            reject("");
          }
        });
      });
    },
    // 计算点击的天数
    calcDaysByTabClick(value) {
      let days = "";
      console.log("value", value);
      switch (value) {
        case 0:
          days = 0;
          break;
        case 1:
          days = 7;
          break;
        case 2:
          days = 30;
          break;
        case 3:
          days = 49;
          break;
        default:
          break;
      }
      return days;
    },
    // 计算psyTab的下标值
    calcPsyTabindex(type) {
      let psyIndex = "";
      switch (type) {
        case 1:
          psyIndex = 1;
          break;
        case 2:
          psyIndex = 2;
          break;
        case 3:
          psyIndex = 0;
          break;
        default:
          break;
      }
      return psyIndex;
    },
    // 获取这个月中有数据的日期，控制日历组件的日期样式
    getCalendarData() {
      let currentDate = new Date();
      // 获取最近30天的心情等级日历数据
      let dateList = this.getPostDate(currentDate, 30, true);
      let reqUrl = `${PsyBaseUrl}/api/Data/GetCalendarData`;
      let reqParams = {
        uid: this.uid,
        startDate: dateList[0],
        endDate: dateList[1],
      };
      axios
        .get(reqUrl, {
          params: { ...reqParams },
          headers: { AccessToken: this.$store.getters.ssjlToken },
        })
        .then((res) => {
          if (res.data) {
            let data = res.data.response;
            // const mergedArr = [...new Set([...arr1, ...arr2, ...arr3])];
            /* let name = this.params.name.charAt(0).toUpperCase()+ this.params.name.slice(1); */
            let currentName = this.currentEmoName;
            let list = [];
            if (currentName === "stress") {
              list = data.Stress;
            } else if (currentName === "depression") {
              list = data.Depression;
            } else {
              list = data.Tiredness;
            }
            list = list.map((item) => {
              item.Date = this.$dayjs(item.Date.replace(/-/g, "/")).format(
                "YYYY/MM/DD"
              );
              return item;
            });
            this.highlightDates = [...list];
          }
        });
    },
    // 获取饼状图数据，TODO 对接接口数据
    getPieData() {
      this.pieData = [
        { value: 12, name: "", itemStyle: { color: "green" } },
        { value: 2, name: "", itemStyle: { color: "orange" } },
        { value: 1, name: "", itemStyle: { color: "#FFC0CB" } },
        { value: 1, name: "", itemStyle: { color: "red" } },
      ];
    },
    // 获取情绪数据
    getPsychologiclData(date, startDate, endDate) {
      this.$toast.loading({
        message: "数据加载中",
      });
      let reqDate = date
        ? this.$dayjs(date).format("YYYY-MM-DD")
        : this.routeDate ||
        this.$dayjs(this.defaultDate).format("YYYY-MM-DD"); /* "2023-05-23" */
      let reqParams = {
        uid: this.uid,
        startDate: startDate || reqDate,
        endDate: endDate || reqDate,
        type: this.emoType,
      };
      console.log("请求参数", reqParams);
      let reqUrl = `${PsyBaseUrl}/api/Data/GetHisData`;
      axios
        .get(reqUrl, {
          params: { ...reqParams },
          headers: { AccessToken: this.$store.getters.ssjlToken },
        })
        .then((res) => {
          if (res.data) {
            let data = res.data.response;
            // 监测次数
            this.monitoringCount = data.Count;
            this.pieRightList = [];
            this.statisticsList = [];
            this.emotionList = [];
            let None = {
              count: data.None,
              percentage: this.calcPercentage(data.None, data.Count),
              text: `无${this.emoName}倾向`,
              color: "#62BD48",
            };
            let Mild = {
              count: data.Mild,
              percentage: this.calcPercentage(data.Mild, data.Count),
              text: `轻度${this.emoName}倾向`,
              color: "#ffde00",
            };
            let Moderate = {
              count: data.Moderate,
              percentage: this.calcPercentage(data.Moderate, data.Count),
              text: `中度${this.emoName}倾向`,
              color: "#ff8a00",
            };
            let Severe = {
              count: data.Severe,
              percentage: this.calcPercentage(data.Severe, data.Count),
              text: `重度${this.emoName}倾向`,
              color: "#d70d0d",
            };
            // 饼状图右边数据
            this.pieRightList.push(None);
            this.pieRightList.push(Mild);
            this.pieRightList.push(Moderate);
            this.pieRightList.push(Severe);
            this.pieDayData = this.pieRightList.map((item) => {
              item.value = item.count;
              item.itemStyle = {
                color: item.color,
              };
              return item;
            });
            // 最大，最小和最近值
            let Max = {
              label: "最大值",
              value: data.Max,
              time: data.MaxDesc
                ? this.currentDays === 0
                  ? this.$dayjs(data.MaxDesc).format("HH:mm")
                  : this.$dayjs(data.MaxDesc).format("MM/DD HH:mm")
                : "",
              level: data.MaxLevel
            };
            let Min = {
              label: "最小值",
              value: data.Min,
              time: data.MinDesc
                ? this.currentDays === 0
                  ? this.$dayjs(data.MinDesc).format("HH:mm")
                  : this.$dayjs(data.MinDesc).format("MM/DD HH:mm")
                : "",
              level: data.MinLevel
            };
            let Avg = {
              label: "平均值",
              value: data.Avg,
              time: data.AvgDesc
                ? this.currentDays === 0
                  ? this.$dayjs(data.AvgDesc).format("HH:mm")
                  : this.$dayjs(data.AvgDesc).format("MM/DD HH:mm")
                : "",
              level: data.AvgLevel
            };
            let Current = {
              label: "最近值",
              value: data.Current,
              time: data.CurrentDesc
                ? this.currentDays === 0
                  ? this.$dayjs(data.CurrentDesc).format("HH:mm")
                  : this.$dayjs(data.CurrentDesc).format("MM/DD HH:mm")
                : "",
              level: data.CurrentLevel
            };
            this.statisticsList.push(Max);
            this.statisticsList.push(Min);
            this.statisticsList.push(Avg);
            this.statisticsList.push(Current);
            // 周报月报底部显示数据
            let NoneDay = {
              days: data.NoneDay,
              text: `无${this.emoName}倾向`,
              color: "#62BD48",
            };
            let MildDay = {
              days: data.MildDay,
              text: `轻度${this.emoName}倾向`,
              color: "#ffde00",
            };
            let ModerateDay = {
              days: data.ModerateDay,
              text: `中度${this.emoName}倾向`,
              color: "#ff8a00",
            };
            let SevereDay = {
              days: data.SevereDay,
              text: `重度${this.emoName}倾向`,
              color: "#d70d0d",
            };
            this.emotionList.push(NoneDay);
            this.emotionList.push(MildDay);
            this.emotionList.push(ModerateDay);
            this.emotionList.push(SevereDay);
            // 图表数据
            this.emotionData = data.ChartDatas.map((item) => {
              return {
                value: item.Value,
                itemStyle: {
                  color: this.calcResultColor(item.Level),
                },
              };
            });
            // 7天 和 30天柱形图显示
            this.weekAndMonData = data.ChartDatas.map((item, index) => {
              return {
                value: [index, item.MinValue, item.MaxValue],
              };
            });
            // x轴显示数据
            if (this.currentDays === 0) {
              // 显示今天数据
              this.xAxisData = data.ChartDatas.map((item) => {
                return this.$dayjs(item.Key.replace(/-/g, "/")).format("HH:mm");
              });
            } else {
              this.xAxisData = data.ChartDatas.map((item) => {
                return this.$dayjs(item.Key.replace(/-/g, "/")).format("MM/DD");
              });
              let emphasisStyle = {
                itemStyle: {
                  shadowBlur: 10,
                  shadowColor: "rgba(0,0,0,0.3)",
                },
              };
              let that = this;
              // 7天和30天变成柱状图
              this.weekAndMonthSeries = [
                {
                  name: "平均值",
                  type: "scatter",
                  symbolSize: 8,
                  data: this.emotionData,
                },
                {
                  name: "",
                  type: "custom",
                  data: this.weekAndMonData,
                  renderItem: function (params, api) {
                    var categoryIndex = api.value(0);
                    var end = api.coord([categoryIndex, api.value(1)]);
                    var start = api.coord([categoryIndex, api.value(2)]);
                    var width = 8;
                    var rectShape = that.$echarts.graphic.clipRectByRect(
                      {
                        x: start[0] - width / 2,
                        y: start[1],
                        width: 8,
                        height: end[1] - start[1],
                      },
                      {
                        x: params.coordSys.x,
                        y: params.coordSys.y,
                        width: params.coordSys.width,
                        height: params.coordSys.height,
                      }
                    );
                    if (rectShape) {
                      rectShape.r = [10];
                    }
                    return (
                      rectShape && {
                        type: "rect",
                        shape: rectShape,
                        style: api.style(),
                      }
                    );
                  },
                  itemStyle: {
                    opacity: 0.8,
                  },
                  encode: {
                    y: [1, 2],
                    x: 0,
                  },
                },
                {
                  name: `轻度${this.emoName}倾向`,
                  type: "scatter",
                  symbolSize: 8,
                  data: "",
                },
                {
                  name: `中度${this.emoName}倾向`,
                  type: "scatter",
                  symbolSize: 8,
                  data: "",
                },
                {
                  name: `重度${this.emoName}倾向`,
                  type: "scatter",
                  symbolSize: 8,
                  data: "",
                },
                {
                  name: `无${this.emoName}倾向`,
                  type: "scatter",
                  symbolSize: 8,
                  data: "",
                },
              ];
              // 点击提示此时为空
              this.defaultOptions.tooltip = {
                trigger: "axis",
                formatter: function (params) {
                  return (
                    params[0].marker +
                    "平均值:" +
                    params[0].name +
                    "--" +
                    params[0].value +
                    "</br>" +
                    params[1].marker +
                    "最大值:" +
                    params[1].name +
                    "--" +
                    params[1].value[2] +
                    "</br>" +
                    params[1].marker +
                    "最小值:" +
                    params[1].name +
                    "--" +
                    params[1].value[1]
                  );
                },
              };
              this.defaultOptions.series = this.weekAndMonthSeries;
            }
            // 结果解读
            this.result = data.Result;
            this.resultLevel = data.ResultLevel;
            this.advice = data.Advice;
            this.$toast.success({
              message: "数据加载完成",
            });
          }
        })
        .catch(() => {
          this.$dialog({
            message: "登录过期，请重新进入",
          });
        })
        .finally(() => { });
    },
    // 计算百分比
    calcPercentage(value, total) {
      if (
        typeof value !== "number" ||
        typeof total !== "number" ||
        total === 0
      ) {
        return 0;
      }
      let milValue = value * 1000;
      let milTotal = total * 1000;
      return Math.round((milValue / milTotal) * 100);
    },
    // 初始化图表的文字内容
    initEchartText() {
      let text = this.emoName === "depression" ? "趋势" : "";
      let today =
        this.$dayjs(this.defaultDate).format("YYYY-MM-DD") ===
          this.$dayjs(new Date()).format("YYYY-MM-DD")
          ? "今天"
          : "";
      this.result = `无${this.emoName}倾向`;
      this.defaultSeries = [
        {
          name: ``,
          type: "line",
          padding: 5,
          data: this.emotionData,
          symbol: "circle",
          symbolSize: 8, // 拐点圆的大小
          areaStyle: {},
        },
        {
          name: `轻度${this.emoName}倾向`,
          type: "line",
          padding: 10,
          data: "",
          symbol: "circle",
          symbolSize: 8, // 拐点圆的大小
        },
        {
          name: `中度${this.emoName}倾向`,
          type: "line",
          data: "",
        },
        {
          name: `重度${this.emoName}倾向`,
          type: "line",
          data: "",
        },
      ];
      this.pieRightList = this.pieRightList.map((item) => {
        item.text = item.text.replace("情绪", this.emoName);
        return item;
      });
    },
    // 初始化饼状图
    initPieEchart() {
      if (
        this.pieEcharts != null &&
        this.pieEcharts != "" &&
        this.pieEcharts != undefined
      ) {
        this.pieEcharts.dispose();
      }
      this.pieEcharts = this.$echarts.init(this.$refs.pieChart);
      this.pieEcharts.setOption(this.pieOption);


     
    },
    initPieDayEchart() {
      if (
        this.pieDayEcharts != null &&
        this.pieDayEcharts != "" &&
        this.pieDayEcharts != undefined
      ) {
        this.pieDayEcharts.dispose();
      }
      this.pieDayEcharts = this.$echarts.init(this.$refs.pieChartDay);
      this.pieDayEcharts.setOption(this.pieDayOption);
    },
    // 格式化日期显示参数
    formatter(day) {
      const month = day.date.getMonth() + 1;
      const date = day.date.getDate();
      const formatDate = this.$dayjs(day.date).format("YYYY/MM/DD");
      const currentDate = this.$dayjs(new Date()).format("YYYY/MM/DD");
      day.className = "custom-calendar";
      for (let h = 0; h < this.highlightDates.length; h++) {
        if (this.highlightDates[h].Date === formatDate) {
          day.className = `highlight-border ${this.calcResultColor(
            this.highlightDates[h].SummaryLevel,
            true
          )}`;
        } else if (formatDate === currentDate) {
          day.text = "今天";
        }
      }
      return day;
    },
    //   返回
    onNavBack() {
      this.$router.replace({
        name: "psychological",
        query: {
          name: this.params.name,
          uid: this.params.uid,
          pageType: 1,
          current: this.params.current
        },
      });
    },
    // 点击日期选择
    onTabClick(value, index) {
      this.current = index;
      this.currentDays = value;
      this.$store.commit("tabClick", index);
      let currentDate = value === 0 ? new Date() : new Date(this.$dayjs().subtract(1, 'days'))
      this.surveyTitle = value === 7 ? "7天概览" : "30天概览";
      if (value === 7) {
        let dateList = this.getPostDate(currentDate, 6, true);
        this.getPsychologiclData("", dateList[0], dateList[1]);
        this.startDate = dateList[0];
        this.endDate = dateList[1];
      } else if (value === 0) {
        // 今天
        this.defaultOptions.xAxis.data = this.xAxisData;
        this.defaultOptions.series = this.defaultSeries;
        this.defaultOptions.series[0].data = this.emotionData;
        this.getPsychologiclData(
          this.selectDate
            ? this.selectDate
            : this.$dayjs(currentDate).format("YYYY-MM-DD")
        );
        this.startDate =
          this.selectDate || this.$dayjs(currentDate).format("YYYY-MM-DD");
        this.endDate =
          this.selectDate || this.$dayjs(currentDate).format("YYYY-MM-DD");
      } else if (value === 30) {
        // 30天
        this.defaultOptions.xAxis.data = this.xAxisData;
        this.defaultOptions.series = this.defaultSeries;
        this.defaultOptions.series[0].data = this.emotionData;
        let dateList = this.getPostDate(currentDate, 30, true);
        this.getPsychologiclData("", dateList[0], dateList[1]);
        this.startDate = dateList[0];
        this.endDate = dateList[1];
      } else {
        // 周报菜单
        console.log("点击周报");
        this.onPsyTabClick(this.psyList[this.psyCurrent].name, this.psyCurrent);
        /* this.getWeekResultDetail(); */

      }
    },
    // 点击情绪tab
    async onPsyTabClick(name, index) {
      this.psyCurrent = index;
      this.emoName = this.$replaceAll(EmotionModel[name].name, '抑郁', '忧郁');
      this.currentEmoName = name;
      this.emoType = EmotionModel[name].type;
      console.log("this.currentDays", this.currentDays);
      if (this.currentDays === 49) {
        // 即点击了周报,此时调用获取周报详情接口
        // 根据 getWeekResult 获取到的的周报列表筛选出指定日期的类型
        let recordId = await this.getWeekResult();
        if(recordId) {
          this.getWeekResultDetail(recordId)
        }

      } else {

        this.getPsychologiclData(this.selectDate, this.startDate, this.endDate);
      }
      this.getCalendarData();
    },
    getCurrentMonthStaAndEnd(currentDate) {
      let list = [];
      let monthStart = new Date(
        currentDate.getFullYear(),
        currentDate.getMonth(),
        1
      ); // 获取本月第一天的日期时间
      let monthEnd = new Date(
        currentDate.getFullYear(),
        currentDate.getMonth() + 1,
        0,
        23,
        59,
        59
      ); // 获取本月最后一天的日期时间（时间为23:59:59）
      list.push(this.$dayjs(monthStart).format("YYYY-MM-DD"));
      list.push(this.$dayjs(monthEnd).format("YYYY-MM-DD"));
      return list;
    },
    // 获取指定天数的起始日期
    /**
     *
     * @param dateNow :Date类
     * @param intervalDays ：间隔天数
     * @param bolPastTime  ：Boolean,判断在参数date之前，还是之后，
     */
    getPostDate(dateNow, intervalDays, bolPastTime) {
      let oneDayTime = 24 * 60 * 60 * 1000;
      let list = [];
      let lastDay;

      if (bolPastTime == true) {
        lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
        list.push(this.formateDate(lastDay));
        list.push(this.formateDate(dateNow));
      } else {
        lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
        list.push(this.formateDate(dateNow));
        list.push(this.formateDate(lastDay));
      }
      return list;
    },
    formateDate(time) {
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let day = time.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return year + "-" + month + "-" + day + "";
    },
    // 字体大小转化
    fontChar(res) {
      const clientWidth =
        window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth;
      if (!clientWidth) return;
      let fontSize = clientWidth / 750;
      return res * fontSize;
    },
    // 初始化折线图表
    initEchart() {
      if(this.current === 3) {
        // 周报详情
        if (
        this.echarts != null &&
        this.echarts != "" &&
        this.echarts != undefined
      ) {
        this.echarts.resize();
        this.echarts.dispose();
      }
      this.echarts = this.$echarts.init(this.$refs.charts);
      this.echarts.setOption(this.defaultOptions);
      } else {
        if (
        this.dayEcharts != null &&
        this.dayEcharts != "" &&
        this.dayEcharts != undefined
      ) {
        this.dayEcharts.resize();
        this.dayEcharts.dispose();
      }
      this.dayEcharts = this.$echarts.init(this.$refs.dayCharts);
      this.dayEcharts.setOption(this.defaultOptions);
      }
      
    },
    // 点击历史监测，打开日历
    onHistory() {
      this.calendarDialogShow = true;
    },
    // 选择日历具体某一个日期
    onSelect(value) {
      const selectDate = this.$dayjs(value).format("YYYY-MM-DD");
      this.dateList[0].text =
        this.$dayjs(value).format("YYYY-MM-DD") ===
          this.$dayjs(new Date()).format("YYYY-MM-DD")
          ? "今天"
          : this.$dayjs(value).format("MM-DD");
      this.calendarDialogShow = false;
      this.selectDate = selectDate;
      this.startDate = selectDate;
      this.endDate = selectDate;
      this.current = 0;
      this.getPsychologiclData(selectDate);
    },
    // 计算字体显示的颜色
    calcColor(value) {
      let color = "";
      if (value <= 40) {
        color = "#62BD48";
      } else if (value > 40 && value <= 65) {
        color = "#ffde00";
      } else if (value > 65 && value <= 80) {
        color = "#ff8a00";
      } else if (value > 80) {
        color = "#d70d0d";
      } else {
        color = "";
      }
      return color;
    },
    // 计算结果采用哪种颜色
    calcResultColor(value, isCallBackClass) {
      let color = "";
      let className = "";
      switch (Number(value)) {
        case 0:
          color = "#62BD48";
          className = "none";
          break;
        case 1:
          color = "#ffde00";
          className = "mild";
          break;
        case 2:
          color = "#ff8a00";
          className = "moderate";
          break;
        case 3:
          color = "#d70d0d";
          className = "severe";
          break;
      }
      return isCallBackClass ? className : color;
    },
    // 点击帮助
    onHelp() {
      this.isPopup = true;
    },
    // 关闭poup
    onClose() {
      this.isPopup = false;
    },
    //循环调用3次 GetWeekResult 接口
    async getWeekResultAny() {

      Promise.all([
        await this.getWeekResultPro(1),
        await this.getWeekResultPro(2),
        await this.getWeekResultPro(3),
      ]).then(res => {
        let weekResultLists = res.reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])

        let typeMap = {};
        weekResultLists.forEach(item => {
          if (!typeMap[item.name]) {
            typeMap[item.name] = {
              name: item.name,
              recordId: [],
              summary: [],
              summaryLevel: [],
              summaryDetails: [],
              type: item.type,

            };
            weekResultLists.push(typeMap[item.name]);
          }

          typeMap[item.name].recordId.push(item.recordId);
          typeMap[item.name].summary.push(item.summary);
          typeMap[item.name].summaryLevel.push(item.summaryLevel);
          let combinedArray = typeMap[item.name].summary.map((sum, index) => ({ summary: sum, summaryLevel: typeMap[item.name].summaryLevel[index] }));
          console.log(combinedArray);
          typeMap[item.name].summaryDetails = combinedArray

        });
        let array = Object.entries(typeMap);
        this.weekResultList = array;
        console.log("weekResultLists", this.weekResultList);
        console.log("typeMap", typeMap);
      });

    },
    getWeekResultPro(type) {
      let baseUrl =
        process.env.NODE_ENV === "production"
          ? "https://dbmq.rzliot.com/auth_heart"
          : "https://dbmq.rzliot.com/heart";
      let reqUrl = `${baseUrl}/api/Data/GetWeekResult`;
      let reqParams = {
        uid: this.uid /* '2023101521270090082' */,
        type: type || this.emoType,
      };
      
      axios
          .get(reqUrl, {
            params: { ...reqParams },
            /*  headers: { 'AccessToken': this.$store.getters.ssjlToken } */
          }).then(res => {
            const data = res.data.response;
            let summaryList = data.map(item => {
              return {
                name: item.Name.replace("周报", "")
                  .replace(/-/g, ".")
                  .replace(/~/g, "-"),
                recordId: item.RecordId,
                summary: this.$replaceAll(item.Summary, '抑郁', '忧郁'),
                summaryLevel: item.SummaryLevel,
                type: item.Type,
              };
            });
          })
    },
    getWeekResult(type) {
      this.$toast.loading("数据加载中");
      let baseUrl =
        process.env.NODE_ENV === "production"
          ? "https://dbmq.rzliot.com/auth_heart"
          : "https://dbmq.rzliot.com/heart";
      let reqUrl = `${baseUrl}/api/Data/GetWeekResult`;
      let reqParams = {
        uid: this.uid /* '2023101521270090082' */,
        type: this.emoType,
      };
      return new Promise(resolve => {
        axios
        .get(reqUrl, {
          params: { ...reqParams },
        })
        .then((res) => {
          console.log("res", res);
          const data = res.data.response;
          let time = this.$route.query.time;
          let selectData = data.filter(item => {
            return item.Name.replace("周报", "")
                  .replace(/-/g, ".")
                  .replace(/~/g, "-") === time
          });
          console.log("selectData", selectData);
          let recordId = selectData && selectData[0].RecordId;
          console.log("根据当前日期不同emoType得到的周报列表数据", selectData);
          this.$toast.success("数据加载完成");
          resolve(recordId)
          
        });
      })
      
    },
    onClickItem(recordId) {
      this.$router.push({
        name: "psychologicalReport",
        query: {
          recordId: recordId,
          name: this.currentEmoName,
          isShowLeft: true,
          uid: this.uid,
        },
      });
    },
    // 重新拼接日期
    resetDate(startDate, endDate) {
      let callBackDate = "";
      if (startDate && endDate) {
        callBackDate =
          startDate.replace(/-/g, ".") +
          "-" +
          endDate.slice(5, endDate.length).replace(/-/g, ".");
      }
      return callBackDate;
    },
    async getWeekResultDetail(recordId) {
      // 优先取传过来的值
      if(!recordId){
        recordId = this.$route.query.recordId
      }
      // 没有则自动取
      if(!recordId) {
        recordId = await this.getWeekResult();
      }

      this.$toast.loading("数据加载中");
      let baseUrl =
        process.env.NODE_ENV === "production"
          ? "https://dbmq.rzliot.com/auth_heart"
          : "https://dbmq.rzliot.com/heart";
      let reqUrl = `${baseUrl}/api/Data/GetWeekResultDetail`;
      let reqParams = {
        recordId: recordId,
      };
      axios
        .get(reqUrl, {
          params: { ...reqParams },
          /*  headers: { 'AccessToken': this.$store.getters.ssjlToken } */
        })
        .then((res) => {
          const data = res.data.response;
          let chartData = data.ChartData
            ? JSON.parse(data.ChartData).filter((item) => {
              return item.Key;
            })
            : [];
          console.log("chartData", chartData);
          if (data) {
            this.monitoringCount = data.Total;
            this.pieRightList = [];
            this.statisticsList = [];
            this.emotionList = [];
            this.weekResult = data;
            this.weekResult.Explain = this.$replaceAll(data.Explain, '抑郁', '忧郁')
            this.weekResult.Summary = this.$replaceAll(data.Summary, '抑郁', '忧郁')
            this.weekResult.Advice = this.$replaceAll(data.Advice, '抑郁', '忧郁')
            this.emoName = this.calcTitle(data.Type);
            this.isShowCompare = data.LastweekData;
          }
          let None = {
            count: data.None,
            percentage: this.calcPercentage(data.None, data.Total),
            text: `无${this.emoName}倾向`,
            color: "#62BD48",
            scale: data.NoneRatio,
            lastPercentage: this.calcPercentage(data.LastNone, data.LastTotal),
          };
          let Mild = {
            count: data.Mild,
            percentage: this.calcPercentage(data.Mild, data.Total),
            text: `轻度${this.emoName}倾向`,
            color: "#ffde00",
            scale: data.MildRatio,
            lastPercentage: this.calcPercentage(data.LastMild, data.LastTotal),
          };
          let Moderate = {
            count: data.Moderate,
            percentage: this.calcPercentage(data.Moderate, data.Total),
            text: `中度${this.emoName}倾向`,
            color: "#ff8a00",
            scale: data.ModerateRatio,
            lastPercentage: this.calcPercentage(
              data.LastModerate,
              data.LastTotal
            ),
          };
          let Severe = {
            count: data.Severe,
            percentage: this.calcPercentage(data.Severe, data.Total),
            text: `重度${this.emoName}倾向`,
            color: "#d70d0d",
            scale: data.SevereRatio,
            lastPercentage: this.calcPercentage(
              data.LastSevere,
              data.LastTotal
            ),
          };
          // 饼状图右边数据
          this.pieRightList.push(None);
          this.pieRightList.push(Mild);
          this.pieRightList.push(Moderate);
          this.pieRightList.push(Severe);
          this.pieData = this.pieRightList.map((item) => {
            item.value = item.count;
            item.itemStyle = {
              color: item.color,
            };
            return item;
          });
          let Max = {
            label: "最大值",
            value: data.Max,
            time: data.MaxDesc
              ? this.currentDays === 0
                ? this.$dayjs(data.MaxDesc).format("HH:mm")
                : this.$dayjs(data.MaxDesc).format("MM/DD HH:mm")
              : "",
            level: data.MaxLevel
          };
          let Min = {
            label: "最小值",
            value: data.Min,
            time: data.MinDesc
              ? this.currentDays === 0
                ? this.$dayjs(data.MinDesc).format("HH:mm")
                : this.$dayjs(data.MinDesc).format("MM/DD HH:mm")
              : "",
            level: data.MinLevel
          };
          let Avg = {
            label: "平均值",
            value: data.Avg,
            time: data.AvgDesc
              ? this.currentDays === 0
                ? this.$dayjs(data.AvgDesc).format("HH:mm")
                : this.$dayjs(data.AvgDesc).format("MM/DD HH:mm")
              : "",
            level: data.AvgLevel
          };
          this.statisticsList.push(Max);
          this.statisticsList.push(Min);
          this.statisticsList.push(Avg);
          let NoneDay = {
            days: data.NoneDay,
            text: `无${this.emoName}倾向`,
            color: "#62BD48",
            lastDay: data.LastNoneDay,
            scale: data.NoneDayRatio,
          };
          let MildDay = {
            days: data.MildDay,
            text: `轻度${this.emoName}倾向`,
            color: "#ffde00",
            lastDay: data.LastMildDay,
            scale: data.MildDayRatio,
          };
          let ModerateDay = {
            days: data.ModerateDay,
            text: `中度${this.emoName}倾向`,
            color: "#ff8a00",
            lastDay: data.LastModerateDay,
            scale: data.ModerateDayRatio,
          };
          let SevereDay = {
            days: data.SevereDay,
            text: `重度${this.emoName}倾向`,
            color: "#d70d0d",
            lastDay: data.LastSevereDay,
            scale: data.SevereDayRatio,
          };
          this.emotionList.push(NoneDay);
          this.emotionList.push(MildDay);
          this.emotionList.push(ModerateDay);
          this.emotionList.push(SevereDay);
          // 图表数据
          this.emotionData = chartData.map(item => {
            return {
              value: item.Value,
              itemStyle: {
                color: this.calcResultColor(item.Level),
              },
            };
          });
          this.weekAndMonData = chartData.map((item, index) => {
            return {
              value: [index, item.MinValue, item.MaxValue],
            };
          });
          this.xAxisData = chartData.map((item) => {
            return item.Key
              ? this.$dayjs(item.Key.replace(/-/g, "/")).format("MM/DD")
              : item.Key;
          });
          let emphasisStyle = {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: "rgba(0,0,0,0.3)",
            },
          };
          let that = this;
          // 7天和30天变成柱状图
          this.weekAndMonthSeries = [
            {
              name: "平均值",
              type: "scatter",
              symbolSize: 8,
              data: this.emotionData,
            },
            {
              name: "",
              type: "custom",
              data: this.weekAndMonData,
              renderItem: function (params, api) {
                var categoryIndex = api.value(0);
                var end = api.coord([categoryIndex, api.value(1)]);
                var start = api.coord([categoryIndex, api.value(2)]);
                var width = 8;
                var rectShape = that.$echarts.graphic.clipRectByRect(
                  {
                    x: start[0] - width / 2,
                    y: start[1],
                    width: 8,
                    height: end[1] - start[1],
                  },
                  {
                    x: params.coordSys.x,
                    y: params.coordSys.y,
                    width: params.coordSys.width,
                    height: params.coordSys.height,
                  }
                );
                if (rectShape) {
                  rectShape.r = [10];
                }
                return (
                  rectShape && {
                    type: "rect",
                    shape: rectShape,
                    style: api.style(),
                  }
                );
              },
              itemStyle: {
                opacity: 0.8,
              },
              encode: {
                y: [1, 2],
                x: 0,
              },
            },
            {
              name: `轻度${this.emoName}倾向`,
              type: "scatter",
              symbolSize: 8,
              data: "",
            },
            {
              name: `中度${this.emoName}倾向`,
              type: "scatter",
              symbolSize: 8,
              data: "",
            },
            {
              name: `重度${this.emoName}倾向`,
              type: "scatter",
              symbolSize: 8,
              data: "",
            },
            {
              name: `无${this.emoName}倾向`,
              type: "scatter",
              symbolSize: 8,
              data: "",
            },
          ];
          // 点击提示此时为空
          this.defaultOptions.tooltip = {
            trigger: "axis",
            formatter: function (params) {
              if (params) {
                return (
                  params[0].marker +
                  "平均值:" +
                  params[0].name +
                  "--" +
                  params[0].value +
                  "</br>" +
                  params[1].marker +
                  "最大值:" +
                  params[1].name +
                  "--" +
                  params[1].value[2] +
                  "</br>" +
                  params[1].marker +
                  "最小值:" +
                  params[1].name +
                  "--" +
                  params[1].value[1]
                );
              }
            },
          };
          this.defaultOptions.series = this.weekAndMonthSeries;
          this.$toast.success("数据加载完成");
        });
    },
    calcTitle(type) {
      let title = "";
      switch (type) {
        case 1:
          title = "压力";
          break;
        case 2:
          title = anxietyText;
          break;
        case 3:
          title = "疲劳";
          break;
        default:
          break;
      }
      return title;
    },
  },
};
</script>

<style lang="scss">
.van-nav-bar .van-icon {
  padding-left: 10px;
}

.calenddar-dialog {
  overflow: scroll;
}

.calendar {
  overflow: scroll;

  .van-calendar {
    height: 350px;

    .van-calendar__header {
      display: none;
    }

    .van-calendar__days .van-calendar__day {
      width: 27px;
      height: 27px;
      margin: 5px;
      font-size: 12px;

      &.custom-calendar {
        width: 27px;
        height: 27px;
      }

      &.highlight-border {
        border: 1px solid #62bd48;
        width: 27px;
        height: 27px;
        border-radius: 50%;

        &.none {
          border: 1px solid #62bd48;
        }

        &.mild {
          border: 1px solid #ffde00;
        }

        &.moderate {
          border: 1px solid #ff8a00;
        }

        &.severe {
          border: 1px solid #d70d0d;
        }
      }
    }

    .van-calendar__selected-day {
      width: 27px;
      height: 27px;
      border-radius: 50%;
      font-size: 12px;
    }
  }
}
</style>
<style scoped lang="scss">
@import "./../index.scss";
@import "./index.scss";
</style>