<!--
 * @Date: 2023-10-10 15:29:50
 * @LastEditors: JinxChen
 * @LastEditTime: 2023-10-19 14:21:55
 * @FilePath: \TelpoH5FrontendWeb\src\views\gps-card-frontend\device-power\index.vue
 * @description:
-->
<template>
    <div class="device-power">
        <van-nav-bar :left-arrow="true" @click-left="onNavBack">
            <template #left>
                <van-icon name="arrow-left" size="24" style="padding: 0"/>
                <span>返回</span>
            </template>
        </van-nav-bar>
        <div class="top">
            <p>查看数据</p>
        </div>
        <div class="action">
            <div class="left">
                <van-dropdown-menu>
                    <van-dropdown-item style="min-width: 150px" v-model="dayValue" :options="dayOption" @change="onChange" />
                </van-dropdown-menu>
            </div>
            <div class="right">
                <div class="btn-container">
                    <van-button :class="['btn', {active: btnActive ===item.index }]" @click="onClickBtn(item.index)" v-for="(item, index) in btnList" :key="index">{{ item.text }}</van-button>
                </div>
            </div>
        </div>
        <div class="details-container" v-if="btnActive === 0 && data.length > 0 || tableData.length > 0 && btnActive === 1">
            <Echart :option="chartOption" v-show="btnActive === 0"/>
            <Table :columns="titleList" :data="tableData" v-show="btnActive === 1"/>
        </div>
        <div class="details-container no-data" v-else>
            <van-empty image="error" description="暂无数据" />
        </div>
    </div>
</template>

<script>
import Echart from '@/components/echarts';
import Table from '@/components/tables';
import APIIot from '@/api/iot';
import { DEVICE_POWER } from "@/config/models";
import axios from 'axios';
export default {
  name:'',
  components: { Echart,Table },
  data(){
   return {
       dayValue: 7,
       dayOption: [
           { text: '7天', value: 7 },
           { text: '30天', value: 30 },
       ],
       btnList: [
           { text: '图表', index: 0 },
           { text: '表格', index: 1 },
       ],
       btnActive: 0,
       chartOption: {},
       titleList: [
           { title: '时间', width: '40%', key: 'time'},
           { title: '原始值', width: '60%', key: 'value' },
       ],
       tableData: [],
       echarts: {
           title: '',
           type: '',
       },
       data: [],
       xAxisData: [],
       filterData: [],
       yAxisObject: {}
   }
  },
  created() {

  },
  mounted() {
    this.loadParams();
  },
  methods: {
    loadParams() {
        let params = this.$route.query;
        if(params) {
            this.echarts.title = DEVICE_POWER[params.title].title;
            this.echarts.type = DEVICE_POWER[params.title].value;
            // 获取接口数据
            this.getData();
        } else {
            // todo跳转404页面
        }
    },
    getData() {
        this.$toast.loading();
        let reqBody = {
            days: String(this.dayValue),
            identifier: this.echarts.type,
            imei: /* '861281060086216' *//* '862838050029479' */this.$store.getters.imei
        };
        // 线上地址
       let baseUrl = process.env.VUE_APP_BASE_API;
       let reqUrl = `${baseUrl}iotservice/getdeviceinfo`;
        // 开启代理如下
       /* let reqUrl = `/api/id/getdeviceinfo`; */
        axios.post(`${reqUrl}`, reqBody).then(res => {
            let data = res.data;
            if(data.code === 200) {
                if(this.echarts.type === 'BatteryLevel' || this.echarts.type === 'status') {
                    this.filterData = data[this.echarts.type].data/* .list.propertyInfo */;
                } else if(this.echarts.type === 'offline') {
                    this.filterData = data.Offline.data;
                }
                if(this.echarts.type === 'status') {
                    // 信号强度
                    this.yAxisObject = {
                        type: "value",
                        /* max: 4,
                        min: 0,
                        interval: 1,
                        splitNumber : 1,
                        boundaryGap : [ '5%', '5%' ], */
                    }
                    this.titleList = [
                        { title: '时间', width: '40%', key: 'time'},
                        { title: '原始值', width: '60%', key: 'value' },
                    ];
                    let propertyInfo = this.filterData.map(item => {
                        return item.list.propertyInfo;
                    });
                    let result = [];
                    for (let i = 0; i < propertyInfo.length; i++) {
                        // 循环对象中的数组
                        result = [].concat(...propertyInfo)
                    }
                    // 表格则要显示全部数据
                    this.tableData = result.map(item => {
                        return {
                            value: item.value,
                            time: this.$dayjs(this.$dayjs(Number(item.time))).format("YYYY/MM/DD hh:mm")
                        }
                    }).reverse();
                    // 图表筛选过滤只显示 rssi <= 2的数据
                    this.data = result.map(item => {
                        // 序列化json
                        let json = JSON.parse(item.value);
                        return {
                            value: json.rssi,
                            time: this.$dayjs(this.$dayjs(Number(item.time))).format("YYYY/MM/DD hh:mm"),
                            type: 'status'
                        }
                    }).filter(f => {
                        return f.value  <=2;
                    })
                } else if (this.echarts.type === 'offline') {
                    // 设备离线次数
                    this.titleList = [
                        { title: '时间', width: '60%', key: 'time'},
                        { title: '离线次数', width: '40%', key: 'value' },
                    ],
                    this.yAxisObject = {
                        type: "value",
                      /*   max: 10,
                        min: 0,
                        interval: 1,
                        splitNumber : 1,
                        boundaryGap : [ '5%', '5%' ], */
                    };
                    this.data = this.filterData.map(item => {
                        return {
                            /* value: item.value, */
                            time: item.createTime.slice(0,10),
                            day: item.createTime.slice(0,10),
                            type: 'offline'
                        }
                    }).reduce((accumulator, currentValue) => {
                        if (accumulator.find(obj => obj.day === currentValue.day)) {
                            accumulator.find(obj => obj.day === currentValue.day).value++;
                        } else {
                            accumulator.push({ day: currentValue.day, time: currentValue.time, value: 1, type: 'offline' });
                        }
                        return accumulator;
                    }, []).sort(function(date1, date2) {
                        // 日期升序排序
                        return date2.time < date1.time ? 1 : -1
                    });
                    this.tableData = this.filterData.map(item => {
                        return {
                            /* value: item.value, */
                            time: item.createTime.slice(0,10),
                            day: item.createTime.slice(0,10)
                        }
                    }).reduce((accumulator, currentValue) => {
                        // 筛选遍历数据，获取相同日期的数据，计算出现的次数后重新累加组合到一个新的数组里面
                        if (accumulator.find(obj => obj.day === currentValue.day)) {
                            accumulator.find(obj => obj.day === currentValue.day).value++;
                        } else {
                            accumulator.push({ day: currentValue.day, time: currentValue.time, value: 1 });
                        }
                        return accumulator;
                    }, []).sort(function(date1, date2) {
                        // 日期升序排序
                        return date2.time < date1.time ? 1 : -1
                    }).reverse();
                } else {
                    this.titleList = [
                        { title: '时间', width: '40%', key: 'time'},
                        { title: '电量', width: '60%', key: 'value' },
                    ],
                    this.yAxisObject = {
                        type: "value",
                        max: 100,
                        min: 0,
                        interval: 20,
                        splitNumber : 1,
                        boundaryGap : [ '5%', '5%' ],
                    }
                    let propertyInfo = this.filterData.map(item => {
                        return item.list.propertyInfo;
                    });
                    let result = [];
                    for (let i = 0; i < propertyInfo.length; i++) {
                        // 循环对象中的数组
                        result = [].concat(...propertyInfo)
                    }
                    this.data = result.map(item => {
                        return {
                            value: item.value,
                            time: this.$dayjs(this.$dayjs(Number(item.time))).format("YYYY/MM/DD hh:mm"),
                        }
                    });
                    this.tableData = result.map(item => {
                        return {
                            value: item.value,
                            time: this.$dayjs(this.$dayjs(Number(item.time))).format("YYYY/MM/DD hh:mm")
                        }
                    }).reverse();
                }
                this.xAxisData = this.data.map(item => {
                    return this.$dayjs(item.time).format("MM/DD");
                })
                this.chartOption = {
                    title: {
                        text: this.echarts.title,
                    },
                    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
                    },
                    yAxis: this.yAxisObject,
                    series: [
                        {
                            type: "line",
                            data: this.data,
                            /* areaStyle: {}, */
                        },
                    ],
                    dataZoom: [
                        {
                            start: 0,
                            end: 100,
                            textStyle: {
                                color: "#FFF",
                                fontSize: 14
                            },
                            show: true,
                            height: 20,
                            bottom: 5,
                            handleStyle: {
                                borderWidth: 1,
                                borderCap: "square"
                            }
                        }
                    ],
                    tooltip: {
                        trigger: "axis",
                        textStyle: {
                            fontSize: 14,
                            align: "center"
                        },
                        formatter: function(params) {
                            return `${params[0].marker}${params[0].data.time}</br>
                            ${ params[0].data.type === 'offline' ? '离线次数:' + params[0].data.value + '次' :
                            params[0].data.type === 'status' ? 'rssi值:' +  params[0].data.value :
                            '电量:' + params[0].data.value}`
                        }
                    },
                }
            }
        }).catch(() => {

        }).finally(() => {
            this.$toast.clear();
        })
    },
    onClickBtn(value) {
        this.btnActive = value;
        this.getData();
    },
    onChange(value) {
        this.dayValue = value;
        this.getData();
    },
    onNavBack() {
        this.$router.push({
            name: 'deviceSetting'
        })
    }
  }
}
</script>

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