<template>
    <div class="data-center-history-wrap">
        <el-drawer :title="title" :visible.sync="drawer" size="50%">
            <div class="device-wrap">
                <el-form :model="devQueryParams" ref="devQueryForm" :inline="true" label-width="68px">
                    <el-form-item prop="dayDaterange" style="margin-left: 20px">
                        <el-date-picker
                            style="width: 340px"
                            v-model="devQueryParams.dayDaterange"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            type="datetimerange"
                            range-separator="-"
                            :start-placeholder="$t('dataCenter.history.384934-6')"
                            :end-placeholder="$t('dataCenter.history.384934-7')"
                            :picker-options="pickerOptions"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDevQuery">{{ $t('dataCenter.history.384934-8') }}</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="handleDevResetQuery">{{ $t('dataCenter.history.384934-9') }}</el-button>
                    </el-form-item>
                </el-form>

                <el-row>
                    <el-col :span="24" style="margin-bottom: 15px">
                        <el-card v-loading="loading" shadow="never">
                            <div slot="header">
                                <span>{{ $t('dataCenter.history.384934-10') }}</span>
                                <span style="margin-left: 10px; color: #f56c6c; font-size: 12px">{{ $t('dataCenter.history.384934-11') }}</span>
                            </div>
                            <div class="el-table--enable-row-hover el-table--medium">
                                <div v-show="devDatas.length !== 0" ref="devLineChart" style="width: 100%; height: 480px; background: #fff"></div>
                                <el-empty v-if="devDatas.length === 0" style="height: 480px" :description="$t('dataCenter.history.384934-12')"></el-empty>
                                <el-table v-show="devTotal > 0" style="margin-top: 50px" :data="devTableList" :border="false">
                                    <el-table-column :label="$t('dataCenter.history.384934-13')" prop="time" width="200" />
                                    <el-table-column v-for="item in this.devTableHeaderTemp" :key="item.value" :label="item.name" :prop="item.value" />
                                </el-table>
                                <pagination v-show="devTotal > 0" :autoScroll="false" :total="devTotal" :page.sync="devPageNum" :limit.sync="devPageSize" />
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import moment from 'moment';
import { getDataCenterDeviceHistory, getDataCenterSceneHistory } from '@/api/data/center.js';

export default {
    name: 'dataCenterHistory',
    props: {
        model: {
            type: Object,
            default: null,
        },
    },
    data() {
        return {
            activeTab: 'device',
            drawer: false,
            title: '历史数据',
            devDeviceList: [], // 设备-设备列表
            devIdentifierList: [],
            pickerOptions: {
                shortcuts: [
                    {
                        text: this.$t('dataCenter.history.384934-19'),
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 2);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                    {
                        text: this.$t('dataCenter.history.384934-20'),
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                    {
                        text: this.$t('dataCenter.history.384934-21'),
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                    {
                        text: this.$t('dataCenter.history.384934-22'),
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                ],
            },
            // 查询参数
            devQueryParams: {
                deviceId: null,
                identifiers: [],
                dayDaterange: [new Date(new Date().getTime() - 3600 * 1000 * 2), new Date()],
            },
            loading: false,
            devDatas: [], // 设备列表数据
            devTableComTemp: [], // 设备列表table数据
            devTableHeaderTemp: [], // 设备列表table数据
            devPageNum: 1,
            devPageSize: 10,
            devTotal: 0,
            sceneModelList: [], // 场景列表
            sceneDeviceList: [],
            sceneIdentifierList: [], // 场景变量
            sceneQueryParams: {
                sceneModelId: null,
                sceneModelDeviceId: null,
                identifiers: [],
                dayDaterange: [new Date(new Date().getTime() - 3600 * 1000 * 2), new Date()],
            },
            sceneDatas: [], // 场景列表数据
            sceneTableComTemp: [], // 设备列表table数据
            sceneTableHeaderTemp: [], // 设备列表table数据
            scenePageNum: 1,
            scenePageSize: 10,
            sceneTotal: 0,
        };
    },
    mounted() {},
    computed: {
        devTableList() {
            const start = (this.devPageNum - 1) * this.devPageSize;
            const end = start + this.devPageSize;
            return this.devTableComTemp.slice(start, end);
        },
    },
    methods: {
        // 获取设备图形数据
        getDevChartDatas() {
            this.loading = true;
            const identifierList = [{ identifier: this.model.identifier, type: this.model.type }];
            const params = {
                deviceId: this.model.deviceId,
                serialNumber: this.model.serialNumber,
                identifierList: identifierList,
                beginTime: moment(this.devQueryParams.dayDaterange[0]).format('YYYY-MM-DD HH:mm:ss'),
                endTime: moment(this.devQueryParams.dayDaterange[1]).format('YYYY-MM-DD HH:mm:ss'),
            };
            getDataCenterDeviceHistory(params).then((res) => {
                if (res.code === 200) {
                    this.devDatas = res.data;
                    this.formatDevTableDatas();
                    if (this.devDatas.length !== 0) {
                        setTimeout(() => {
                            this.drawDevLine();
                        }, 500);
                    }
                }
                this.loading = false;
            });
        },
        // 搜索按钮操作
        handleDevQuery() {
            this.getDevChartDatas();
        },
        // 重置按钮操作
        handleDevResetQuery() {
            this.resetForm('devQueryForm');
            this.devQueryParams.identifiers = [];
            this.devDatas = [];
            this.devTableComTemp = [];
            this.devTotal = 0;
            this.handleDevQuery();
        },
        drawDevLine() {
            // 初始化折线图
            this.charts = this.$echarts.init(this.$refs.devLineChart);
            this.charts.clear();
            // 设置折线图数据和样式
            this.charts.setOption({
                tooltip: {
                    trigger: 'axis',
                },
                legend: {
                    align: 'right',
                    left: '3%',
                    top: '15%',
                },
                grid: {
                    top: '30%',
                    left: '5%',
                    right: '5%',
                    bottom: '5%',
                    containLabel: true,
                },
                toolbox: {
                    feature: {
                        dataView: {},
                        restore: {},
                        saveAsImage: {},
                    },
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100,
                    },
                    {
                        start: 0,
                        end: 100,
                    },
                ],
                // 自定义：设置x轴刻度
                xAxis: {
                    type: 'category',
                    boundaryGap: true,
                    axisTick: {
                        alignWithLabel: true,
                    },
                    // 自定义标签
                    data: this.devDatas.length !== 0 && this.devDatas.map((item) => Object.keys(item)[0]),
                },
                // 自定义：设置y轴刻度
                yAxis: {
                    type: 'value',
                    scale: true, //自适应
                },
                // 设置数据
                series: this.getDevSeries(),
            });
        },
        // 获取设备的series
        getDevSeries() {
            return {
                name: this.model.identifier,
                type: 'line',
                stack: this.$t('dataCenter.history.384934-23'),
                data: this.devDatas.map((d) => {
                    const ide = Object.values(d)[0].find((f) => Object.keys(f)[0] === this.model.identifier);
                    return Object.values(ide)[0];
                }),
            };
        },
        // 格式化设备列表数据
        formatDevTableDatas() {
            this.devTableComTemp = this.devDatas.map((item) => {
                const time = Object.keys(item)[0];
                let obj = {};
                Object.values(item)[0].forEach((chil) => {
                    obj[Object.keys(chil)[0]] = Object.values(chil)[0];
                });
                return { time, ...obj };
            });
            this.devTotal = this.devDatas.length;
            const arr = [this.model.identifier];
            this.devTableHeaderTemp = arr.map((item) => ({
                name: this.model.identifier,
                value: item,
            }));
        },
    },
};
</script>

<style lang="scss" scoped>
.data-center-history-wrap {
    padding: 20px;

    .device-wrap {
        margin-top: 5px;
    }

    .scene-wrap {
        margin-top: 5px;
    }
}
</style>
