<!--  -->

<template>
  <div class="pageContent insight">
    <div class="periodNav">
      <div class="periodItem week" :class="{ active: active == 0 }" @click="active = 0">周</div>
      <div class="periodItem month" :class="{ active: active == 1 }" @click="active = 1">月</div>
    </div>
    <DateSwitch :dateType="active == 0 ? 'week' : 'month'" @updateDate="updateDate" v-if="false"></DateSwitch>
    <!-- <div class="periodSwitch">
      <div class="arrow arrowLeft">
        <van-icon name="arrow-left"></van-icon>
      </div>
      <div class="timearea">2023-11-15~2023-11-22</div>
      <div class="arrow arrowRight">
        <van-icon name="arrow"></van-icon>
      </div>
    </div> -->
    <div class="label">
      <div class="left">情绪感知</div>
      <div class="right">
        <span @click="onRouterTo('emo')">详情 ></span>
      </div>
    </div>
    <div class="periodNav">
      <div class="periodItem minPeriodItem" :class="{ active: emotionActive == index }" v-for="(item, index) in psyList"
        :key="index" @click="onEmotionClick(item, index)">
        <span>{{ item.name }}</span>
      </div>
    </div>
    <div class="echart-container">
      <div class="echart">
        <EchartBox echartId="emotionChart" :outTitle="emoLegend.outTitle" height="200" width="200" :legend="emoLegend"
          :options="defaultOptions"></EchartBox>
      </div>
    </div>
    <div class="grid">
      <div class="gridItem" :style="`background:${item.color};`" v-for="(item, index) in emotionList" :key="index">
        <div class="time">
          <span class="number">{{ item.days }}</span>
          <span>天</span>
        </div>
        <div class="title">{{ item.text }}</div>
      </div>
    </div>
    <div class="label">
      <div class="left">体征感知</div>
      <div class="right">
        <span @click="onRouterTo('signs')">详情 ></span>
      </div>
    </div>

    <div class="periodNav">
      <div class="periodItem minPeriodItem" :class="{ active: signActive == index }" v-for="(item, index) in signList"
        :key="index" @click="onSignClick(index, item)">
        <span>{{ item.name }}</span>
      </div>
    </div>
    <!-- bmi显示/输入 TODO待接口-->
    <!-- <div class="bmi" v-show="signActive == 2">
      <p>身高:<span>170</span>cm</p>
      <p>体重:<span>60</span>kg</p>
      <p>BMI:<span>24.5</span></p>
      <p>{{ bmi.result }}</p>
      <van-button size="mini">更新</van-button>
    </div> -->
    <div class="title-out">
      <span>{{ signsChartTitle }}</span>
    </div>
    <div class="ChatBox" :class="{ hiddenChart: signActive == 2 }">
      <div class="legendBox minLegendBox">
        <div class="legend">
          <div class="legendItem" :class="item.type" v-for="(item, index) in signGrid" :key="index">
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>

      <div class="Chat signChart" id="signChart"></div>
    </div>
    <div class="grid">
      <div class="gridItem" v-show="signActive != 2" :style="`background:${item.color};`"
        v-for="(item, index) in signDaysList" :key="index">
        <div class="time">
          <span class="number">{{ item.day }}</span>
          <span>天</span>
        </div>
        <div class="title">{{ item.name }}</div>
      </div>
    </div>
    <div class="ChatBox minChartBox" :class="{ hiddenChart: signActive != 2 }">
      <h4>运动步数</h4>
      <div class="Chat stepChart" id="stepChart"></div>
      <div class="result">
        <div class="wrapBox">
          <div class="text">
            <div class="left">
              <p>总步数：{{ stepsData.total || '--' }}</p>
            </div>
            <div class="right">
              <img :src="stepsData.lastStepTotalCompare > 0 ? upImg : downImg" alt="" />
              <span>{{ Math.abs(stepsData.lastStepTotalCompare) || '--' }}</span>
            </div>
          </div>
          <div class="text">
            <div class="left">
              <p>平均步数：{{ stepsData.avg || '--' }}</p>
            </div>
            <div class="right">
              <img :src="stepsData.lastStepAvgCompare > 0 ? upImg : downImg" alt="" />
              <span>{{ Math.abs(stepsData.lastStepAvgCompare) || '--' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="ChatBox minChartBox" :class="{ hiddenChart: signActive != 2 }">
      <h4>热量消耗</h4>
      <div class="Chat calorieChart" id="calorieChart"></div>
      <div class="result">
        <div class="wrapBox">
          <div class="text">
            <div class="left">
              <p>总消耗：{{ calorieData.total || '--' }}</p>
            </div>
            <div class="right">
              <img :src="calorieData.lastCalorieTotalCompare > 0 ? upImg : downImg" alt="" />
              <span>{{ Math.abs(calorieData.lastCalorieTotalCompare) || '--' }}</span>
            </div>
          </div>
          <div class="text">
            <div class="left">
              <p>平均消耗：{{ calorieData.avg || '--' }}</p>
            </div>
            <div class="right">
              <img :src="calorieData.lastCalorieAvgCompare > 0 ? upImg : downImg" alt="" />
              <span>{{ Math.abs(calorieData.avg) || '--' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import DateSwitch from '@/components/DateSwitch.vue';
import { format, startOfMonth, endOfMonth } from 'date-fns';
import ToastService from '@/services/toast-service';
import { /* EmotionModel, */ PsyBaseUrl } from '@/config/models';
import axios from 'axios';
import EchartBox from '@/components/EchartBox';
import APIHealthUser from '@/api/health-user';
import APIAlarm from '@/api/core';
export default {
  components: {
    DateSwitch,
    EchartBox
  },
  data() {
    return {
      active: 0,
      emotionActive: 0,
      signActive: 0,
      emotionChart: null,
      signChart: null,
      stepChart: null,
      calorieChart: null,
      psyList: [
        {
          name: '疲劳',
          type: 3
        },
        {
          name: '压力',
          type: 1
        },
        {
          name: '抑郁',
          type: 2
        }
      ],
      degreeList: [
        {
          name: '无',
          type: 'not',
          color: '#179B3B'
        },
        {
          name: '轻度',
          type: 'mild',
          color: '#2EA7E0'
        },
        {
          name: '中度',
          type: 'moderate',
          color: '#8DC21F'
        },
        {
          name: '重度',
          type: 'severe',
          color: '#FF5F8B'
        }
      ],
      signList: [
        {
          grid: 'heartRateList',
          name: '心率',
          label: 'heartrate'
        },
        {
          grid: 'temperatureList',
          name: '体温',
          label: 'temperature'
        },
        {
          grid: null,
          name: '运动',
          label: 'step'
        }
      ],
      heartRateList: [
        {
          name: '正常',
          type: 'moderate',
          color: '#179B3B'
        },
        {
          name: '偏高',
          type: 'severe',
          color: '#FF5F8B'
        },
        {
          name: '偏低',
          type: 'mild',
          color: '#2EA7E0'
        }
      ],
      temperatureList: [
        {
          name: '正常',
          type: 'moderate',
          color: '#179B3B'
        },
        {
          name: '发烧',
          type: 'severe',
          color: '#FF5F8B'
        }
      ],
      bmi: {
        height: '170',
        weight: '57',
        value: '24.5',
        result: '肥胖'
      },
      upImg: require('@/assets/today/icons/up.png'),
      downImg: require('@/assets/today/icons/down.png'),
      date: '',
      monthDate: {},
      dateList: [],
      emotionData: [],
      xAxisData: [], //图表x轴展示的数据
      echarts: null,
      signCurrent: 0,
      emoName: '',
      result: '',
      // 需要高亮的日期数组
      highlightDates: [],
      // 日历 默认最小可选择日期，默认为当前时间
      maxDate: new Date(this.$dayjs().hour(0).minute(0).second(0).format()),
      // 默认日历日期时间
      defaultDate: new Date(this.$dayjs().hour(0).minute(0).second(0).format()),

      // 7天和30天最大数据列表
      weekAndMonData: [],
      weekList: [],
      startDate: '', //接口需要的开始时间
      endDate: '', //接口需要的结束时间
      currentEmoName: '', //当前情绪名称
      emotionList: [],
      weekAndMonthSeries: null,
      emoType: '1',
      signData: {},
      signDaysList: [],
      stepsData: {},
      calorieData: {}
    };
  },
  created() {
    this.emoName = this.psyList[this.emotionActive].name;
    this.initEchartText();

    /* this.getPsychologiclData('', '2023-11-21', '2023-12-21'); */
  },
  async mounted() {
    const isExistToken = await this.getAuth();
    if (isExistToken) {
      this.initData();
      this.getPsychologiclData();
    }
  },
  watch: {
    active(val) {
      console.log(val);
      console.log('最近7天开始时间和结束时间', this.$getRangeStartAndEnd(7));
      let days = val === 0 ? 7 : 30;
      let startAndEndDate = this.$getRangeStartAndEnd(days);
      let date = {
        start: this.$dayjs(startAndEndDate.start).format('YYYY-MM-DD'),
        end: this.$dayjs(startAndEndDate.end).format('YYYY-MM-DD')
      };
      this.$nextTick(() => {
        this.updateDate(date);
      });

    },
    emotionActive(val) {
      console.log(val);
      /* this.$nextTick(() => {
        this.initEmotionChart();
      }); */
    },
    signActive(val) {
      console.log(val);
      this.$nextTick(() => {
        /* this.initSignChart(); */
        this.initData();
      });
    }
  },
  computed: {
    uid() {
      return this.$store.getters.uid
    },
    signsChartTitle() {
      return `${this.signList[this.signActive].name}数据图`
    },
    degreeMap() {
      let map = new Map();
      this.degreeList.forEach(item => {
        map.set(item.name, item.color);
      });
      return map;
    },
    heartRateMap() {
      let map = new Map();
      this.heartRateList.forEach(item => {
        map.set(item.name, item.color);
      });
      return map;
    },
    temperatureMap() {
      let map = new Map();
      this.temperatureList.forEach(item => {
        map.set(item.name, item.color);
      });
      return map;
    },
    signGrid() {
      let list = [];
      if (this.signList[this.signActive].grid) {
        let temp = this[`${this.signList[this.signActive].grid}`];
        if (temp) {
          list = temp;
        }
      }
      return list;
    },
    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: ''
          }
        ]
      };
    },
    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' }
        ]
      };
    }
  },
  methods: {
    //   获取b端token
    getAuth() {
      let manufactorId = '5bf13062-a41e-4d00-ba14-1101aad12650';
      return new Promise((resove, reject) => {
        APIAlarm.getAuth({ manufactorId: manufactorId })
          .then(res => {
            let data = res.data;
            if (data.code === 0) {
              this.$store.commit('ssjlToken', res.data.data);
              resove(true);
            }
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    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: ''
        }
      ];
      let days = this.active === 0 ? 7 : 30;
      let startAndEndDate = this.$getRangeStartAndEnd(days);
      this.date = {
        start: this.$dayjs(startAndEndDate.start).format('YYYY-MM-DD'),
        end: this.$dayjs(startAndEndDate.end).format('YYYY-MM-DD')
      };
    },
    // 获取情绪数据
    getPsychologiclData(date, startDate, endDate) {
      ToastService.loading({
        message: '数据加载中'
      });
      let reqParams = {
        uid: this.uid,
        startDate: startDate || this.date.start,
        endDate: endDate || this.date.end,
        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);
        })
        .finally(() => {
          ToastService.clear();
        });
    },
    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;
    },
    updateDate(value) {
      this.date = value;
      console.log('this.date', this.date);
      this.getPsychologiclData('', value.start, value.end);
      this.initData();
      //this.getReportData('', value.start, value.end);
    },
    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 + '';
    },
    // 计算结果采用哪种颜色
    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;
    },
    // 计算百分比
    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);
    },
    getMonthStaEnd(value) {
      const dateObj = {};
      console.log("时间值", value);
      const start = startOfMonth(value);
      const end = endOfMonth(value);
      console.log("时间值start", start);
      console.log("时间值end", end);
      dateObj.start = format(start, 'yyyy-MM-dd');
      dateObj.end = format(end, 'yyyy-MM-dd');
      this.monthDate = { ...dateObj };
    },
    initData() {
      //初始化图表
      /* if (!this.emotionChart) {
        this.emotionChart = this.$echarts.init(document.getElementById('emotionChart'));
      } */

      if (!this.signChart) {
        this.signChart = this.$echarts.init(document.getElementById('signChart'));
      }
      if (!this.stepChart) {
        this.stepChart = this.$echarts.init(document.getElementById('stepChart'));
      }
      if (!this.calorieChart) {
        this.calorieChart = this.$echarts.init(document.getElementById('calorieChart'));
      }
      //渲染图表
      /* this.initEmotionChart(); */
      this.initSignChart();
    },
    initEmotionChart() {
      let option = this.getOption();

      //测试
      let data = [
        {
          time: '5.11',
          value: 10
        },
        {
          time: '5.12',
          value: 20
        },
        {
          time: '5.13',
          value: 40
        },
        {
          time: '5.14',
          value: 50
        },
        {
          time: '5.15',
          value: 60
        },
        {
          time: '5.16',
          value: 70
        },
        {
          time: '5.17',
          value: 90
        }
      ];

      this.formateEmotionData(option, data);

      this.emotionChart.setOption(option);
    },
    async initSignChart() {
      let option = this.getOption();

      let data = await this.getReportData('', this.date.start, this.date.end);
      if (this.signActive == 0) {
        //测试
        this.formateHeartRateData(option, data.day);
        this.signChart.setOption(option);
      } else if (this.signActive == 1) {
        //测试
        this.formateTemperatureData(option, data.day);
        this.signChart.setOption(option);
      } else if (this.signActive == 2) {
        option = this.getOption(false);
        let option2 = this.getOption(false);
        let data2 = await this.getReportData(3, this.date.start, this.date.end);
        this.stepsData = { ...data };
        this.calorieData = { ...data2 };

        this.formateStepData(option, data.day);
        this.formateCalorieData(option2, data2.day);

        this.stepChart.setOption(option);
        this.calorieChart.setOption(option2);
      }
    },
    formateEmotionData(option, data) {
      let xdata = [];
      let ydata = [];
      let fill = [];
      let max = 0;
      data.forEach(item => {
        if (item.value > max) {
          max = item.value || '--';
        }
      });
      data.forEach(item => {
        xdata.push(item.time);
        fill.push({
          value: max - item.value || '--',
          label: {
            show: false
          },
          itemStyle: {
            color: this.formateEmotionColor(item.value)
          }
        });
        ydata.push({
          value: item.value || '--',
          label: {
            show: true
          },
          itemStyle: {
            color: this.formateEmotionColor(item.value)
          }
        });
      });
      option.xAxis.data = xdata;
      option.series[0].data = ydata;
      /* option.series[1].data = fill; */
    },
    formateEmotionColor(value) {
      if (value > 75) {
        return this.degreeMap.get('重度');
      } else if (value > 50) {
        return this.degreeMap.get('中度');
      } else if (value > 25) {
        return this.degreeMap.get('轻度');
      } else {
        return this.degreeMap.get('无');
      }
    },
    formateHeartRateData(option, data) {
      let xdata = [];
      let ydata = [];
      let fill = [];
      let max = 0;
      data.forEach(item => {
        if (item.value > max) {
          max = item.value || '--';
        }
      });
      data.forEach(item => {
        xdata.push(item.date);
        fill.push({
          value: max - item.value || '--',
          label: {
            show: false
          },
          itemStyle: {
            borderWidth: 3,
            borderColor: this.calcColorByEvaluate(item.evaluate)
          }
        });
        ydata.push({
          value: item.value || '--',
          label: {
            show: false
          },
          itemStyle: {
            borderWidth: 3,
            borderColor: this.calcColorByEvaluate(item.evaluate)
          }
        });
      });
      option.xAxis.data = xdata;
      option.series[0].data = ydata;
      /* option.series[1].data = fill; */
      // 规定最小值
      option.yAxis.min = 40;
      // 规定最大值
      option.yAxis.max = 150;
      //设置高压标线
      option.series[0].markLine = {
        data: [
          {
            symbol: 'pin',
            silent: true,
            yAxis: 120,
            lineStyle: {
              color: '#C1272D'
            },
            label: {
              color: '#C1272D'
            }
          }
        ]
      };
    },
    formateHeartRateColor(value) {
      if (value > 120) {
        return this.heartRateMap.get('偏高');
      } else if (value >= 60) {
        return this.heartRateMap.get('正常');
      } else {
        return this.heartRateMap.get('偏低');
      }
    },
    formateTemperatureData(option, data) {
      let xdata = [];
      let ydata = [];
      let fill = [];
      let max = 0;
      data.forEach(item => {
        if (item.value > max) {
          max = item.value || '--';
        }
      });
      data.forEach(item => {
        xdata.push(item.date);
        fill.push({
          value: max - item.value || '--',
          label: {
            show: false
          },
          itemStyle: {
            borderWidth: 3,
            borderColor: this.calcColorByEvaluate(item.evaluate)
          }
        });
        ydata.push({
          value: item.value || '--',
          label: {
            show: false
          },
          itemStyle: {
            borderWidth: 3,
            borderColor: this.calcColorByEvaluate(item.evaluate)
          }
        });
      });
      option.xAxis.data = xdata;
      option.series[0].data = ydata;
      option.series[0].markLine = {
        data: [
          {
            type: "average",
            name: "体温",
            yAxis: 37.2,
            label: {
              fontSize: 14,
              position: "end",
            },
            lineStyle: {
              type: "dashed",
              width: 2,
              color: "red",
            },
          },
        ],
      }
      /* option.series[1].data = fill; */
      // 规定最小值
      option.yAxis.min = 34.5;
      // 规定最大值
      option.yAxis.max = 42.5;
    },
    formateTemperatureColor(value) {
      if (value > 38) {
        return this.temperatureMap.get('发烧');
      } else {
        return this.temperatureMap.get('正常');
      }
    },
    formateStepData(option, data) {
      let xdata = [];
      let ydata = [];
      data.forEach(item => {
        xdata.push(item.date);
        ydata.push({
          value: item.value,
          label: {
            show: true
          },
          itemStyle: {
            borderWidth: 3,
            borderColor: this.calcColorByEvaluate(item.evaluate)
          }
        });
      });
      option.xAxis.data = xdata;
      option.series[0].data = ydata;
      // 隐藏y轴
      option.yAxis.show = false;
    },
    formateCalorieData(option, data) {
      let xdata = [];
      let ydata = [];
      data.forEach(item => {
        xdata.push(item.date);
        ydata.push({
          value: item.value,
          label: {
            show: true
          },
          itemStyle: {
            borderWidth: 3,
            borderColor: this.calcColorByEvaluate(item.evaluate)
          }
        });
      });
      option.xAxis.data = xdata;
      option.series[0].data = ydata;
      // 隐藏y轴
      option.yAxis.show = false;
    },
    getOption(/* point = true */) {
      let option = {
        grid: {
          show: true,
          borderWidth: 0,
          top: '10%',
          left: '15%',
          right: '10%',
          bottom: '20%'
        },
        xAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: '#ddd',
              width: 4
            }
          },
          axisLabel: {
            show: true,
            fontSize: 12,
            showMinLabel: true, //显示最小值
            showMaxLabel: true, //显示最大值
            marginBottom: 10 // 调整标签与轴线的距离
          }
        },
        yAxis: {
          type: 'value',
          boundaryGap: ['5%', '5%'],
          nameTextStyle: {
            fontSize: 13
          },
          alignTicks: false,
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            fontSize: 13
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: '#ddd',
              width: 1
            }
          }
        },
        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) {
            console.log("params", params);
            return params[0].marker + params[0].name + '</br>' + params[0].value;
          }
        },
        series: [
          {
            type: 'line',
            padding: 10,
            smooth: true,
            symbol: 'circle',
            symbolSize: 10,
            itemStyle: {
              color: '#fff',
              borderWidth: 4
            },
            lineStyle: {
              width: 6,
              type: 'solid',
              color: '#189b3b'
            }
          },
          /* {
            type: 'bar',
            barMaxWidth: 15,
            stack: 'value',
            stackStrategy: 'all',
            animation: false,
            itemStyle: {
              borderRadius: [12, 12, 0, 0],
              show: false
            }
          } */
        ]
      };

      /* if (!point) {
        option.series = [
          {
            type: 'bar',
            barMaxWidth: 15,
            label: {
              show: true,
              color: '#000',
              position: 'outside'
            },
            itemStyle: {
              borderRadius: 12
            }
          }
        ];
      } */

      return option;
    },
    onEmotionClick(item, index) {
      this.emotionActive = index;
      this.emoName = item.name;
      this.emoType = item.type;
      if (this.active == 1) {
        /* this.getMonthStaEnd(this.date); */
        this.getPsychologiclData('', this.monthDate.start, this.monthDate.end);
      } else {
        this.getPsychologiclData('', this.date.start, this.date.end);
      }
      // 情绪选项变化重新渲染图表
    },
    onSignClick(index) {
      this.signActive = index;
      // 体征选项变化重新渲染图表
    },
    onRouterTo(name) {
      this.$router.push({
        name: name === 'emo' ? 'reportList' : 'signsReport',
        query: {
          type: name === 'emo' ? this.emoType : this.signActive,
          dateType: this.active, //日期类型
          name: this.signList[this.signActive].label
        }
      });
    },
    // 根据等级计算颜色
    calcColorByEvaluate(value) {
      let color = '';
      const intValue = Number(value);
      switch (intValue) {
        case 1:
          // 偏高
          color = '#ff5f8b';
          break;
        case 2:
          // 正常
          color = '#189b3b';
          break;
        case 3:
          // 偏低
          color = '#2ea7e0';
          break;
        default:
          color = '#189b3b';
          break;
      }
      return color;
    },
    // 获取体征历史数据
    getReportData(value, startDate, endDate) {
      let reqDate = this.date;
      let reqBody = {
        personId: this.$store.getters.personId,
        dateType: 1,
        healthyType: value || this.signActive,
        startTime: startDate || reqDate.start,
        endTime: endDate || reqDate.end
      };
      return new Promise(resolve => {
        APIHealthUser.getReportData(reqBody).then(res => {
          if (res.data.data.day) {
            res.data.data.day = res.data.data.day.map(item => {
              item.date = this.$dayjs(item.date).format('MM-DD');
              return item;
            });
          }
          this.signData = { ...res.data.data };

          if (this.signActive === 1) {
            this.signDaysList = [
              { day: res.data.data.normal, name: '正常', color: '#189b3b' },
              { day: res.data.data.fever, name: '偏高', color: '#ff5f8b' }
              /*  { day: res.data.data.low, name: '偏低', color: '#2ea7e0' } */
            ];
          } else {
            this.signDaysList = [
              { day: res.data.data.normal, name: '正常', color: '#189b3b' },
              { day: res.data.data.high, name: '偏高', color: '#ff5f8b' },
              { day: res.data.data.low, name: '偏低', color: '#2ea7e0' }
            ];
          }
          resolve(res.data.data);
        });
      });
    }
  }
};
</script>

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

.insight {
  padding-top: 20px;

  .periodNav {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .periodItem {
      width: 48%;
      font-size: 28px;
      color: black;
      text-align: center;
      padding: 12px;
      border-radius: 30px;
      background: #e6e6e6;

      &.active {
        color: white;
        background: #179b3b;
      }
    }

    .minPeriodItem {
      width: 32%;
      padding: 8px;
    }
  }

  .periodSwitch {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    padding: 40px 10px;
    padding-bottom: 10px;

    .timearea {
      font-size: 28px;
      justify-self: center;
      color: gray;
    }

    .arrow {
      font-size: 45px;
    }
  }

  .bmi {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    white-space: nowrap;
    padding: 40px 8px 0 8px;
    font-weight: bold;

    p {
      padding: 0 5px;
      font-size: 28px;
    }

    .van-button {
      padding: 5px 10px;
      margin-left: 50px;
      font-size: 12px;
      color: #fff;
      border-radius: 30px;
      background-color: $green;
    }
  }

  .label {
    font-size: 36px;
    font-weight: bold;
    padding: 30px 10px 30px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .right {
      font-size: 30px;
    }
  }

  .title-out {
    font-size: 36px;
    font-weight: bold;
    padding: 60px 20px 20px 20px;
  }

  .echart-container {
    flex: 1;
    position: relative;
    min-height: 600px;
    background-color: #fff;
    padding: 0 10px;
  }

  .ChatBox {
    overflow: hidden;
    width: calc(100vw - 60px);
    height: 650px;
    border: 2px solid #cdf348;
    border-radius: 30px;
    /* margin-top: 30px; */

    h4 {
      padding: 40px 0 10px 60px;
    }

    .legendBox {
      width: 100%;
      height: 100px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 0 30px;

      .legend {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-end;
        align-items: center;
        font-size: 20px;

        .legendItem {
          position: relative;
          width: 205px;
          margin-top: 10px;
          margin-right: 20px;

          &:nth-child(2n) {
            margin-right: 0;
          }
        }

        .not {
          .number {
            color: #179b3b;
          }

          &::before {
            content: '';
            position: absolute;
            top: 0;
            bottom: 0;
            left: -20px;
            width: 15px;
            height: 15px;
            background: #179b3b;
            border-radius: 50%;
            margin: auto;
          }
        }

        .mild {
          .number {
            color: #2ea7e0;
          }

          &::before {
            content: '';
            position: absolute;
            top: 0;
            bottom: 0;
            left: -20px;
            width: 15px;
            height: 15px;
            background: #2ea7e0;
            border-radius: 50%;
            margin: auto;
          }
        }

        .moderate {
          .number {
            color: #8dc21f;
          }

          &::before {
            content: '';
            position: absolute;
            top: 0;
            bottom: 0;
            left: -20px;
            width: 15px;
            height: 15px;
            background: #8dc21f;
            border-radius: 50%;
            margin: auto;
          }
        }

        .severe {
          .number {
            color: #ff5f8b;
          }

          &::before {
            content: '';
            position: absolute;
            top: 0;
            bottom: 0;
            left: -20px;
            width: 15px;
            height: 15px;
            background: #ff5f8b;
            border-radius: 50%;
            margin: auto;
          }
        }
      }
    }

    .minLegendBox {
      .legend {
        .legendItem {
          width: auto;
          margin-right: 50px;

          &:nth-child(2n) {
            margin-right: 50px;
          }

          &:last-child {
            margin-right: 0;
          }
        }
      }
    }

    .Chat {
      width: calc(100vw - 60px);
      height: 500px;
    }

    .result {
      height: 140px;
      padding: 0 30px;
      border-radius: 70px;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      flex-direction: column;

      .wrapBox {
        padding: 10px 120px 10px 60px;
        width: 100%;
        background-color: #e6e6e6;
        border-radius: 30px;
      }

      .text {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        .right {

          @include center();
          padding-left: px2rem(20);

          img {
            height: 30px;
            width: 30px;
            object-fit: contain;
            margin: 0 5px;
          }
        }
      }
    }
  }

  .minChartBox {
    height: 760px;
  }

  .hiddenChart {
    width: 0;
    height: 0;
  }

  .grid {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    color: white;
    font-size: 30px;

    .gridItem {
      width: calc((100vw - 60px) * 0.48);
      height: calc((100vw - 60px) * 0.48);
      border-radius: 60px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-top: 30px;

      .time {
        .number {
          font-size: 90px;
          font-weight: bold;
        }
      }
    }

    .minItem {
      width: calc((100vw - 60px) * 0.32);
      height: calc((100vw - 60px) * 0.32);
      font-size: 28px;

      .time {
        .number {
          font-size: 70px;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
