<template>
    <div class="psychological-container">
        <van-nav-bar :title="emoName + '监测'" :border="true"  :left-arrow="true" @click-left="onNavBack">
            <template #left>
                <van-icon name="arrow-left" size="24" style="padding: 0"/>
            </template>
        </van-nav-bar>
        <div class="main">
            <div class="top">
                <!-- 日期选择 -->
                <!-- TODO 后续可做成一个组件，方便调用 -->
                <div class="tab-bar">
                    <div class="date-tab-con">
                        <div class="date-tab-list">
                            <div
                                :class="['date-tab-item', {active: current === index, notClick: false}]"
                                @click="onTabClick(item.value, index)"
                                v-for="(item, index) in dateList"
                                :key="index"
                            >
                                <span>{{item.text}}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 标题 -->
                <div class="title">
                    <div class="title-left">{{ titleLeft }}<van-icon name="question-o" @click="onHelp"/></div>
                    <div class="title-right" v-show="currentDays === 0">
                        <p @click="onHistory">历史监测</p>
                    </div>
                </div>
                <!-- 日历 -->

                <van-dialog
                    class="calenddar-dialog"
                    v-model="calendarDialogShow"
                    :show-confirm-button="false"
                    :show-cancle-button="false"
                    :close-on-click-overlay="true"
                    ref="calenddarDialog"
                >
                    <template #default>
                        <div class="calendar" ref="calendarCon">
                            <van-calendar
                                v-model="calendarShow"
                                :min-date="minDate"
                                :max-date="maxDate"
                                :default-date="defaultDate"
                                :round="false"
                                :poppable="false"
                                color="#62BD48"
                                :show-confirm="false"
                                :show-title="false"
                                :show-subtitle="false"
                                :formatter="formatter"
                                @select="onSelect"
                            />
                        </div>
                    </template>
                </van-dialog>

                <!-- 监测次数 -->
                <div class="monitoring-count">
                    <p>监测次数：{{ monitoringCount || '0' }}次</p>
                </div>

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

                <div class="pie-chart-con">
                    <div class="pie-chart-left">
                        <div id="pieChart" ref="pieChart"></div>
                    </div>

                    <div class="pie-chart-right">
                        <div class="list">
                            <div class="item" v-for="(item, index) in pieRightList" :key="index">
                                <div class="item-left">
                                    <div class="circle" :style="{backgroundColor: item.color}"></div>

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

                                <div class="item-right">
                                    <span :style="{color: item.color}">{{ item.count ? item.count + '次' : '0次'}}</span>
                                    <label :style="{color: item.color}">{{ item.percentage ? '(' + item.percentage + '%'  + ')' : '(0%)'}}</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 统计 -->

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

                            <div class="middle">
                                <span
                                    :style="{ color: calcColor(item.value)}"
                                >{{ item.value || '--' }}</span>
                            </div>

                            <div class="bottom">
                                <span>{{ item.time || '--' }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 分割线 -->

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

            <!-- 底部 -->

            <div class="bottom">
                <div class="echart-container">
                    <div class="echart" ref="charts"></div>
                </div>

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

                <div class="result" v-if="monitoringCount == ''">
                    <div class="result-con">
                        <div class="title ">
                            <span class="title-no-data">结果解读</span>
                            <div class="no-data">
                                <img src="../../../assets/img/no_data_01.png" alt />
                                <p>暂无数据</p>
                            </div>
                        </div>
                    </div>
                </div>

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

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

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

                        <div class="friendly-reminder" v-if="emoType === 2">
                            <p :style="{color: currentColor}">友情提示：</p>
                            <span>如果您发现抑郁倾向分值升高或处于轻度水平，不需要过度紧张，这可能是由正常的情绪波动或者生活习惯（睡眠时间、运动量等）的改变造成的。如果您发现抑郁倾向分值连续7天及以上处于中度或重度水平，建议您寻求家人朋友或心理咨询师的帮助，及早进行干预。</span>
                        </div>

                        <div class="warm-reminder">
                            <p :style="{color: currentColor}">温馨提示：</p>
                            <span>{{ warmTips }}</span>
                        </div>
                    </div>

                    <div class="result-con" v-show="current > 0">
                        <div class="title">
                            <span class="title-text">{{ surveyTitle }}</span>
                            <div class="mood-list" v-if="emotionList.length > 0">
                                <div class="item" v-for="(item, index) in emotionList" :key="index">
                                    <p>
                                        <span
                                            :style="{color: item.color}"
                                            class="day"
                                        >{{ item.days }}</span>
                                        <span class="day-text">天</span>
                                    </p>

                                    <p>{{ item.text }}</p>
                                </div>
                            </div>
                            <div class="mood-list-no-data" v-else>
                                <div class="no-data">
                                    <img src="../../../assets/img/no_data_01.png" alt />
                                    <p>暂无数据</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!--  -->
            </div>
        </div>
        <!-- 弹出层 -->
        <van-popup v-model="isPopup">
            <div class="popup">
                <div class="item science-tips first" v-if="emoType === 2">
                    <div class="tips"><h5>小科普</h5></div>
                    <p>抑郁症是一种心理疾病，严重时可发展为精神障碍。然而当我们体会到了痛苦、悲伤、和郁闷等负面情绪，并不意味着我们就是抑郁症。日常的短时的喜、怒、哀、乐，都是正常的情绪变化，然而长期的低落情绪、兴趣缺失等可能会让我们有抑郁的风险。</p>
                </div>
                <div class="item" >
                    <h5 v-html="title1"></h5>
                    <div v-html="article1"></div>
                </div>
                <div class="item">
                    <h5 v-html="title2"></h5>
                    <div v-html="article2"></div>
                </div>
                <van-button size="large" @click="onClose">返回</van-button>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { EmotionModel } from "@/config/models";
import axios from "axios";
export default {
    name: "psychological-monitor",
    data() {
        return {
            // 日期选择标签
            dateList: [
                { name: "today", text: "今天", value: 0 },
                { name: "week", text: "7天", value: 7 },
                { name: "month", text: "30天", value: 30 }
            ],
            current: 0, // 日期选择标签-当前选中的标签
            currentDays: 0, //日期选择标签-日期参数
            emotionData: [], //情绪数据，TODO 接口对接
            echarts: null, //折线图
            itemHeight: Number(
                ((document.body.clientWidth / 750) * 95).toFixed()
            ), // 日历组件item高度
            xAxisData: [], //图表x轴展示的数据
            monitoringCount: "", //监测次数
            pieEcharts: null, //饼状图
            pieData: [], //饼状图数据
            //饼状图右边数据,TODO 根据接口数据和 模块 重新封装数组
            pieRightList: [
                /* {
                    text: "无情绪倾向",
                    count: 12,
                    percentage: "80",
                    color: "#62BD48"
                },
                {
                    text: "轻度情绪倾向",
                    count: 2,
                    percentage: "80",
                    color: "#ffde00"
                },
                {
                    text: "中度情绪倾向",
                    count: 1,
                    percentage: "80",
                    color: "#ff8a00"
                },
                {
                    text: "重度情绪倾向",
                    count: 1,
                    percentage: "80",
                    color: "#d70d0d"
                } */
            ],
            // 情绪状态列表
            statisticsList: [
               /*  { label: "最大值", value: "75", time: "08:15" },
                { label: "最小值", value: "40", time: "10:15" },
                { label: "最近值", value: "50", time: "18:15" } */
            ],
            // 周报-情绪计算
            emotionList: [
               /*  { days: "5", text: "无情绪倾向", color: "#62BD48" },
                { days: "4", text: "轻度情绪倾向", color: "#ffde00" },
                { days: "3", text: "中度情绪倾向", color: "#ff8a00" },
                { days: "2", text: "重度情绪倾向", color: "#ACACAC" } */
            ],
            // 弹窗-日历是否显示
            calendarDialogShow: false,
            // 日历是否显示，默认为true
            calendarShow: true,
            // 日历 默认最小可选择日期，默认为最近1个月
            minDate: new Date(
               this.$dayjs()
                    .month(this.$dayjs().month() - 1)
                    .hour(0)
                    .minute(0)
                    .second(0)
                    .format()
            ),
            // 日历 默认最小可选择日期，默认为当前时间
            maxDate: new Date(
                this.$dayjs()
                    .hour(0)
                    .minute(0)
                    .second(0)
                    .format()
            ),
            // 默认日历日期时间
            defaultDate: new Date(
                this.$dayjs()
                    .hour(0)
                    .minute(0)
                    .second(0)
                    .format()
            ),
            // 路由传过来的情绪参数
            emoName: null,
            // 默认折线图 Series 配置
            defaultSeries: null,
            // 非日报折线图 Series 配置
            weekAndMonthSeries: null,
            // 当前情绪类型
            emoType: null,
            // 结果解读
            result: "",
            // 需要高亮的日期数组
            highlightDates: [],
            // 选中的日历日期
            selectDate: '',
            uid: '',
            // 建议
            advice: '',
            // 底部天数标题
            surveyTitle: '' || '7天概览',
            // 路由中的日期
            routeDate: '',
            // 路由参数
            params: {},
            // 是否显示帮助
            isPopup: false,
            // 结果等级
            resultLevel: '',
            // 轻度级别颜色
            mildColor: '#ffde00',
            // 中度级别颜色
            severeColor: '#ff8a00',
            // 重度级别颜色
            moderateColor: '#d70d0d',
            // 7天和30天最大数据列表
            weekAndMonData: [],
        };
    },
    computed: {
        // 默认折线图配置，echarts 具体配置 见 https://echarts.apache.org/zh/option.html#title
        defaultOptions() {
            return {
                time: {
                    useUTC: false
                },
                title: {
                    text: this.echartsTitle,
                    left: 1,
                    right: 25,
                    bottom: 20,
                    top: "3%",
                    textStyle: {
                        fontSize: 16,
                        fontWeight: "bold"
                    }
                },
                legend: {
                    width: "65%",
                    orient: "horizontal",
                    right: 'right',
                    top: 1,
                    bottom: "1%",
                    itemHeight: 12,
                    itemWidth: 12,
                    itemGap: 10,
                    align: 'left',
                    selectedMode: false,
                    data: [

                        {
                            name: `轻度${this.emoName}倾向`,
                            icon: "rect",
                            itemStyle: {
                                color: "#ffde00"
                            },
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        {
                            name: `中度${this.emoName}倾向`,
                            itemStyle: {
                                color: "#ff8a00"
                            },
                            icon: "rect",
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        {
                            name: `重度${this.emoName}倾向`,
                            itemStyle: {
                                color: "#d70d0d",
                            },
                            icon: "rect",
                            textStyle: {
                                fontSize: 12
                            }
                        },
                        {
                            name: `无${this.emoName}倾向`,
                            icon: "rect",
                            itemStyle: {
                                color: "#62BD48"
                            },
                            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: '10%',
                    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: 15,
                        bottom: 5,
                        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: ""
                    }
                ]
            };
        },
        imei() {
            return this.$store.getters.serialNo;
        },
        // 饼状图配置
        pieOption() {
            return {
                tooltip: {
                    trigger: "item",
                    textStyle: {
                        fontSize: 14
                    },
                    position: "right"
                },
                legend: {
                    top: "5%",
                    left: "center",
                    show: false
                },
                series: [
                    {
                        type: "pie",
                        radius: ["40%", "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
                    }
                ]
            };
        },
        titleLeft() {
            let text = this.emoName === 'depression' ? '趋势' : '';
            let today = '';
            if(this.currentDays  !== 0) {
                today = '';
            } else {
                today = this.$dayjs(this.selectDate || this.defaultDate).format("YYYY-MM-DD") === this.$dayjs(new Date()).format("YYYY-MM-DD") ? '今天' : '';
            }
            return `${today}${this.emoName}倾向${text}`;
        },
        // 折线图标题
        echartsTitle() {
            let today = '';
            if(this.currentDays  !== 0) {
                today = '';
            } else {
                today = this.$dayjs(this.selectDate || this.defaultDate).format("YYYY-MM-DD") === this.$dayjs(new Date()).format("YYYY-MM-DD") ? '今天' : '';
            }
            return `${today}${this.emoName}数据图`;
        },
        warmTips() {
            return `正常连续佩戴手表，每半小时计算一个${this.emoName}分值，睡眠期间不进行计算。`
        },
        title1() {
            return EmotionModel[this.params.name].title1;
        },
        article1() {
            return EmotionModel[this.params.name].article1;
        },
        title2() {
            return EmotionModel[this.params.name].title2;
        },
        article2() {
            return EmotionModel[this.params.name].article2;
        },
        // 当前情绪颜色
        currentColor( ) {
            return this.calcResultColor(this.resultLevel) || "#62BD48"
        },
    },
    watch: {
        // 监听数据发生变化 初始化各项图表
        emotionData: {
            handler(n, o) {
                this.initEchart();
            },
            deep: true
        },
        xAxisData: {
            handler(n, o) {
                this.initEchart();
            },
            deep: true
        },
        pieData: {
            handler(n, o) {
                this.initPieEchart();
            },
            deep: true
        },
    },
    created() {
        // 读取路由传过来的参数，根据路由传过来的参数判断是哪种情绪
        this.loadParams();
        this.initEchartText();
        this.getPieData();
        this.getCalendarData();
        this.getPsychologiclData();
    },
    mounted() {
        this.initEchart();
        window.document.title = '心理监测';
    },
    methods: {
        loadParams() {
            let params = this.$route.query;
            if (params) {
                this.emoName = EmotionModel[params.name].name;
                this.emoType = EmotionModel[params.name].type;
                this.uid = params.uid;
                this.routeDate = params.date;
                this.params = params;
                if(params.date) {
                    this.dateList[0].text =  this.$dayjs(params.date).format("YYYY-MM-DD") === this.$dayjs(new Date()).format("YYYY-MM-DD") ? '今天' : this.$dayjs(params.date).format("MM-DD");
                    this.defaultDate = new Date(
                        this.$dayjs(params.date)
                            .hour(0)
                            .minute(0)
                            .second(0)
                            .format()
                    );
                }
            }
        },
        // 获取这个月中有数据的日期，控制日历组件的日期样式
        getCalendarData() {
            let currentDate = new Date();
            // 获取最近30天的心情等级日历数据
            let dateList = this.getPostDate(currentDate, 30, true);
            let reqUrl = `https://dbmq.rzliot.com/auth_heart/api/Data/GetCalendarData`;
            let reqParams = {
                uid: this.uid,
                startDate: dateList[0],
                endDate: dateList[1],
            };
            axios.get(reqUrl, {
                params: { ...reqParams },
                headers: { 'AccessToken': this.$store.getters.ssjlToken }
            }).then(res => {
                    if (res.data) {
                        let data = res.data.response;
                        // const mergedArr = [...new Set([...arr1, ...arr2, ...arr3])];
                        /* let name = this.params.name.charAt(0).toUpperCase()+ this.params.name.slice(1); */
                        let currentName = this.params.name;
                        let list = [];
                        if(currentName === 'stress') {
                            list = data.Stress;
                        } else if(currentName === 'depression') {
                            list = data.Depression;
                        } else {
                            list = data.Tiredness;
                        }
                        list = list.map(item =>{
                            item.Date = this.$dayjs(item.Date.replace(/-/g, "/")).format(
                                "YYYY/MM/DD"
                            );
                            return item;
                        })
                        this.highlightDates = [...list];
                    }
            })

        },
        // 获取饼状图数据，TODO 对接接口数据
        getPieData() {
            this.pieData = [
                { value: 12, name: "", itemStyle: { color: "green" } },
                { value: 2, name: "", itemStyle: { color: "orange" } },
                { value: 1, name: "", itemStyle: { color: "#FFC0CB" } },
                { value: 1, name: "", itemStyle: { color: "red" } }
            ];
        },
        // 获取情绪数据
        getPsychologiclData(date, startDate, endDate) {

            this.$toast.loading({
                message: '数据加载中'
            });
            let reqDate =
                date
                ? this.$dayjs(date).format("YYYY-MM-DD")
                : this.routeDate || this.$dayjs(this.defaultDate).format("YYYY-MM-DD") /* "2023-05-23" */;
            let reqParams = {
                uid: this.uid,
                startDate: startDate || reqDate,
                endDate: endDate || reqDate,
                type: this.emoType
            };
            console.log("请求参数", reqParams);
            let reqUrl = `https://dbmq.rzliot.com/auth_heart/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: "#62BD48"
                        };
                        let Mild = {
                            count: data.Mild,
                            percentage: this.calcPercentage(
                                data.Mild,
                                data.Count
                            ),
                            text: `轻度${this.emoName}倾向`,
                            color: "#ffde00"
                        };
                        let Moderate = {
                            count: data.Moderate,
                            percentage: this.calcPercentage(
                                data.Moderate,
                                data.Count
                            ),
                            text: `中度${this.emoName}倾向`,
                            color: "#ff8a00"
                        };
                        let Severe = {
                            count: data.Severe,
                            percentage: this.calcPercentage(
                                data.Severe,
                                data.Count
                            ),
                            text: `重度${this.emoName}倾向`,
                            color: "#d70d0d"
                        };
                        // 饼状图右边数据
                        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")
                                : ""
                        };
                        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")
                                : ""
                        };
                        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")
                                : ""
                        };
                        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: "#62BD48"
                        };
                        let MildDay = {
                            days: data.MildDay,
                            text: `轻度${this.emoName}倾向`,
                            color: "#ffde00"
                        };
                        let ModerateDay = {
                            days: data.ModerateDay,
                            text: `中度${this.emoName}倾向`,
                            color: "#ff8a00"
                        };
                        let SevereDay = {
                            days: data.SevereDay,
                            text: `重度${this.emoName}倾向`,
                            color: "#d70d0d"
                        };
                        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: {
                                    color: 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 emphasisStyle = {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowColor: 'rgba(0,0,0,0.3)'
                                }
                            };
                            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,
                                    },
                                },
                            ];
                            // 点击提示此时为空
                            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;
                        this.$toast.success({
                            message: '数据加载完成'
                        });
                    }
                }).catch(() => {
                   this.$dialog({
                        message: '登录过期，请重新进入'
                    })
                }).finally(() => { });
        },
        // 计算百分比
        calcPercentage(value, total) {
            if (
                typeof value !== "number" ||
                typeof total !== "number" ||
                total === 0
            ) {
                return 0;
            }
            let milValue = value * 1000;
            let milTotal = total * 1000;
            return Math.round((milValue / milTotal) * 100);
        },
        // 初始化图表的文字内容
        initEchartText() {
            let text = this.emoName === 'depression' ? '趋势' : '';
            let today = this.$dayjs(this.defaultDate).format("YYYY-MM-DD") === this.$dayjs(new Date()).format("YYYY-MM-DD") ? '今天' : '';
            this.result = `无${this.emoName}倾向`;
            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: ""
                    }
            ];
            this.pieRightList = this.pieRightList.map(item => {
                item.text = item.text.replace("情绪", this.emoName);
                return item;
            });
        },
        // 初始化饼状图
        initPieEchart() {
            if (
                this.pieEcharts != null &&
                this.pieEcharts != "" &&
                this.pieEcharts != undefined
            ) {
                this.pieEcharts.dispose();
            }
            this.pieEcharts = this.$echarts.init(this.$refs.pieChart);
            this.pieEcharts.setOption(this.pieOption);
        },
        // 格式化日期显示参数
        formatter(day) {
            const month = day.date.getMonth() + 1;
            const date = day.date.getDate();
            const formatDate = this.$dayjs(day.date).format("YYYY/MM/DD");
            const currentDate = this.$dayjs(new Date()).format("YYYY/MM/DD");
            day.className = "custom-calendar";
            for( let h = 0; h < this.highlightDates.length; h ++) {
                if (this.highlightDates[h].Date === formatDate) {
                    day.className = `highlight-border ${this.calcResultColor(this.highlightDates[h].SummaryLevel, true)}`;
                } else if (formatDate === currentDate) {
                    day.text = '今天'
                }
            }
            return day;
        },
        //   返回
        onNavBack() {
            this.params.name = '';
            this.$router.replace({
                name: 'psychologicalMain',
                query: {
                    ...this.params
                }
            });
        },
        // 点击日期选择
        onTabClick(value, index) {
            this.current = index;
            this.currentDays = value;
            let currentDate = new Date();
            let leftText = value === 0 ? '今天' : value === 7 ? '7天' : '30天';
            this.surveyTitle = value === 7 ? '7天概览' : '30天概览';
            if (value === 7) {
               /*  this.defaultOptions.xAxis.data = [
                    "周一",
                    "周二",
                    "周三",
                    "周四",
                    "周五",
                    "周六",
                    "周日"
                ]; */
                //this.defaultOptions.xAxis.data = this.xAxisData;
                let dateList = this.getPostDate(currentDate, 6, true);
                console.log("dateList", dateList);
                this.getPsychologiclData('', dateList[0], dateList[1]);
            } else if (value === 0) {
                // 今天
                this.defaultOptions.xAxis.data = this.xAxisData;
                this.defaultOptions.series = this.defaultSeries;
                this.defaultOptions.series[0].data = this.emotionData;
                this.getPsychologiclData(this.selectDate ?  this.selectDate : this .$dayjs(currentDate).format("YYYY-MM-DD"));
            } else {
                // 30天
                this.defaultOptions.xAxis.data = this.xAxisData;
                this.defaultOptions.series = this.defaultSeries;
                this.defaultOptions.series[0].data = this.emotionData;
                let dateList = this.getPostDate(currentDate, 30, true);
                console.log("dateList", dateList);
                this.getPsychologiclData('', dateList[0], dateList[1]);
            }
        },
        getCurrentMonthStaAndEnd(currentDate) {
            let list = [];
            let monthStart = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); // 获取本月第一天的日期时间
            let monthEnd = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0, 23, 59, 59); // 获取本月最后一天的日期时间（时间为23:59:59）
            list.push(this.$dayjs(monthStart).format("YYYY-MM-DD"));
            list.push(this.$dayjs(monthEnd).format("YYYY-MM-DD"));
            return list;
        },
        // 获取指定天数的起始日期
        /**
         *
         * @param dateNow :Date类
         * @param intervalDays ：间隔天数
         * @param bolPastTime  ：Boolean,判断在参数date之前，还是之后，
      */
        getPostDate(dateNow,intervalDays,bolPastTime) {
            let oneDayTime = 24 * 60 * 60 * 1000;
            let list = [];
            let lastDay;

            if(bolPastTime == true){
                lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
                list.push(this.formateDate(lastDay));
                list.push(this.formateDate(dateNow));
            }else{
                lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
                list.push(this.formateDate(dateNow));
                list.push(this.formateDate(lastDay));
            }
            return list;
        },
        formateDate(time){
            let year = time.getFullYear();
            let month = time.getMonth() + 1;
            let day = time.getDate();
            if (month < 10) {
                month = '0' + month
            };
            if (day < 10) {
                day = '0' + day
            };
            return year + '-' + month + '-' + day + '';
        },
        // 字体大小转化
        fontChar(res) {
            const clientWidth =
                window.innerWidth ||
                document.documentElement.clientWidth ||
                document.body.clientWidth;
            if (!clientWidth) return;
            let fontSize = clientWidth / 750;
            return res * fontSize;
        },
        // 初始化折线图表
        initEchart() {
            if (
                this.echarts != null &&
                this.echarts != "" &&
                this.echarts != undefined
            ) {
                this.echarts.dispose();
            }
            this.echarts = this.$echarts.init(this.$refs.charts);
            this.echarts.setOption(this.defaultOptions);
        },
        // 点击历史监测，打开日历
        onHistory() {
            this.calendarDialogShow = true;
        },
        // 选择日历具体某一个日期
        onSelect(value) {
            const selectDate = this.$dayjs(value).format("YYYY-MM-DD");
            this.dateList[0].text = this.$dayjs(value).format("YYYY-MM-DD") === this.$dayjs(new Date()).format("YYYY-MM-DD") ? '今天' : this.$dayjs(value).format("MM-DD");
            this.calendarDialogShow = false;
            this.selectDate = selectDate;
            this.getPsychologiclData(selectDate);
        },
        // 计算字体显示的颜色
        calcColor(value) {
            let color = "";
            if (value <= 40) {
                color = "#62BD48";
            } else if (value > 40 && value <= 65) {
                color = "#ffde00";
            } else if (value > 65 && value <= 80) {
                color = "#ff8a00";
            } else if (value > 80) {
                color = "#d70d0d";
            } else {
                color = "";
            }
            return color;
        },
        // 计算结果采用哪种颜色
        calcResultColor(value, isCallBackClass) {
            let color = "";
            let className = "";
            switch(value) {
                case '0':
                    color = "#62BD48";
                    className = 'none';
                break;
                case '1':
                    color = "#ffde00";
                    className = 'mild';
                break;
                case '2':
                    color = "#ff8a00";
                    className = 'moderate';
                break;
                case '3':
                    color = "#d70d0d";
                    className = 'severe';
                break;
            }
            return isCallBackClass ? className : color;
        },
        // 点击帮助
        onHelp() {
            this.isPopup = true;
        },
        // 关闭poup
        onClose() {
            this.isPopup = false;
        }
    }
};
</script>

<style lang="scss">
.van-nav-bar .van-icon {
    padding-left: 10px;
}

.calenddar-dialog {
    overflow: scroll;
}
.calendar {
    overflow: scroll;
    .van-calendar {
        height: 350px;
        .van-calendar__header {
            display: none;
        }
        .van-calendar__days .van-calendar__day {
            width: 27px;
            height: 27px;
            margin: 5px;
            font-size: 12px;
            &.custom-calendar {
                width: 27px;
                height: 27px;
            }
            &.highlight-border {
                border: 1px solid #62bd48;
                width: 27px;
                height: 27px;
                border-radius: 50%;
                &.none {
                    border: 1px solid #62bd48;
                }
                &.mild {
                    border: 1px solid #ffde00;
                }
                &.moderate {
                    border: 1px solid #ff8a00;
                }
                &.severe {
                    border: 1px solid #d70d0d;
                }
            }
        }
        .van-calendar__selected-day {
            width: 27px;
            height: 27px;
            border-radius: 50%;
            font-size: 12px;
        }
    }
}
</style>
<style scoped lang="scss">
@import "./index.scss";
</style>