<template>
    <div class="detail-tab">
        <div class="tab_head">
            <zz-tabs :tabs="tabs" :value="value" @change="change"></zz-tabs>
        </div>
        <div class="box">
            <div class="query-box">
                <div class="left_search">
                    <span class="el-mgRight-sm" v-show="value == 'history'"> 上报时间 </span>
                    <span class="el-mgRight-sm" v-show="value == 'alarm'">告警时间</span>
                    <span class="el-mgRight-sm" v-show="value == 'valveNote'">操作时间</span>
                    <span>
                        <el-date-picker
                            v-model="dataValue"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :value-format="dateType"
                            :picker-options="endDatePicker"
                            @change="timeQuery"
                            :clearable="false"
                        >
                        </el-date-picker>
                    </span>
                </div>
                <el-tooltip class="item" effect="light" placement="bottom" content="导出">
                    <i class="zoniot_font zoniot-icon-daochu2 tab_head-right" @click="exportExcel()"></i>
                </el-tooltip>
            </div>
            <div class="box__wrap" v-show="value == 'history'">
                <zz-table
                    :cols="Cols"
                    :settings="{ showIndex: true, stripe: true }"
                    height="200"
                    :data="
                        historyDataList.slice(
                            (hispageset.currentPage - 1) * hispageset.pageSize,
                            hispageset.currentPage * hispageset.pageSize
                        )
                    "
                    :loading="mixins_onQuery"
                    :pageset="hispageset"
                    @page-change="hispageChange"
                ></zz-table>
                <div class="echart_content" v-if="value == 'history'">
                    <el-echart :option="chartoption"></el-echart>
                </div>
            </div>
            <div class="box__wrap" ref="alarmbox" v-show="value == 'alarm'">
                <zz-table
                    class="fullheight"
                    :cols="AlertsCols"
                    :settings="{ showIndex: true, stripe: true }"
                    :data="mixins_list"
                    :loading="mixins_onQuery"
                    :pageset="mixins_pageset"
                    @page-change="pageChange"
                >
                </zz-table>
            </div>
            <div class="box__wrap" ref="valvebox" v-show="value == 'valveNote'">
                <zz-table
                    :cols="valveInfoCols"
                    class="fullheight"
                    :settings="{ showIndex: true, stripe: true }"
                    :data="mixins_list"
                    :loading="mixins_onQuery"
                    :pageset="mixins_pageset"
                    @page-change="pageChange"
                >
                </zz-table>
            </div>
        </div>
    </div>
</template>

<script>
import list from '@/utils/list';
import { AlertsCols, historyCols, valveInfoCols } from '../baseData';
import { getRowStr } from './basedata';
import { deviceLoader } from '@/utils/basedata.js';
import { chartOption } from './echartoption';
export default {
    mixins: [list],
    props: ['params'],
    components: {},
    data() {
        return {
            deviceLoader,
            type: '',
            chartoption: {}, //
            value: 'history',
            dateType: 'yyyyMMdd',
            tabs: [
                {
                    value: 'history',
                    label: '历史数据'
                },
                {
                    value: 'alarm',
                    label: '告警记录'
                },
                {
                    value: 'valveNote',
                    label: '阀控记录'
                }
                // {
                //     value: 'replace',
                //     label: '换表记录'
                // }
            ],
            dataUnit: '',
            dataValue: [],
            endDatePicker: {
                disabledDate: (time) => {
                    return time.getTime() > new Date().getTime();
                }
            },
            hispageset: {
                total: 0,
                pageSize: 15,
                pageNum: 1,
                currentPage: 1,
                pageSizes: [15, 30, 60, 120]
            },
            Cols: [],
            AlertsCols,
            valveInfoCols,
            historyCols, //告警列表表头
            getRowStr,
            historyDataList: []
        };
    },
    created() {
        if (!!this.$route.query.type && this.$route.query.type == 2) {
            this.tabs[2].label = '闸控记录';
        }
        this.initDate('YYYYMMDD');
        this.mixins_query = {
            deviceId: this.params.id || '',
            startDate: this.dataValue.length ? `${this.dataValue[0]}` : '',
            endDate: this.dataValue.length ? `${this.dataValue[1]}` : ''
        };

        new Promise((resolve) => {
            this.getDeviceMeasuringPoint(resolve);
        }).then(() => {
            this.change('history');
        });
    },
    methods: {
        initDate(type) {
            let date = new Date();
            this.dataValue = [this.$moment(new Date(date.getFullYear(), date.getMonth(), 1)).format(type), this.$moment().format(type)];
        },
        change(value) {
            this.value = value;
            if (value == 'history') {
                this.getHistorical();
                this.getDiscount();
            } else if (value == 'alarm') {
                this.getAllHandleAbnormal();
            } else if (value == 'valveNote') {
                this.getValveData();
            }
        },
        hispageChange(obj) {
            if (obj.pageSize) {
                this.hispageset.pageSize = obj.pageSize;
            }
            if (obj.page) {
                this.hispageset.currentPage = obj.page;
            }
        },

        // 历史数据
        getDiscount() {
            this.$http
                .post('/sc-energy/device/getQuantity', this.mixins_query)
                .then(({ data, status }) => {
                    if (status === 0) {
                        let dataoption = { xData: [], yData: [] };
                        if (data.length > 0) {
                            data.map((item) => {
                                if (item.date) {
                                    let itemdata = item.date ? item.date.toString().replace(/(\d{4})(\d{2})(\d{2})/gi, '$1-$2-$3') : '';
                                    itemdata = itemdata ? itemdata.slice(5) : '';
                                    if (itemdata) {
                                        dataoption.xData.push(itemdata);
                                        dataoption.yData.push(item.value || '0');
                                    }
                                }
                            });
                        }
                        this.chartoption = chartOption('#29B6FF', dataoption, '用水量', '#29B6FF', 't');
                    }
                })
                .catch((err) => {
                    this.chartoption = {};
                    console.log(err);
                });
        },
        getHistorical() {
            this.historyDataList = [];
            // 获取历史数据列表
            this.mixins_query = {
                deviceId: this.params.id || '',
                startDate: this.dataValue.length ? `${this.dataValue[0]}` : '',
                endDate: this.dataValue.length ? `${this.dataValue[1]}` : ''
            };
            if (this.params.productId) {
                this.$http
                    .post('/sc-energy/device/getData', this.mixins_query)
                    .then(({ data, status }) => {
                        if (status === 0) {
                            if (data.length) {
                                let dateTimeCol;
                                this.historyDataList = [];
                                for (let [k, v] of data.entries()) {
                                    dateTimeCol = _.map(v);

                                    let timeformat = this.$moment(Number(dateTimeCol[0])).format('YYYY-MM-DD HH:mm:ss');
                                    this.historyDataList.push(Object.assign({ receiveTime: timeformat }, data[k].measureData));
                                }
                                this.hispageset.total = data.length;
                                this.mixins_onQuery = false;
                            } else {
                                this.mixins_onQuery = false;
                            }
                        } else {
                            this.mixins_onQuery = false;
                        }
                    })
                    .catch(() => {
                        this.mixins_onQuery = false;
                    });
            } else {
                this.mixins_onQuery = false;
            }
        },
        //告警
        getAllHandleAbnormal() {
            this.mixins_list = [];
            this.mixins_dataUrl = '/sc-energy/alarm/getPage';
            this.mixins_post = 'get';
            this.mixins_query = {
                categoryId: this.params.categoryId || '',
                deviceId: this.params.id || '',
                startDate: this.dataValue.length ? `${this.dataValue[0]}` : '',
                endDate: this.dataValue.length ? `${this.dataValue[1]}` : ''
            };
            this.mixins_search();
        },
        // 阀控记录
        getValveData() {
            this.mixins_list = [];
            this.mixins_post = 'get';
            this.mixins_dataUrl = '/sc-energy/device/command/page';
            this.mixins_query = {
                categoryId: this.params.categoryId || '',
                communityId: this.params.communityId || '',
                startDate: this.dataValue.length ? `${this.dataValue[0]}` : '',
                endDate: this.dataValue.length ? `${this.dataValue[1]}` : ''
            };
            this.mixins_search();
        },

        timeQuery() {
            (this.mixins_query.startDate = this.dataValue.length ? `${this.dataValue[0]}` : ''),
                (this.mixins_query.endDate = this.dataValue.length ? `${this.dataValue[1]}` : '');
            this.change(this.value);
        },
        getDeviceMeasuringPoint(resolve) {
            if (this.params && this.params.productId) {
                this.$http
                    .get('/sc-energy/measuring/point/find', { productId: this.params.productId })
                    .then(({ status, msg, data = [] }) => {
                        if (status === 0) {
                            this.pointList = data;
                            this.Cols.push({ label: '时间', prop: 'receiveTime', width: 200 });
                            if (data.length) {
                                data.map((item, index) => {
                                    this.Cols.push({
                                        label: item.measuringName,
                                        prop: item.measuringCode,
                                        format(value) {
                                            if (item.dictList.length) {
                                                let newValue;
                                                item.dictList.map((item, index) => {
                                                    if (item.dataValue == value) {
                                                        newValue = item.dataName;
                                                    }
                                                });
                                                return newValue;
                                            } else {
                                                return value;
                                            }
                                        }
                                    });
                                });
                            } else {
                                this.mixins_onQuery = false;
                            }
                        } else {
                            this.mixins_onQuery = false;
                        }
                        resolve && resolve(true);
                    })
                    .catch(() => {
                        this.mixins_onQuery = false;
                    });
            }
        },

        dataFormat(date) {
            return date
                .toLocaleString()
                .replace(/\/|[\u4e00-\u9fa5]|:|\s+/g, '')
                .substr(0, 8);
        },
        exportExcel(date) {
            let downurl = '';
            let params = {
                deviceId: this.params.id || '',
                startDate: this.dataValue.length ? `${this.dataValue[0]}000000` : '',
                endDate: this.dataValue.length ? `${this.dataValue[1]}235959` : ''
            };
            if (this.value == 'history') {
                params = {
                    deviceId: this.params.id || '',
                    startDate: this.dataValue.length ? `${this.dataValue[0]}` : '',
                    endDate: this.dataValue.length ? `${this.dataValue[1]}` : ''
                };
                downurl = '/sc-energy/device/getDataExcel';
            } else if (this.value == 'alarm') {
                params = Object.assign(params, {
                    categoryId: this.params.categoryId || '',
                    deviceId: this.params.id || ''
                });
                downurl = '/sc-energy/alarm/exportExcel';
            } else if (this.value == 'replace') {
                return;
                params = {
                    deviceNo: this.params.deviceNo || '',
                    replaceMethod: this.params.replaceMethod || '',
                    startDate: this.dataValue.length ? `${this.dataValue[0]}000000` : '',
                    endDate: this.dataValue.length ? `${this.dataValue[1]}235959` : ''
                };
                downurl = '/zoniot-rmcp-web/device/meter/replace/export/excel';
            } else {
                downurl = '/sc-energy/device/command/export/excel';
                params = {
                    categoryId: this.params.categoryId,
                    startDate: this.dataValue.length ? `${this.dataValue[0]}000000` : '',
                    endDate: this.dataValue.length ? `${this.dataValue[1]}235959` : '',
                    type: '' //操作类型
                };
            }
            this.__exportExcel(downurl, params);
        }
    }
};
</script>

<style lang="scss" scoped>
.tab_head-right {
    line-height: inherit;
    color: #0eaeff;
    font-size: 30px;
}
.box__wrap {
    /deep/ .fullheight {
        height: 100%;
        // height: fit-content;
        width: 100%;
        display: inline-flex;
        flex-direction: column;
        justify-content: space-between;
        .el-table {
            overflow-y: auto;
        }
    }
}
</style>
