<template>
  <div class="psychological-container">
    <van-nav-bar title="体征监测" @click-left="onNavBack" right-text="历史" @click-right="onHistory" left-text="返回"
      left-arrow>
    </van-nav-bar>
    <div class="tab-bar">
      <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="tab-bar">
          <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="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="#179b3b" :show-confirm="false" :show-title="false"
                :show-subtitle="false" :formatter="formatter" @select="onSelect" />
            </div>
          </template>
        </van-dialog>

        <!-- 监测次数 -->
        <div class="monitoring-count" v-show="current === 0">
          <p>{{ currentDesc || '--' }}</p>
        </div>

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

        <div class="pie-chart-con" v-show="current !== 0">
          <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 + unit : `0${unit}` }}</span>
                  <label :style="{ color: item.color }">{{ '(' + item.percentage + ')' }}</label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 非7天30天显示 -->
        <div class="circle-con" v-show="current === 0">
          <div class="out-circle">
            <van-circle v-model="currentCircle" layer-color="#f1f0ff" :rate="circleRate" :speed="100" clockwise
              :color="calcColorByTypeAndValue(this.healthyType, this.resultLevel, 2)" stroke-linecap="butt"
              stroke-width="120">
              <template #default>
                <div class="circle-text">
                  <p class="left">{{ todayValue || '--' }}</p>
                  <p class="right">{{ signUnit }}</p>
                </div>
              </template>
            </van-circle>

            <div class="circle-white" :style="{
      borderColor: calcColorByTypeAndValue(this.healthyType, this.resultLevel, 2)
    }"></div>
          </div>
          <div class="progress">
            <div class="progress-circle" :style="{
      borderColor: calcColorByTypeAndValue(this.healthyType, this.resultLevel, 2),
      left: this.progressCircle
    }" v-show="todayValue != ''"></div>
            <div class="state-item" v-for="(item, index) in statesList" :key="index">
              <div :class="['state-line', item.state]" :style="{ backgroundColor: item.color }"></div>
              <div class="state-text">
                <span :style="{ color: item.color }"> {{ item.text }} </span>
              </div>
            </div>
          </div>
        </div>
        <!-- 统计 -->

        <div class="statistics" v-show="psyCurrent !== 2">
          <div class="list">
            <div class="item" v-for="(item, index) in statisticsList" :key="index"
              :style="{ backgroundColor: item.bgColor }">
              <div class="top">
                <span>{{ item.label || '--' }}</span>
              </div>

              <div class="middle">
                <span>{{ item.value || '--' }}</span>
              </div>

              <div class="bottom">
                <span>{{ item.time || '--' }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="tip">
          <img class="img" src="@/assets/today/icons/2_25.png" />
          <p>
            <span>温馨提示：</span>检测数据仅供参考，<span>不可做医疗诊断和治疗依据</span>，在运动、工作等场景会影响健康检测。
          </p>
        </div>
      </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, index)" v-for="(item, index) in psyList" :key="index">
              <span>{{ item.text }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- <div class="line"></div> -->
      <!-- 底部 -->
      <div class="bottom">
        <div class="echart-container">
          <div class="echart">
            <EchartBox echartId="charts" :outTitle="emoLegend.outTitle" rightRowType="in-line-block" height="200"
              width="200" :legend="emoLegend" :options="defaultOptions"></EchartBox>
          </div>
        </div>

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

        <div class="result" v-show="false">
          <div class="result-con">
            <div class="title">
              <span class="title-no-data">结果解读</span>
              <div class="no-data">
                <img :src="noDataImg" alt />
                <p>暂无数据</p>
              </div>
            </div>
          </div>
        </div>

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

              <p class="title-emo" :style="{ color: currentColor }">
                {{ result }}
              </p>

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

            <!--  <div class="friendly-reminder" v-if="emoType === 2">
              <p :style="{ color: currentColor }">友情提示：</p>
              <span
                >如果您发现抑郁倾向分值升高或处于轻度水平，不需要过度紧张，这可能是由正常的情绪波动或者生活习惯（睡眠时间、运动量等）的改变造成的。如果您发现抑郁倾向分值连续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"
                  :style="{ backgroundColor: item.color }">
                  <p>
                    <span 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="noDataImg" alt />
                  <p>暂无数据</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>
            抑郁症是一抑郁种心理疾病，严重时可发展为精神障碍。然而当我们体会到了痛苦、悲伤、和郁闷等负面情绪，并不意味着我们就是抑郁症。日常的短时的喜、怒、哀、乐，都是正常的情绪变化，然而长期的低落情绪、兴趣缺失等可能会让我们有抑郁的风险。
          </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 { Signsmodel } from '@/config/models';
import EchartBox from '@/components/EchartBox';
import ToastService from '@/services/toast-service';
/* import DialogService from "../../services/dialog-service"; */
import APIHealthUser from '@/api/health-user';
/* import { isNull } from "@/services/utils-service"; */
export default {
  name: 'psychological-monitor',
  components: {
    EchartBox
  },
  data() {
    return {
      currentCircle: 0, //外圈圆的进度值
      // 日期选择标签
      dateList: [
        { name: 'today', text: '今天', value: 0 },
        { name: 'week', text: '7天', value: 1 },
        { name: 'month', text: '30天', value: 2 }
        /* { name: 'weekReport', text: '周报', value: 49 } */
      ],
      // 情绪tab
      psyList: [
        { name: 'temperature', text: '体温', value: 1 },
        { name: 'heartrate', text: '心率', value: 0 },
        { name: 'step', text: '步数', 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: "#179b3b"
                    },
                    {
                        text: "轻度情绪倾向",
                        count: 2,
                        percentage: "80",
                        color: "#8dc21f"
                    },
                    {
                        text: "中度情绪倾向",
                        count: 1,
                        percentage: "80",
                        color: "#2ea7e0"
                    },
                    {
                        text: "重度情绪倾向",
                        count: 1,
                        percentage: "80",
                        color: "#ff5f8b"
                    } */
      ],
      // 情绪状态列表
      statisticsList: [
        /*  { label: "最大值", value: "75", time: "08:15" },
                    { label: "最小值", value: "40", time: "10:15" },
                    { label: "最近值", value: "50", time: "18:15" } */
      ],
      // 周报-情绪计算
      emotionList: [
        /*  { days: "5", text: "无情绪倾向", color: "#179b3b" },
                    { days: "4", text: "轻度情绪倾向", color: "#8dc21f" },
                    { days: "3", text: "中度情绪倾向", color: "#2ea7e0" },
                    { 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: '#8dc21f',
      // 中度级别颜色
      severeColor: '#2ea7e0',
      // 重度级别颜色
      moderateColor: '#ff5f8b',
      // 7天和30天最大数据列表
      weekAndMonData: [],
      tabImgUrl: require('@/assets/today/icons/statistical_form.png'),
      selectDownImg: require('@/assets/today/icons/select_down.png'),
      weekImg: require('@/assets/today/icons/week_report.png'),
      moreImg: require('@/assets/today/icons/more.png'),
      noDataImg: require('@/assets/today/images/no_data_01.png'),
      weekList: [],
      //接口需要的开始时间
      startDate: '',
      //接口需要的结束时间
      endDate: '',
      //当前情绪名称
      currentEmoName: '',
      emotionDataNew: [],
      todayValue: '',
      currentDesc: '',
      healthyType: 0
    };
  },
  computed: {
    unit() {
      return this.healthyType === 2 ? '天' : '次';
    },
    circleRate() {
      if (this.healthyType == 0) {
        // 心率
        return this.calcPercentage(Number(this.todayValue), 180);
      } else if (this.healthyType == 1) {
        // 体温
        return this.calcPercentage(Number(this.todayValue), 43);
      } else if (this.healthyType == 2) {
        // 步数
        return this.calcPercentage(Number(this.todayValue), 20000);
      } else {
        return 40;
      }
    },
    progressCircle() {
      return this.calcColorByTypeAndValue(this.healthyType, this.resultLevel, 1);
    },
    // 状态条
    statesList() {
      return Signsmodel[this.currentEmoName].progressTextList;
    },
    emoLegend() {
      if (this.healthyType === 0) {
        return {
          title: '',
          outTitle: `${this.emoName}数据图`,
          list: [
            { name: `${this.emoName}偏低`, color: '#2ea7e0' },
            { name: `${this.emoName}正常`, color: '#179b3b' },
            { name: `${this.emoName}偏高`, color: '#ff5f8b' }
          ]
        };
      } else if (this.healthyType === 1) {
        return {
          title: '',
          outTitle: `${this.emoName}数据图`,
          list: [
            { name: `${this.emoName}正常`, color: '#179b3b' },
            { name: `${this.emoName}偏高`, color: '#ff5f8b' }
          ]
        };
      } else {
        return {
          title: '',
          outTitle: `${this.emoName}数据图`,
          list: [
            { name: `${this.emoName}偏低`, color: '#2ea7e0' },
            { name: `${this.emoName}正常`, color: '#179b3b' },
            { name: `${this.emoName}偏高`, color: '#ff5f8b' }
          ]
        };
      }
    },
    // 默认折线图配置，echarts 具体配置 见 https://echarts.apache.org/zh/option.html#title
    defaultOptions() {
      return {
        time: {
          useUTC: false
        },
        grid: {
          show: true,
          borderWidth: 0,
          top: '10%',
          left: '5%',
          right: '10%',
          bottom: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          textStyle: {
            fontSize: 10
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: '#ddd',
              width: 4
            }
          },
          nameLocation: 'center',
          axisLabel: {
            show: true,
            fontSize: 12,
            showMinLabel: true, //显示最小值
            showMaxLabel: true, //显示最大值
            marginBottom: 10 // 调整标签与轴线的距离
          },
          data: this.xAxisData
        },
        dataZoom: [
          {
            start: 0,
            end: 100,
            textStyle: {
              color: '#FFF',
              fontSize: 14
            },
            show: true,
            height: 20,
            bottom: 8,
            handleStyle: {
              borderWidth: 4,
              borderCap: 'square'
            }
          }
        ],
        tooltip: {
          trigger: 'axis',
          textStyle: {
            fontSize: 16,
            align: 'center'
          },
          formatter: function (params) {
            return params[0].marker + params[0].name + '</br>' + params[0].value;
          }
        },
        yAxis: {
          type: 'value',
          /*  max: 100,
          min: 0,
          interval: 20, */
          splitNumber: 1,
          boundaryGap: ['5%', '5%'],
          nameTextStyle: {
            fontSize: 13
          },
          alignTicks: false,
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            fontSize: 13
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: '#ddd',
              width: 1
            }
          }
        },
        series: [
          {
            name: `无${this.emoName}倾向`,
            type: 'line',
            padding: 10,
            smooth: true,
            data: this.emotionData,
            symbol: 'circle',
            symbolSize: 10,
            itemStyle: {
              color: '#fff',
              borderWidth: 4
            },
            lineStyle: {
              width: 6,
              type: 'solid',
              color: '#189b3b'
            }
          },
          {
            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: 16
          },
          position: 'right'
        },
        legend: {
          top: '5%',
          left: 'center',
          show: false
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '90%'],
            avoidLabelOverlap: false,
            startAngle: 270, // 设置逆时针渲染
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 4,
              fontSize: 16
            },
            label: {
              show: false,
              position: 'center',
              fontSize: 16
            },
            emphasis: {
              label: {
                show: false,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.pieData
          }
        ]
      };
    },
    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 Signsmodel[this.currentEmoName].title1;
    },
    article1() {
      return Signsmodel[this.currentEmoName].article1;
    },
    title2() {
      return Signsmodel[this.currentEmoName].title2;
    },
    article2() {
      return Signsmodel[this.currentEmoName].article2;
    },
    signUnit() {
      return Signsmodel[this.currentEmoName].unit;
    },
    // 当前情绪颜色
    currentColor() {
      return this.calcResultColor(this.resultLevel) || '#179b3b';
    }
  },
  watch: {
    // 监听数据发生变化 初始化各项图表
    emotionData: {
      handler() {
        this.initEchart();
      },
      deep: true
    },
    xAxisData: {
      handler() {
        this.initEchart();
      },
      deep: true
    },
    pieData: {
      handler() {
        this.$nextTick(() => {
          this.initPieEchart();
        });
      },
      deep: true
    }
  },
  created() {
    // 读取路由传过来的参数，根据路由传过来的参数判断是哪种情绪
    this.loadParams();
    this.initEchartText();
  },
  mounted() {
    this.psyCurrent = this.calcPsyTabindex(Signsmodel[this.params.name].type);
    this.healthyType = Signsmodel[this.params.name].type;
    this.getSignsData();
    this.getCalendar();
  },
  methods: {
    loadParams() {
      let params = this.$route.query;
      if (params) {
        this.emoName = Signsmodel[params.name].name;
        /*  this.emoType = Signsmodel[params.name].type; */
        this.params = params;
        this.currentEmoName = params.name;
        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());
        }
      }
    },
    // 初始化饼状图
    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);
    },
    // 初始化图表的文字内容
    initEchartText() {
      this.defaultSeries = [
        {
          name: ``,
          type: 'line',
          padding: 10,
          data: this.emotionData,
          symbol: 'circle',
          symbolSize: 12, // 拐点圆的大小
          areaStyle: {}
        },
        {
          name: `轻度${this.emoName}倾向`,
          type: 'line',
          padding: 10,
          data: '',
          symbol: 'circle',
          symbolSize: 12 // 拐点圆的大小
        },
        {
          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;
      }); */
    },
    calcPsyTabindex(type) {
      let psyIndex = '';
      switch (type) {
        case 0:
          psyIndex = 1;
          break;
        case 1:
          psyIndex = 0;
          break;
        case 2:
          psyIndex = 2;
          break;
        default:
          break;
      }
      return psyIndex;
    },
    getCalendar() {
      let reqParams = {
        personId: this.$store.getters.personId
      };
      APIHealthUser.getCalendar(reqParams).then(res => {
        console.log('当前健康类型是', this.healthyType);
        console.log('日历数据', res);
        let list = [];
        let data = res.data.data;
        if (this.healthyType === 0) {
          list = data.heartRate;
        } else if (this.healthyType === 1) {
          list = data.temperature;
        } else {
          list = data.steps;
        }
        list = list.map(item => {
          item.date = this.$dayjs(item.date.replace(/-/g, '/')).format('YYYY/MM/DD');
          return item;
        });
        this.highlightDates = [...list];
      });
    },
    getSignsData(date) {
      ToastService.loading({
        message: '数据加载中'
      });
      this.pieRightList = [];
      this.statisticsList = [];
      this.emotionList = [];
      this.emotionData = [];
      this.xAxisData = [];
      let reqBody = {
        dateType: this.currentDays,
        healthyType: this.healthyType,
        startTime: date,
        endTime: date
      };
      APIHealthUser.getHisData(reqBody)
        .then(res => {
          console.log('体征数据', res);
          const data = res.data.data;
          this.todayValue = data.value || '';
          (this.currentDesc = data.valueTime
            ? this.currentDays === 0
              ? this.$dayjs(data.valueTime).format('YYYY-MM-DD HH:mm')
              : this.$dayjs(data.valueTime).format('YYYY-MM-DD HH:mm')
            : ''),
            (this.monitoringCount = data.checkTotal);
          this.resultLevel = data.resultLevel;
          this.result = data.result;
          this.advice = data.advice;

          // 右边饼状图
          let None = {
            count: data.normalTimes,
            percentage: data.normalPercent,
            text: `${this.emoName}正常`,
            color: '#179b3b'
          };
          let Moderate = {
            count: data.lowTimes,
            percentage: data.lowPercent,
            text: `${this.emoName}偏低`,
            color: '#2ea7e0'
          };
          let Severe = {
            count: data.highTimes,
            percentage: data.highPercent,
            text: `${this.emoName}偏高`,
            color: '#ff5f8b'
          };
          if (this.healthyType !== 1) {
            this.pieRightList.push(None);
            this.pieRightList.push(Moderate);
            this.pieRightList.push(Severe);
          } else {
            this.pieRightList.push(None);
            this.pieRightList.push(Severe);
          }

          this.pieData = this.pieRightList.map(item => {
            item.value = item.count;
            item.itemStyle = {
              color: item.color
            };
            return item;
          });
          console.log('this.pieRightList', this.pieRightList);
          // 下方最大最小图
          let Max = {
            label: '最大值',
            value: data.valueMax,
            time: data.valueMaxTime
              ? this.currentDays === 0
                ? this.$dayjs(data.valueMaxTime).format('HH:mm')
                : this.$dayjs(data.valueMaxTime).format('MM/DD HH:mm')
              : '',
            bgColor: /* this.calcBGColor(this.healthyType, data.valueMax) */ this.calcResultColor(data.levelMax)
          };
          let Min = {
            label: '最小值',
            value: data.valueMin,
            time: data.valueMinTime
              ? this.currentDays === 0
                ? this.$dayjs(data.valueMinTime).format('HH:mm')
                : this.$dayjs(data.valueMinTime).format('MM/DD HH:mm')
              : '',
            bgColor: /* this.calcBGColor(this.healthyType, data.valueMin) */ this.calcResultColor(data.levelMin)
          };
          let Avg = {
            label: '平均值',
            value: data.valueAvg || '--',
            time: data.valueAvgTime
              ? this.currentDays === 0
                ? this.$dayjs(data.valueAvgTime).format('HH:mm')
                : this.$dayjs(data.valueAvgTime).format('MM/DD HH:mm')
              : '' || '--',
            bgColor: /* this.calcBGColor(this.healthyType, data.valueAvg) */ this.calcResultColor(data.levelAvg)
          };
          this.statisticsList.push(Max);
          this.statisticsList.push(Min);
          this.statisticsList.push(Avg);
          // 周报月报底部显示数据
          let NoneDay = {
            days: data.normalDays,
            text: `${this.emoName}正常`,
            color: '#179b3b'
          };
          let ModerateDay = {
            days: data.lowDays,
            text: `${this.emoName}偏低`,
            color: '#2ea7e0'
          };
          let SevereDay = {
            days: data.highDays,
            text: `${this.emoName}偏高`,
            color: '#ff5f8b'
          };
          // 体温不显示偏低
          if (this.healthyType !== 1) {
            this.emotionList.push(NoneDay);
            this.emotionList.push(ModerateDay);
            this.emotionList.push(SevereDay);
          } else {
            this.emotionList.push(NoneDay);
            this.emotionList.push(SevereDay);
          }

          if (!data.chartDatas) {
            return;
          }
          // 中间折线图
          this.emotionData = data.chartDatas
            ? data.chartDatas.map(item => {
              return {
                value: item.value || '--',
                itemStyle: {
                  color: this.currentDays !== 0 && this.healthyType !== 2 ? this.calcResultColor(item.level) : '#fff',
                  borderColor: this.calcResultColor(item.level),
                  borderWidth: 3
                }
              };
            })
            : [];
          // 7天 和 30天柱形图显示
          this.weekAndMonData = data.chartDatas
            ? data.chartDatas.map((item, index) => {
              return {
                value: [index, item.valueMin || '--', item.valueMax || '--']
              };
            })
            : [];
          console.log('this.weekAndMonData', this.weekAndMonData);
          if (this.currentDays === 0) {
            // 显示今天数据
            this.xAxisData = data.chartDatas.map(item => {
              return this.$dayjs(item.key.replace(/-/g, '/')).format('HH:mm');
            });
            if (this.healthyType === 1) {
              this.defaultOptions.yAxis.max = 43;
              this.defaultOptions.yAxis.min = 34.5;
              this.defaultOptions.yAxis.interval = 2;
              // 体温的折线图
              this.defaultOptions.series[0].markLine = {
                data: [
                  {
                    type: 'average',
                    name: '体温',
                    yAxis: 37.2,
                    label: {
                      fontSize: 14,
                      position: 'end'
                    },
                    lineStyle: {
                      type: 'dashed',
                      width: 5,
                      color: 'red'
                    }
                  }
                ]
              };
            } else if (this.healthyType === 2) {
              this.defaultOptions.yAxis.min = 0;
            }
          } else if (this.currentDays !== 0 && this.healthyType === 2) {
            // 折线图显示，因为步数没有最大最小步数
            this.xAxisData = data.chartDatas.map(item => {
              return this.$dayjs(item.key.replace(/-/g, '/')).format('MM/DD');
            });
            if (this.healthyType === 2) {
              this.defaultOptions.yAxis.min = 0;
            }
          } else {
            console.log('周月');
            this.xAxisData = data.chartDatas.map(item => {
              return this.$dayjs(item.key.replace(/-/g, '/')).format('MM/DD');
            });
            let that = this;
            this.weekAndMonthSeries = [
              {
                name: '平均值',
                type: 'scatter',
                symbolSize: 14,
                data: this.emotionData
              },
              {
                name: '',
                type: 'custom',
                data: this.weekAndMonData,
                renderItem: function (params, api) {
                  let categoryIndex = api.value(0);
                  console.log('categoryIndex', categoryIndex);
                  let end = api.coord([categoryIndex, api.value(1)]);
                  let start = api.coord([categoryIndex, api.value(2)]);
                  let width = 16;
                  console.log('end', end, 'start', start);
                  let rectShape = that.$echarts.graphic.clipRectByRect(
                    {
                      x: start[0] - width / 2,
                      y: start[1],
                      width: 16,
                      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 = [20];
                  }
                  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: 12,
                data: ''
              },
              {
                name: `中度${this.emoName}倾向`,
                type: 'scatter',
                symbolSize: 12,
                data: ''
              },
              {
                name: `重度${this.emoName}倾向`,
                type: 'scatter',
                symbolSize: 12,
                data: ''
              },
              {
                name: `无${this.emoName}倾向`,
                type: 'scatter',
                symbolSize: 12,
                data: ''
              }
            ];
            if (this.healthyType === 1) {
              this.defaultOptions.yAxis.max = 43;
              this.defaultOptions.yAxis.min = 34.5;
              this.defaultOptions.yAxis.interval = 2;
              /* this.weekAndMonthSeries[0].markLine = {
              data: [
                {
                  type: "average",
                  name: "体温",
                  yAxis: 37.2,
                  label: {
                    fontSize: 28,
                    position: "end",
                  },
                  lineStyle: {
                    type: "dashed",
                    width: 5,
                    color: "red",
                  },
                },
              ],
            }; */
            } else if (this.healthyType === 2) {
              this.defaultOptions.yAxis.min = 0;
            }
            // 点击提示此时为空
            this.defaultOptions.tooltip = {
              trigger: 'axis',
              textStyle: {
                fontSize: 16
              },
              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;
          }
        })
        .finally(() => {
          ToastService.success({
            message: '数据加载完成'
          });
        });
    },
    onNavBack() {
      this.$router.push({
        name: 'Today'
      });
    },
    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.dateType = 0;
      this.current = 0;
      this.currentDays = 0;
      this.getSignsData(selectDate);
    },
    onClose() { },
    // 点击日期选择
    onTabClick(value, index) {
      this.current = index;
      this.currentDays = value;
      this.surveyTitle = value > 0 ? (value === 1 ? '7天概览' : '30天概览') : '';
      /*  this.defaultOptions.series = this.defaultSeries;
      this.defaultOptions.series[0].data = this.emotionData;
       */
      if (this.selectDate && this.current === 0) {
        this.getSignsData(this.selectDate);
      } else {
        this.getSignsData();
      }
    },
    onPsyTabClick(item) {
      this.healthyType = item.value;
      this.psyCurrent = this.calcPsyTabindex(Signsmodel[item.name].type);
      this.emoName = Signsmodel[item.name].name;
      this.currentEmoName = item.name;
      console.log('selectDate', this.selectDate);
      if (this.selectDate && this.current === 0) {
        this.dateType = 0;
        this.getSignsData(this.selectDate);
      } else {
        this.getSignsData();
      }
      this.getCalendar();
    },
    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);
    },
    // 根据类型，和数值计算使用什么颜色
    calcColorByTypeAndValue(type, value, callBack) {
      let offset = '';
      let color = '';
      const intValue = Number(value);
      switch (intValue) {
        case 0:
          offset = '15%';
          color = '#2ea7e0';
          break;
        case 1:
          offset = type === 1 ? '22%' : '45%';
          color = '#189b3b';
          break;
        case 2:
          color = '#ff5f8b';
          offset = type === 1 ? '70%' : '75%';
          break;
        case 3:
          color = '#ff5f8b';
          offset = type === 1 ? '70%' : '75%';
          break;
        default:
          color = '#f1f0ff';
          offset = '0%';
          break;
      }

      if (callBack == 1) {
        return offset;
      } else {
        return color;
      }
    },
    // 计算背景颜色
    calcBGColor(type, value) {
      let color = '';
      const intValue = Number(value);
      if (type == 0) {
        // 心率
        if (intValue > 120) {
          color = '#ff5f8b';
        } else if (intValue < 40) {
          color = '#2ea7e0';
        } else {
          color = '#189b3b';
        }
      } else if (type == 1) {
        // 体温
        if (intValue >= 37.3) {
          color = '#ff5f8b';
        } else if (intValue <= 34) {
          color = '#2ea7e0';
        } else {
          color = '#189b3b';
        }
      } else {
        // 步数 2
        if (intValue >= 5000) {
          color = '#ff5f8b';
        } else if (intValue <= 3000) {
          color = '#2ea7e0';
        } else {
          color = '#189b3b';
        }
      }
      return color;
    },
    calcResultColor(value, isCallBackClass) {
      let color = '';
      let className = '';
      switch (Number(value)) {
        case 0:
          color = '#2ea7e0';
          className = 'moderate';
          break;
        case 1:
          color = '#179b3b';
          className = 'none';
          break;
        case 2:
          color = '#ff5f8b';
          className = 'severe';
          break;
        case 3:
          color = '#ff5f8b';
          className = 'severe';
          break;
        default:
          color = '#179b3b';
          className = 'none';
          break;
      }
      return isCallBackClass ? className : color;
    },
    initEchart() {
      /*  if (this.echarts != null && this.echarts != '' && this.echarts != undefined) {
          this.echarts.dispose();
        }
        this.echarts = this.$echarts.init(this.$refs.charts);
        this.echarts.setOption(this.defaultOptions); */
    },
    // 格式化日历日期显示参数
    formatter(day) {
      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;
    }
  }
};
</script>

<style lang="scss">
.calendar {
  height: 800px;

  .van-calendar {
    height: 400px;
    overflow: scroll;

    .van-calendar__header {
      display: none;
    }

    .van-calendar__days {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
    }

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

      &.custom-calendar {
        width: 27px;
        height: 27px;
        margin-left: 0 !important;
      }

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

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

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

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

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

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