<template>
  <!-- 周/月报 -->
  <div class="report">
    <NavBar title="周报" @on-click-left="onNavBack" right-text="历史"> </NavBar>

    <div class="main">
      <div class="periodNav">
        <div
          class="periodItem minPeriodItem"
          :class="{ active: signActive == index }"
          v-for="(item, index) in signList"
          :key="index"
          @click="onSignClick(index)"
        >
          <span>{{ item.name }}</span>
        </div>
      </div>
      <!-- 总评 -->
      <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="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">
                <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"
            :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="line"></div>
      <!-- 24小时 -->
      <!-- <div class="chart-title">
        <p>24小时{{ emoName }}时间分布图</p>
      </div> -->
      <div class="scatter">
        <EchartBox
          echartId="scatterCharts"
          outTitle="24小时抑郁时间分布图"
          :border="false"
          height="200"
          width="200"
          :options="scatterOptions"
        >
          <template #custom-bot>
            <div class="custom-bot">
              <div class="list">
                <div class="item" v-for="(item, index) in timeList" :key="index">
                  <span>{{ item }}</span>
                </div>
              </div>
            </div>
          </template>
        </EchartBox>
      </div>

      <div class="chart-title">
        <p>{{ echartsTitle }}</p>
      </div>
      <!-- 数据图-柱形图 -->
      <div class="bar-chart">
        <div class="echart">
          <EchartBox echartId="charts" height="200" width="200" :legend="emoLegend" :options="emoOptions"></EchartBox>
        </div>
      </div>
      <div class="line"></div>
      <!-- 建议 -->
      <div class="advice">
        <div class="content">
          <p class="title">健康建议</p>
          <!-- <p>{{ weekResult.Advice || '--' }}</p> -->
          <p>
            健康建议抑郁是一种负性情绪，是人们遇到具体生活事件后，出现
            的一种不愉快、烦闷压抑的内心体验。情绪受挫折的影响是很正常
            的反应，不要任由情绪跟着负面想法走，让自己陷入抑郁之中。与
            人沟通，有助于排解不良情绪；把注意力放到当下真正需要关注的 事情中来，积极应对困难，有助于改善现状。
          </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"
                :style="{ backgroundColor: item.color }"
              >
                <p>
                  <span class="day">{{ item.days }}</span>
                  <span class="day-text">天</span>
                  <img :src="calcWeekImg(item.days, item.lastDay)" alt="" />
                  <span class="day-text status">{{ calcWeekImg(item.days, item.lastDay, true) }}</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 class="main no-data">
      <img src="../../assets/today/images/no_data_01.png" alt />
      <p>暂无数据</p>
    </div>
  </div>
</template>

<script>
import { isNotNull } from '@/services/utils-service';
import axios from 'axios';
import APICore from '@/api/core';
import NavBar from '@/components/NavBar';
import EchartBox from '@/components/EchartBox';
export default {
  name: '',
  components: {
    NavBar,
    EchartBox
  },
  data() {
    return {
      signActive: 0,
      emoLegend: {
        title: '',
        list: [
          { name: '无抑郁倾向', color: '#179b3b' },
          { name: '轻度抑郁倾向', color: '#8dc21f' },
          { name: '中度抑郁倾向', color: '#2ea7e0' },
          { name: '重度抑郁倾向', color: '#ff5f8b' }
        ]
      },
      signList: [
        {
          grid: 'heartRateList',
          name: '疲劳'
        },
        {
          grid: 'temperatureList',
          name: '压力'
        },
        {
          grid: 'stepList',
          name: '焦虑'
        }
      ],
      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', bgColor: '#ff5f8b' },
        { label: '最小值', value: '40', time: '10:15', bgColor: '#189b3b' },
        { label: '最近值', value: '50', time: '18:15', bgColor: '#2ea7e0' } */
      ],
      emotionList: [],
      surveyTitle: '本周概况',
      echarts: null,
      // 路由传过来的情绪参数
      emoName: '',
      pieData: [],
      xAxisData: [],
      pieEcharts: null,
      monitoringCount: '',
      // 7天和30天最大数据列表
      weekAndMonData: [],
      defaultSeries: null,
      defaultLegend: [
        {
          name: `轻度${this.emoName}倾向`,
          icon: 'rect',
          itemStyle: {
            color: '#8dc21f'
          },
          textStyle: {
            fontSize: 12
          }
        },
        {
          name: `中度${this.emoName}倾向`,
          itemStyle: {
            color: '#2ea7e0'
          },
          icon: 'rect',
          textStyle: {
            fontSize: 12
          }
        },
        {
          name: `重度${this.emoName}倾向`,
          itemStyle: {
            color: '#ff5f8b'
          },
          icon: 'rect',
          textStyle: {
            fontSize: 12
          }
        },
        {
          name: `无${this.emoName}倾向`,
          icon: 'rect',
          itemStyle: {
            color: '#179b3b'
          },
          textStyle: {
            // 项目遗留问题，新项目不需重新转换文字大小
            fontSize: 12
          }
        }
      ],
      params: {},
      weekResult: {},
      upImg: require('@/assets/today/icons/up.png'),
      downImg: require('@/assets/today/icons/down.png'),
      signGrid: [],
      chartsScatter: null,
      timeList: ['0', '6', '12', '18', '24'],
      emotionDataNew: []
    };
  },
  created() {
    this.initEchartText();
    this.createList();
  },
  mounted() {
    this.loadParams();
    this.initEchart();
  },
  watch: {
    // 监听数据发生变化 初始化各项图表
    emotionData: {
      handler() {
        this.initEchart();
      },
      deep: true
    },
    xAxisData: {
      handler() {
        this.initEchart();
      },
      deep: true
    },
    pieData: {
      handler() {
        this.initPieEchart();
      },
      deep: true
    }
  },
  computed: {
    emoOptions() {
      return {
        grid: {
          top: '10%',
          left: '10%',
          right: '10%',
          bottom: '20%'
        },
        xAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          textStyle: {
            fontSize: 10
          },
          axisTick: {
            show: false
          },
          nameLocation: 'left',
          axisLabel: {
            show: true,
            fontSize: 12,
            showMinLabel: true, //显示最小值
            showMaxLabel: true //显示最大值
          },
          data: ['6:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            type: 'line',
            data: this.emotionDataNew,
            symbol: 'circle',
            symbolSize: 12,
            smooth: true,
            itemStyle: {
              normal: {
                color: '#fff',
                borderWidth: 2,
                lineStyle: {
                  width: 6,
                  type: 'solid',
                  color: '#189b3b'
                }
              }
            }
          }
        ]
      };
    },
    // 折线图标题
    echartsTitle() {
      return `${this.emoName}数据图`;
    },
    defaultOptions() {
      return {
        time: {
          useUTC: false
        },
        title: {
          /* text: this.echartsTitle, */
          left: 1,
          right: 25,
          bottom: 20,
          top: '3%',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        legend: {
          width: '65%',
          orient: 'horizontal',
          right: 'right',
          top: '3%',
          bottom: '1%',
          itemHeight: 12,
          itemWidth: 12,
          itemGap: 10,
          align: 'left',
          selectedMode: false,
          data: [
            {
              name: `轻度${this.emoName}倾向`,
              icon: 'rect',
              itemStyle: {
                color: '#8dc21f'
              },
              textStyle: {
                fontSize: 12
              }
            },
            {
              name: `中度${this.emoName}倾向`,
              itemStyle: {
                color: '#2ea7e0'
              },
              icon: 'rect',
              textStyle: {
                fontSize: 12
              }
            },
            {
              name: `重度${this.emoName}倾向`,
              itemStyle: {
                color: '#ff5f8b'
              },
              icon: 'rect',
              textStyle: {
                fontSize: 12
              }
            },
            {
              name: `无${this.emoName}倾向`,
              icon: 'rect',
              itemStyle: {
                color: '#179b3b'
              },
              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: '5%',
          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: false,
            height: 25,
            bottom: '3%',
            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: ''
          }
        ]
      };
    },
    // 饼状图配置
    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
          }
        ]
      };
    },
    scatterOptions() {
      return {
        backgroundColor: 'rgba(255, 255, 255, 1)',
        grid: {
          top: '1%',
          left: '10%',
          right: '10%',
          bottom: '1%'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            margin: 15
          },
          show: false
        },
        yAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'].reverse(),
          show: true
        },
        series: [
          {
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar',
            stack: 'one',
            barWidth: 20,
            itemStyle: {
              borderWidth: 3,
              borderColor: 'rgba(255, 255, 255, 1)', //同背景色一样
              barBorderRadius: 120
            },

            emphasis: {
              itemStyle: {
                borderColor: 'rgba(255, 255, 255, 1)'
              }
            }
          },
          {
            data: [120, 30, 150, 80, 70, 110, 130],
            type: 'bar',
            stack: 'one', //堆叠
            barWidth: 20,
            itemStyle: {
              borderWidth: 3, //用border设置两个柱形图之间的间距
              borderColor: 'rgba(255, 255, 255, 1)', //同背景色一样
              barBorderRadius: 120
            },
            emphasis: {
              itemStyle: {
                borderColor: 'rgba(255, 255, 255, 1)'
              }
            }
          },
          {
            data: [120, 30, 150, 80, 70, 110, 130],
            type: 'bar',
            stack: 'one', //堆叠
            barWidth: 20,
            itemStyle: {
              borderWidth: 3, //用border设置两个柱形图之间的间距
              borderColor: 'rgba(255, 255, 255, 1)', //同背景色一样
              barBorderRadius: 120
            },
            emphasis: {
              itemStyle: {
                borderColor: 'rgba(255, 255, 255, 1)'
              }
            }
          },
          {
            data: [120, 30, 150, 80, 70, 110, 130],
            type: 'bar',
            stack: 'one', //堆叠
            barWidth: 20,
            itemStyle: {
              borderWidth: 3, //用border设置两个柱形图之间的间距
              borderColor: 'rgba(255, 255, 255, 1)', //同背景色一样
              barBorderRadius: 120
            },
            emphasis: {
              itemStyle: {
                borderColor: 'rgba(255, 255, 255, 1)'
              }
            }
          }
        ]
      };
    }
  },
  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
          }
        });
      }
    },
    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.params = params;
        if (!params.accessToken) {
          let authToken = await this.getAuth();
          this.$store.commit('ssjlToken', authToken);
        } else {
          this.$store.commit('ssjlToken', params.accessToken);
        }
        this.getWeekResultDetail();
      }
    },
    //   获取b端token
    getAuth() {
      let manufactorId = '5bf13062-a41e-4d00-ba14-1101aad12650';
      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('');
          }
        });
      });
    },
    initEchartText() {
      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: ''
        }
      ];
    },
    calcTitle(type) {
      let title = '';
      switch (type) {
        case 1:
          title = '压力';
          break;
        case 2:
          title = '抑郁';
          break;
        case 3:
          title = '疲劳';
          break;
        default:
          break;
      }
      return title;
    },
    getWeekResultDetail() {
      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: /* this.params.recordId */ '1728096156447281486'
      };
      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;
              })
            : [];
          if (data) {
            this.monitoringCount = data.Total;
            this.pieRightList = [];
            this.statisticsList = [];
            this.emotionList = [];
            this.weekResult = data;
            this.emoName = this.calcTitle(data.Type);
          }
          let None = {
            count: data.None,
            percentage: this.calcPercentage(data.None, data.Total),
            text: `无${this.emoName}倾向`,
            color: '#179b3b',
            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: '#8dc21f',
            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: '#2ea7e0',
            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: '#ff5f8b',
            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')
              : '',
            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.Min,
            time: data.MinDesc
              ? this.currentDays === 0
                ? this.$dayjs(data.MinDesc).format('HH:mm')
                : this.$dayjs(data.MinDesc).format('MM/DD HH:mm')
              : '',
            bgColor: '#2ea7e0'
          };
          /* 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')
              : '',
            bgColor: '#2ea7e0'
          }; */
          this.statisticsList.push(Max);
          this.statisticsList.push(Min);
          this.statisticsList.push(Avg);
          let NoneDay = {
            days: data.NoneDay,
            text: `无${this.emoName}倾向`,
            color: '#179b3b',
            lastDay: data.LastNoneDay,
            scale: data.NoneDayRatio
          };
          let MildDay = {
            days: data.MildDay,
            text: `轻度${this.emoName}倾向`,
            color: '#8dc21f',
            lastDay: data.LastMildDay,
            scale: data.MildDayRatio
          };
          let ModerateDay = {
            days: data.ModerateDay,
            text: `中度${this.emoName}倾向`,
            color: '#2ea7e0',
            lastDay: data.LastModerateDay,
            scale: data.ModerateDayRatio
          };
          let SevereDay = {
            days: data.SevereDay,
            text: `重度${this.emoName}倾向`,
            color: '#ff5f8b',
            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 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('数据加载完成');
        });
    },
    initEchart() {
      /* if (this.echarts != null && this.echarts != '' && this.echarts != undefined) {
        this.echarts.dispose();
      } */
      /* if (this.chartsScatter != null && this.chartsScatter != '' && this.chartsScatter != undefined) {
        this.chartsScatter.dispose();
      } */
      /* this.echarts = this.$echarts.init(this.$refs.charts);
      this.echarts.setOption(this.defaultOptions); */
      /*  this.chartsScatter = this.$echarts.init(this.$refs.chartsScatter);
      this.chartsScatter.setOption(this.scatterOptions); */
    },
    // 初始化饼状图
    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);
    },
    onNavBack() {
      this.$router.push({
        name: 'Insight'
      });
    },
    // 计算字体显示的颜色
    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;
    },
    // 计算百分比
    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);
    },
    // 计算结果采用哪种颜色
    calcResultColor(value, isCallBackClass) {
      let color = '';
      let className = '';
      switch (value) {
        case ('0', 0):
          color = '#179b3b';
          className = 'none';
          break;
        case ('1', 1):
          color = '#8dc21f';
          className = 'mild';
          break;
        case ('2', 2):
          color = '#2ea7e0';
          className = 'moderate';
          break;
        case ('3', 3):
          color = '#ff5f8b';
          className = 'severe';
          break;
      }
      return isCallBackClass ? className : color;
    },
    // 重新拼接日期
    resetDate(startDate, endDate) {
      let callBackDate = '';
      if (startDate && endDate) {
        callBackDate = startDate.replace(/-/g, '.') + '-' + endDate.slice(5, endDate.length).replace(/-/g, '.');
      }
      return callBackDate;
    },
    onSignClick(index) {
      this.signActive = index;
    }
  }
};
</script>

<style scoped lang="scss">
@import './scss/report.scss';
</style>
