<!-- 今日 -->

<template>
  <div class="today">
    <div class="devicesSwitch" v-if="false">
      <!-- <i :class="[{on: isClear},'news']" @click="newsClick" v-show="true"></i> -->
      <div :class="[
      'imgArea',
      {
        cut: currentPerson.deviceStatus ? currentPerson.deviceStatus.online != 0 : false
      }
    ]" @click="imgAreaClick" v-show="personList !== null && personList.length">
        <img :src="currentPerson.avatar" />
        <span style="font-weight: bolder" v-show="currentPerson && currentPerson.nickName">{{
      currentPerson.nickName
    }}</span>
        <span>切换</span>
      </div>
      <!-- 点击宝贝切换出现 -->
      <div :class="[{ active: conAreaShow }, 'conArea']" v-if="personList !== null">
        <div class="list" v-for="(item, index) in personList" :key="`list_index_${index}`"
          @click="imageListClick(item, index)">
          <div :class="[
      { active: item.id == $store.getters.personId },
      'imgA',
      {
        online: {
          online: item.deviceStatus ? item.deviceStatus.online && item.deviceStatus.online == 1 : 'false'
        }
      }
    ]">
            <img :src="item.avatar" />
          </div>
          <div :class="['Myname', { active: item.id == $store.getters.personId }]">
            {{ item.nickName }}
          </div>
        </div>
      </div>
    </div>
    <div v-show="isPageShow" class="today-con" @click="conAreaShow = false">
      <!-- 未绑定有设备时或者未添加有用户时 -->
      <!-- <div class="no-data" v-show="currentPerson.deviceId == null">
        <img :src="noDataImg" alt="" />
        <p>暂无设备信息</p>
      </div> -->
      <!-- 今日状态 -->
      <div @click="conAreaShow = false" :style="{
      paddingBottom: isShowBind ? '40px' : 0
    }">
        <div class="today-status">
          <img class="img" :src="calcTodayStatus(todayLevel, 'img')" />
          <!-- <img
            class="icon"
            src="@/assets/today/icons/2_12.png"
            @click="calendarDialogShow = true"
          /> -->
          <div class="status">
            <p>状态{{ calcTodayStatus(todayLevel, 'text') }}</p>
            <ul>
              <li v-for="(item, index) in statusList" :key="index" :class="[item.className, { active: item.active }]">
              </li>
              <!-- <li :class="['toobad', { active: false }]"></li>
              <li :class="['ordinary', { active: todayStatus }]"></li>
              <li :class="['sameas', { active: false }]"></li>
              <li :class="['excellent', { active: false }]"></li> -->
            </ul>
          </div>
          <div class="interpret">
            <div class="no-text" v-if="todayResult.Level === -1">
              <img :src="noDataImg" alt="" />
              <p>暂无信息</p>
            </div>
            <div v-else>
              <!-- 工作学习要有度，适当摸鱼也很好，不用太卷哟！保持张弛
              有度的节奏，是应对压力的有效方法。
              综合今日的HRV(MSSD)和静息心率情况看，你今天整体状
              态优秀，身体压力状态较小，能很好应对今日工作生活中的
              挑战，请继续保持优秀状态。 相信自己，你一定可以实现你的目标！ -->

              <p>{{ todayResult.Describe || '' }}</p>
              <p>{{ todayResult.TirDesc || '' }}</p>
              <P>{{ todayResult.StressDesc || '' }}</P>
              <P>{{ todayResult.DepDesc || '' }}</P>
              <P>{{ todayResult.EncouragingLanguage || '' }}</P>
            </div>
            <!-- <hr /> -->
            <!-- <div class="bottom">
              <p>详细解读</p>
              <div @click="onScroll">
                <span>日记</span>
                <img src="@/assets/today/icons/2_22.png" />
              </div>
            </div> -->
          </div>
        </div>
        <!-- 今日情绪感知 -->
        <div class="emotion">
          <div class="title" @click="onRouterTo('emotionDetails', 'tiredness')">
            <p>今日情绪感知</p>
            <div>
              <p>{{ now }}</p>
              <van-icon name="arrow" size="18" />
            </div>
          </div>
          <ul>
            <li v-for="(item, index) in psyDataList.length > 0 ? psyDataList : 3" :key="index"
              :style="{ backgroundColor: item.bgColor }" @click="onRouterTo('emotionDetails', item.class)">
              <h4>{{ item.value || '--' }}</h4>
              <p>{{ item.name || '--' }}</p>
              <span>{{ item.result || '暂无数据' }}</span>
              <time>{{ item.time || '--' }}</time>
            </li>
          </ul>
        </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="calendarDialogShow" :min-date="minDate" :max-date="maxDate"
                :default-date="defaultDate" :round="false" :poppable="false" color="#179b3b" :show-confirm="false"
                :show-title="true" :show-subtitle="false" :formatter="formatterDay" @select="onSelect" />
            </div>
          </template>
        </van-dialog>
        <!-- 今体征感知 todo 待需求开放-->
        <div class="perception" v-if="true">
          <div class="title" @click="onRouterTo('signsDetails', 'temperature')">
            <p>今日体征感知</p>
            <div>
              <p>{{ now }}</p>
              <van-icon name="arrow" size="18" />
            </div>
          </div>
          <ul>
            <li v-for="(item, index) in signDataList.length > 0 ? signDataList : 3" :key="index"
              :style="{ backgroundColor: item.bgColor }" @click="onRouterTo('signsDetails', item.class)">
              <h4>{{ item.value || '--' }}</h4>
              <p>{{ item.name || '暂无数据' }}</p>
              <time>{{ item.time || '--' }}</time>
            </li>
          </ul>
          <div class="tip">
            <img class="img" src="@/assets/today/icons/2_25.png" />
            <p>
              <span>温馨提示：</span>检测数据仅供参考，<span>不可做医疗诊断和治疗依据</span>，在运动、工作等场景会影响健康检测。
            </p>
          </div>
        </div>
        <div class="diary">
          <div class="title">
            <p>情绪日记</p>
            <div>
              <div>
                <p @click="onSaveDiary">保存</p>
                <van-icon name="arrow" size="18" />
              </div>
            </div>
          </div>
          <div class="main">
            <van-radio-group v-model="result">
              <van-radio v-for="(item, index) in moodList" :key="index" :name="item.con" shape="square" icon-size="14"
                checked-color="#179b3b">

                <template #default>
                  <div class="checkbox-label">
                    <img :src="item.imgPath" />
                    <div class="text">
                      <span>{{ item.text }}</span>
                    </div>

                  </div>
                </template>
              </van-radio>
              <!--  <van-checkbox name="b" shape="square" checked-color="#179b3b">
                <img src="@/assets/today/icons/2_59.png" />
              </van-checkbox>
              <van-checkbox name="c" shape="square" checked-color="#179b3b">
                <img src="@/assets/today/icons/2_54.png" />
              </van-checkbox>
              <van-checkbox name="d" shape="square" checked-color="#179b3b">
                <img src="@/assets/today/icons/2_67.png" />
              </van-checkbox>
              <van-checkbox name="e" shape="square" checked-color="#179b3b">
                <img src="@/assets/today/icons/2_72.png" />
              </van-checkbox>
              <van-checkbox name="f" shape="square" checked-color="#179b3b">
                <img src="@/assets/today/icons/2_70.png" />
              </van-checkbox> -->
            </van-radio-group>
            <div class="textarea">
              <textarea placeholder="我要写亲密日记" rows="5" v-model="diary" ref="myTextarea"></textarea>
            </div>
          </div>
        </div>
        <!-- 情绪知识库 -->
        <div class="knowledge">
          <div class="title">
            <p>情绪知识库</p>
          </div>
          <div class="main">
            <ul>
              <li>
                <p>健康同学 测量的 什么压力？ 测量原理是什么？</p>
                <img src="@/assets/today/images/2_42.png" />
              </li>
              <li>
                <p>健康同学 测量的 什么压力？ 测量原理是什么？</p>
                <img src="@/assets/today/images/2_48.png" />
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <!-- 绑定或者添加用户提示 -->
    <div class="bind-tips" @click="onToBind(tipsText)" v-show="isPageShow">
      <div class="con" v-show="isShowBind">
        <p>点击绑定{{ tipsText }}</p>
      </div>
    </div>
    <!-- <overlay-loading :showOverlay="showOverlay"></overlay-loading> -->
  </div>
</template>

<script>
import APIAlarm from '@/api/core';
import APIPsy from '@/api/psychological';
import APIHealthUser from '@/api/health-user';
/* import overlayLoading from '@/components/overlay-loading/overlay-loading'; */
import ToastService from '../../services/toast-service';
import DialogService from '../../services/dialog-service';
export default {
  /* components: { overlayLoading }, */
  data() {
    return {
      todayStatus: true,
      // 0：优秀、1：良好、2：一般、3：糟糕
      statusList: [
        { className: 'toobad', active: false, value: 3 },
        { className: 'ordinary', active: false, value: 2 },
        { className: 'sameas', active: false, value: 1 },
        { className: 'excellent', active: false, value: 0 }
      ],
      moodList: [
        { name: 'a', imgPath: require('@/assets/today/icons/2_72.png'), text: '平静', con: '🙂' },
        { name: 'b', imgPath: require('@/assets/today/icons/2_59.png'), text: '开心', con: '😀' },
        { name: 'c', imgPath: require('@/assets/today/icons/2_54.png'), text: '生病', con: '😢' },
        { name: 'd', imgPath: require('@/assets/today/icons/2_67.png'), text: '生气', con: '☹️' },
        { name: 'e', imgPath: require('@/assets/today/icons/2_72.png'), text: '失落', con: '😔' },
        { name: 'f', imgPath: require('@/assets/today/icons/2_70.png'), text: '难过', con: '😞' },

      ],
      todayResult: {},
      todayLevel: '',
      dateList: [
        { name: 'today', text: '今天', value: 0 },
        { name: 'week', text: '7天', value: 7 },
        { name: 'month', text: '30天', value: 30 }
        /* { name: 'weekReport', text: '周报', value: 49 } */
      ],
      date: '',
      calendarDialogShow: false,
      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()),
      currentRate1: 0,
      currentRate2: 0,
      result: [],
      uid: '',
      psyDataList: [],
      signDataList: [],
      devicesList: [
        {
          imagePath: '',
          deviceId: '',
          deviceStatus: { online: 1 },
          serialNo: '861281060086216'
        }
      ],
      conAreaShow: false,
      currentDevice: {
        // 当前设备对象，用于存储接口返回的list的当前对象
        deviceId: '',
        deviceName: '',
        phoneNumber: '',
        personName: '',
        binType: '',
        nickName: '',
        imagePath: '',
        serialNo: '861281060086216',
        positionTime: '',
        deviceVersion: '',
        locationType: '',
        lat: '',
        lng: '',
        deviceStatus: {
          battery: '',
          online: '',
          step: ''
        },
        address: '',
        radius: 0
      },
      // 需要高亮的日期数组
      highlightDates: [],
      // 人员列表
      personList: [],
      // 当前人员信息
      currentPerson: {},
      noDataImg: require('@/assets/today/images/no_data_01.png'),
      showOverlay: true,
      isPageShow: false,
      encouragingLanguage: '',
      diary: '', //情绪日记内容
    };
  },
  computed: {
    now() {
      return this.$dayjs(new Date()).format('MM.DD');
    },
    tipsText() {
      // 如果没有添加用户，则提示添加用户，否则提示添加设备
      return this.personList.length > 0 ? (this.currentPerson.deviceId == null ? '设备' : '') : '用户';
    },
    isShowBind() {
      return this.personList.length > 0 ? (this.currentPerson.deviceId == null ? true : false) : true;
    },
    isBinding() {
      return this.$route.query.isBinding || false;
    }
  },
  created() {
    this.$nextTick(() => {
      this.getPersonList();
      this.getAuth();
    })
  },
  mounted() {

  },
  methods: {
    getPersonList() {
      APIHealthUser.personList()
        .then(res => {
          console.log('人员列表', res);
          const list = res.data.data;
          if (list) {
            this.personList = list;
            let personIdIndex = list.findIndex(item => {
              return item.id == this.$store.getters.personId;
            });
            if (personIdIndex < 0) {
              this.$store.commit('personId', list[0].id);
            }
          }
          this.getPersonInfo();
        })
        .catch(() => {
          this.showOverlay = false;
          this.isPageShow = true;
        });
    },
    // 获取指定用户信息
    getPersonInfo(personId, showToast) {
      if (showToast) {
        ToastService.loading({
          message: '切换中'
        });
      }
      let reqParams = {
        personId: personId || this.$store.getters.personId
      };
      APIHealthUser.personInfo(reqParams)
        .then(res => {
          const data = res.data.data;
          if (data) {
            let deviceStatus = this.personList.filter(item => {
              return item.id == this.$store.getters.personId;
            });
            this.currentPerson = {
              id: data.personId,
              avatar: data.avatar,
              nickName: data.nickName,
              uid: data.physicUid,
              deviceId: data.deviceId,
              deviceStatus: deviceStatus[0] ? deviceStatus[0].deviceStatus : ''
            };
            this.$store.commit('deviceId', data.deviceId || '');
            this.$store.commit('serialNo', data.imei);
            console.log('this.currentPerson', this.currentPerson);
            this.getComprehensiveEvaluation();
            this.getPsychologiclData();
            this.getHomeData();
          }
        })
        .catch(error => {
          console.log('error', error);
          this.showOverlay = false;
          this.isPageShow = true;
        })
        .finally(() => {
          if (showToast) {
            ToastService.clear();
          }
          this.showOverlay = false;
          this.isPageShow = true;
        });
    },
    // 获取首页情绪数据
    getPsychologiclData() {
      let reqParams = {
        uid: this.currentPerson.uid,
        date: this.$dayjs(new Date()).format('YYYY-MM-DD') /* '2023-11-21' */
      };
      APIPsy.getHomeData(reqParams).then(res => {
        const data = res.data.response;
        if (!data) {
          ToastService.fail(res.data.msg);
        }
        this.psyDataList = [
          // 2023.12.5 修改菜单顺序
          // 疲劳指数
          {
            value: data.TirScore,
            name: '疲劳指数',
            class: 'tiredness',
            result: data.TirDesc,
            time: data.TirMeasureUpdateTime ? this.$dayjs(data.TirMeasureUpdateTime).format('HH:mm') : '',
            level: data.TirLevel,
            bgColor: this.calcResultColor(data.TirLevel)
          },
          // 压力指数
          {
            value: data.StressScore,
            name: '压力指数',
            class: 'stress',
            result: data.StressDesc,
            time: data.StressMeasureUpdateTime ? this.$dayjs(data.StressMeasureUpdateTime).format('HH:mm') : '',
            level: data.StressLevel,
            bgColor: this.calcResultColor(data.StressLevel)
          },
          // 抑郁
          {
            value: data.DepScore,
            name: '抑郁指数',
            class: 'depression',
            result: data.DepDesc,
            time: data.DepMeasureUpdateTime ? this.$dayjs(data.DepMeasureUpdateTime).format('HH:mm') : '',
            level: data.DepLevel,
            bgColor: this.calcResultColor(data.DepLevel)
          }
        ];
      });
    },
    // 当天三大指标综合总评
    getComprehensiveEvaluation() {
      let reqParams = {
        uid: this.currentPerson.uid,
        date: this.$dayjs(new Date()).format('YYYY-MM-DD') /* '2023-11-21' */
      };
      APIPsy.getComprehensiveEvaluation(reqParams).then(res => {
        const data = res.data.response;
        if (!data) {
          return ToastService.fail(res.data.msg);
        } else {
          console.log('三大指标', data);
          this.todayResult = { ...data };
          this.todayLevel = data.Level;
          this.statusList.map(item => {
            item.active = item.value == data.Level;
            return item;
          });
        }
      });
    },
    calcTodayStatus(level, type) {
      // @/assets/today/images/2_03.png
      let text = '';
      let imgPath = require('@/assets/today/images/2_03.png');
      if (this.$own.isNull(level) || level === -1) {
        return type == 'text' ? text : imgPath;
      }
      switch (level) {
        case 0:
          text = '优秀';
          imgPath = require('@/assets/today/images/2_03.png');
          break;
        case 1:
          text = '良好';
          imgPath = require('@/assets/today/images/2_03.png');
          break;
        case 2:
          text = '一般';
          imgPath = require('@/assets/today/images/2_39.png');
          break;
        case 3:
          text = '糟糕';
          imgPath = require('@/assets/today/images/2_62.png');
          break;
      }
      return type == 'text' ? text : imgPath;
    },
    // 获取首页体征数据
    getHomeData() {
      let reqParams = {
        personId: this.$store.getters.personId
      };
      APIHealthUser.getHomeData(reqParams)
        .then(res => {
          console.log('体征:', res);
          let data = res.data.data;
          this.signDataList = [
            // 2023.12.5 修改菜单顺序
            // 疲劳指数
            {
              value: data.temperature,
              name: '体温',
              class: 'temperature',
              /* result: data.TirDesc, */
              time: data.temperatureTime ? this.$dayjs(data.temperatureTime).format('HH:mm') : '',
              bgColor: this.calcSignResultColor(data.levelTemperature)
            },
            // 压力指数
            {
              value: data.heartRate,
              name: '心率',
              class: 'heartrate',
              /* result: data.StressDesc, */
              time: data.heartRateTime ? this.$dayjs(data.heartRateTime).format('HH:mm') : '',
              bgColor: this.calcSignResultColor(data.levelHeartRate)
            },
            // 抑郁
            {
              value: data.steps,
              name: '步数',
              class: 'step',
              /* result: data.DepDesc, */
              time: data.stepsTime ? this.$dayjs(data.stepsTime).format('HH:mm') : '',
              bgColor: this.calcSignResultColor(data.levelSteps)
            }
          ];
        })
        .finally(() => {
          this.showOverlay = false;
          this.isPageShow = true;
        });
    },
    formatDate(date) {
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    async onRouterTo(name, query) {
      console.log('name', name, this.currentPerson.uid);
      if (name === 'emotionDetails') {
        // 心理
        if (this.currentPerson.uid) {
          // 先根据uid查建模进度，未完成跳建模进度查询页面，完成跳详情
          const isModelSuccess = await this.getProgress();
          console.log('isModelSuccess', isModelSuccess);
          if (!isModelSuccess) {
            this.$router.push({
              name: 'psychologicalModeling',
              query: {
                uid: this.currentPerson.uid
              }
            });
          }
          this.$router.push({
            name: name,
            query: {
              // 参数默认传疲劳
              name: query,
              uid: this.currentPerson.uid
            }
          });
        } else {
          DialogService.confirm({
            message: `uid不存在，请联系管理员`
          });
        }
      } else {
        this.$router.push({
          name: name,
          query: {
            // 参数默认传疲劳
            name: query,
            uid: this.currentPerson.uid
          }
        });
      }
    },
    // 计算体征结果采用哪种颜色
    calcSignResultColor(value, isCallBackClass) {
      let color = '';
      let className = '';
      switch (Number(value)) {
        case 0:
          color = '#2ea7e0';
          className = 'none';
          break;
        case 1:
          color = '#179b3b';
          className = 'moderate';
          break;
        case 2:
          color = '#ff5f8b';
          className = 'severe';
          break;
        case 3:
          color = '#ff5f8b';
          className = 'severe';
          break;
        default:
          color = '#179b3b';
          className = 'none';
          break;
      }
      return isCallBackClass ? className : color;
    },
    // 计算情绪结果采用哪种颜色
    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;
        default:
          color = '#179b3b';
          className = 'none';
          break;
      }
      return isCallBackClass ? className : color;
    },
    getProgress() {
      let reqParams = {
        uid: this.currentPerson.uid
      };
      return new Promise(resolve => {
        APIPsy.getProgress(reqParams)
          .then(res => {
            const re = res.data;
            if (re.success) {
              if (re.response && re.response.state === -1) {
                resolve(false);
              } else if (re.response && re.response.initScaleState === 1 && re.response.progress === 1) {
                resolve(true);
              } else {
                resolve(false);
              }
            } else {
              resolve(false);
            }
          })
          .catch(() => {
            resolve(false);
          });
      });
    },
    //   获取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);
          });
      });
    },
    onScroll() {
      window.scrollTo({
        top: document.body.scrollHeight,
        left: 0,
        behavior: 'smooth'
      });
    },
    imgAreaClick() {
      this.conAreaShow = !this.conAreaShow;
    },
    imageListClick(item) {
      this.conAreaShow = false;
      this.$store.commit('personId', item.id);
      this.currentPerson = {};
      this.isPageShow = false;
      this.getPersonInfo(item.id, true);
    },
    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 + '';
    },
    // 获取指定天数的起始日期
    /**
     *
     * @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;
    },
    getCalendarData() {
      let currentDate = new Date();
      // 获取最近30天的心情等级日历数据
      let dateList = this.getPostDate(currentDate, 30, true);
      let reqParams = {
        uid: this.currentPerson.uid,
        startDate: dateList[0],
        endDate: dateList[1]
      };
      APIPsy.getCalendarData(reqParams).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];
        }
      });
    },
    // 格式化日期显示参数
    formatterDay(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;
    },
    // 选择日历具体某一个日期
    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);
      this.getComprehensiveEvaluation(selectDate);
    },
    onToBind(text) {
      // text 设备  用户
      if (text == '设备') {
        this.$router.push({
          name: 'deviceBinding',
          query: {
            from: 'health'
          }
        });
      } else if (text == '用户') {
        this.$router.push({
          name: 'userInfos',
          query: {
            from: 'health',
            showLeft: true
          }
        });
      }
    },
    // 根据类型，和数值计算使用什么颜色
    calcColorByTypeAndValue(type, value) {
      let color = '';
      const intValue = Number(value);
      if (!value) {
        return (color = '#189b3b');
      }
      if (type == 0) {
        // 心率
        if (intValue > 120) {
          color = '#ff5f8b';
        } else if (intValue < 40) {
          color = '#2ea7e0';
        } else {
          color = '#189b3b';
        }
      } else if (type == 1) {
        // 体温
        if (intValue >= 37.3) {
          color = '#ff5f8b';
        } else if (intValue <= 34) {
          color = '#2ea7e0';
        } else {
          color = '#189b3b';
        }
      } else {
        // 步数 2
        if (intValue >= 5000) {
          color = '#ff5f8b';
        } else if (intValue <= 3000) {
          color = '#2ea7e0';
        } else {
          color = '#189b3b';
        }
      }
      return color;
    },
    onSaveDiary() {
      if (this.$own.isNull(this.diary)) {
        return ToastService.fail({
          message: '日记内容不能为空'
        })
      }
      ToastService.loading();
      let reqBody = {
        personId: Number(this.$store.getters.personId),
        mood: "",
        content: this.diary
      };
      APIHealthUser.saveDiary(reqBody).then(res => {
        console.log("保存情绪日记结果", res);
        let data = res.data;
        if (data.stateCode === 1) {
          ToastService.success({
            message: '保存成功'
          })
        } else {
          ToastService.fail({
            message: `${data.message}`
          })
        }
      }).catch(e => {
        ToastService.fail({
          message: `${e.message}`
        })
      })
    },
    // TODO 实现表情输入
    onChange() {
      console.log("表情", this.result);
      // 获取当前光标位置
      let start = this.$refs.myTextarea.selectionStart;
      let end = this.$refs.myTextarea.selectionEnd;
      this.$refs.myTextarea.value = this.$refs.myTextarea.value.slice(0, start) + this.result + this.$refs.myTextarea.value.slice(end);
      this.$refs.myTextarea.setSelectionRange(start + 1, start + 1);
    }
  }
}
</script>

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