<template>
  <div class="psychological-container">
    <NavBar title="心理监测" @on-click-left="onNavBack" right-text="历史" @on-click-right="onHistory"> </NavBar>
    <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">
          <p>监测次数：{{ monitoringCount || '0' }}次</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>
            </div>
          </div>
        </div>

        <!-- 统计 -->

        <div class="statistics">
          <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>
      <!-- 分割线 -->
      <!-- 情绪切换 -->
      <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="line"></div>
      <!-- 底部 -->
      <div class="bottom">
        <div class="echart-container">
          <div class="echart">
            <EchartBox
              echartId="charts"
              :outTitle="emoLegend.outTitle"
              height="200"
              width="200"
              :legend="emoLegend"
              :options="defaultOptions"
            ></EchartBox>
          </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="noDataImg" 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 }">{{ 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>
    <!-- 周报菜单 -->
    <div class="main report" v-show="current == 3">
      <div class="content">
        <div class="list" v-if="weekList.length > 0">
          <div class="item" v-for="(item, index) in weekList" :key="index" @click="onClickItem(item.recordId)">
            <div class="left">
              <img :src="weekImg" alt />
              <div class="middle">
                <div class="title">
                  <span>周报</span>
                  <p>{{ item.name }}</p>
                </div>
                <div class="overall">
                  <div class="left">
                    <span>总评</span>
                    <p :style="{ color: calcResultColor(item.summaryLevel) }">{{ item.summary }}</p>
                  </div>
                </div>
                <!-- <div class="trend">
                                    <p>( <span>无抑郁倾向</span><span>5%</span>，<span>轻度抑郁倾向</span> <span>5%</span> )</p>
                                </div>-->
              </div>
            </div>

            <div class="right">
              <img :src="moreImg" alt />
            </div>
          </div>
        </div>
        <div class="list no-data" v-else>
          <img :src="noDataImg" alt />
          <p>连续佩戴两周产生对比数据</p>
        </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 { EmotionModel, PsyBaseUrl } from '@/config/models';
import EchartBox from '@/components/EchartBox';
import NavBar from '@/components/NavBar';
import axios from 'axios';
import ToastService from '@/services/toast-service';
export default {
  name: 'psychological-monitor',
  components: {
    NavBar,
    EchartBox
  },
  data() {
    return {
      // 日期选择标签
      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: '抑郁', 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: []
    };
  },
  computed: {
    emoLegend() {
      return {
        title: '',
        outTitle: `${this.emoName}数据图`,
        list: [
          { name: `无${this.emoName}倾向`, color: '#179b3b' },
          { name: `轻度${this.emoName}倾向`, color: '#8dc21f' },
          { name: `中度${this.emoName}倾向`, color: '#2ea7e0' },
          { 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: '3%',
          left: '1%',
          right: '3%',
          bottom: '15%',
          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: 20,
            bottom: 4,
            handleStyle: {
              borderWidth: 1,
              borderCap: 'square'
            }
          }
        ],
        tooltip: {
          trigger: 'axis',
          textStyle: {
            fontSize: 14,
            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: 5,
            smooth: true,
            data: this.emotionData,
            symbol: 'circle',
            symbolSize: 10,
            itemStyle: {
              color: '#fff',
              borderWidth: 2
            },
            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: 14
          },
          position: 'right'
        },
        legend: {
          top: '5%',
          left: 'center',
          show: false
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '90%'],
            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
          }
        ]
      };
    },
    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 EmotionModel[this.params.name].title1;
    },
    article1() {
      return EmotionModel[this.params.name].article1;
    },
    title2() {
      return EmotionModel[this.params.name].title2;
    },
    article2() {
      return EmotionModel[this.params.name].article2;
    },
    // 当前情绪颜色
    currentColor() {
      return this.calcResultColor(this.resultLevel) || '#179b3b';
    }
  },
  watch: {
    // 监听数据发生变化 初始化各项图表
    emotionData: {
      handler() {
        this.initEchart();
      },
      deep: true
    },
    xAxisData: {
      handler() {
        this.initEchart();
      },
      deep: true
    },
    pieData: {
      handler() {
        this.initPieEchart();
      },
      deep: true
    }
  },
  created() {
    // 读取路由传过来的参数，根据路由传过来的参数判断是哪种情绪
    this.loadParams();
    this.initEchartText();
    this.getCalendarData();
    this.getPsychologiclData();
    this.createList();
    //this.getWeekResult();
  },
  mounted() {
    this.initEchart();
    /* 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); */
  },
  methods: {
    createList() {
      // 模拟数据
      this.emotionDataNew = [];
      const colors = ['#189b3b', '#2ea7e0', '#ff5f8b'];
      for (let i = 0; i < 7; i++) {
        let value = Math.floor(Math.random() * 60) + 80;
        let color = colors[Math.floor(Math.random() * colors.length)];
        this.emotionDataNew.push({
          value,
          itemStyle: {
            borderColor: color
          }
        });
      }
    },
    loadParams() {
      let params = this.$route.query;
      if (params) {
        this.emoName = 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.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());
        }
      }
    },
    // 计算点击的天数
    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.params.name;
            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) {
      ToastService.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: '#179b3b'
            };
            let Mild = {
              count: data.Mild,
              percentage: this.calcPercentage(data.Mild, data.Count),
              text: `轻度${this.emoName}倾向`,
              color: '#8dc21f'
            };
            let Moderate = {
              count: data.Moderate,
              percentage: this.calcPercentage(data.Moderate, data.Count),
              text: `中度${this.emoName}倾向`,
              color: '#2ea7e0'
            };
            let Severe = {
              count: data.Severe,
              percentage: this.calcPercentage(data.Severe, data.Count),
              text: `重度${this.emoName}倾向`,
              color: '#ff5f8b'
            };
            // 饼状图右边数据
            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')
                : '',
              bgColor: '#ff5f8b'
            };
            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')
                : '',
              bgColor: '#189b3b'
            };
            /* 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')
                : ''
            }; */
            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')
                : '',
              bgColor: '#2ea7e0'
            };
            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: '#179b3b'
            };
            let MildDay = {
              days: data.MildDay,
              text: `轻度${this.emoName}倾向`,
              color: '#8dc21f'
            };
            let ModerateDay = {
              days: data.ModerateDay,
              text: `中度${this.emoName}倾向`,
              color: '#2ea7e0'
            };
            let SevereDay = {
              days: data.SevereDay,
              text: `重度${this.emoName}倾向`,
              color: '#ff5f8b'
            };
            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: {
                  borderColor: 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 that = this;
              // 7天和30天变成柱状图
              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);
                    let end = api.coord([categoryIndex, api.value(1)]);
                    let start = api.coord([categoryIndex, api.value(2)]);
                    let width = 16;
                    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 = [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: 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: ''
                }
              ];
              // 点击提示此时为空
              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;
            ToastService.success({
              message: '数据加载完成'
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 计算百分比
    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() {
      this.result = `无${this.emoName}倾向`;
      this.defaultSeries = [
        {
          name: ``,
          type: 'line',
          padding: 5,
          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;
      });
    },
    // 初始化饼状图
    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);
    },
    // 格式化日期显示参数
    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;
    },
    //   返回
    onNavBack() {
      this.$router.push({
        name: 'Today'
      });
    },
    // 点击日期选择
    onTabClick(value, index) {
      this.current = index;
      this.currentDays = value;
      this.$store.commit('tabClick', index);
      let currentDate = new Date();
      this.surveyTitle = value === 7 ? '7天概览' : '30天概览';
      if (value === 7) {
        let dateList = this.getPostDate(currentDate, 6, true);
        this.getPsychologiclData('', dateList[0] /* '2023-11-15' */ /* dateList[1] */ /* '2023-11-21' */);
        this.startDate = dateList[0] /* '2023-11-15' */;
        this.endDate = dateList[1] /* '2023-11-21' */;
      } 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') /* '2023-11-21' */
        );
        this.startDate = this.$dayjs(currentDate).format('YYYY-MM-DD') /* '2023-11-21' */;
        this.endDate = this.$dayjs(currentDate).format('YYYY-MM-DD') /* '2023-11-21' */;
      } 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] /* '2023-11-21' */, dateList[1] /* '2023-12-21' */);
        this.startDate = dateList[0] /* '2023-11-21' */;
        this.endDate = dateList[1] /* '2023-12-21' */;
      } else {
        // 周报菜单
        this.getWeekResult();
      }
    },
    // 点击情绪tab
    onPsyTabClick(name, index) {
      this.psyCurrent = index;
      this.emoName = EmotionModel[name].name;
      this.currentEmoName = name;
      this.emoType = EmotionModel[name].type;
      console.log('this.currentDays', this.currentDays);
      if (this.currentDays === 49) {
        // 即点击了周报,此时调用获取周报接口
        this.getWeekResult();
      } else {
        this.getPsychologiclData(this.startDate, this.endDate);
      }
    },
    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.echarts != null && this.echarts != '' && this.echarts != undefined) {
        this.echarts.dispose();
      }
      this.echarts = this.$echarts.init(this.$refs.charts);
      this.echarts.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.getPsychologiclData(selectDate);
    },
    // 计算字体显示的颜色
    calcColor(value) {
      let color = '';
      if (value <= 40) {
        color = '#179b3b';
      } else if (value > 40 && value <= 65) {
        color = '#8dc21f';
      } else if (value > 65 && value <= 80) {
        color = '#2ea7e0';
      } else if (value > 80) {
        color = '#ff5f8b';
      } else {
        color = '';
      }
      return color;
    },
    // 计算结果采用哪种颜色
    calcResultColor(value, isCallBackClass) {
      let color = '';
      let className = '';
      switch (Number(value)) {
        case 0:
          color = '#179b3b';
          className = 'none';
          break;
        case 1:
          color = '#8dc21f';
          className = 'mild';
          break;
        case 2:
          color = '#2ea7e0';
          className = 'moderate';
          break;
        case 3:
          color = '#ff5f8b';
          className = 'severe';
          break;
      }
      return isCallBackClass ? className : color;
    },
    // 点击帮助
    onHelp() {
      this.isPopup = true;
    },
    // 关闭poup
    onClose() {
      this.isPopup = false;
    },
    getWeekResult() {
      ToastService.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
      };
      axios
        .get(reqUrl, {
          params: { ...reqParams }
          /*  headers: { 'AccessToken': this.$store.getters.ssjlToken } */
        })
        .then(res => {
          console.log('res', res);
          const data = res.data.response;
          this.weekList = data
            .map(item => {
              return {
                name: item.Name.replace('周报', '').replace(/-/g, '.').replace(/~/g, '-'),
                recordId: item.RecordId,
                summary: item.Summary,
                summaryLevel: item.SummaryLevel,
                type: this.emoType
              };
            })
            .reverse();
          ToastService.success('数据加载完成');
        });
    },
    onClickItem(recordId) {
      this.$router.push({
        name: 'report',
        query: {
          recordId: recordId,
          name: this.currentEmoName,
          isShowLeft: true,
          uid: this.uid
        }
      });
    }
  }
};
</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 #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>
