<template>
    <Page>
        <div class="device-control">
            <!--左侧列表区-->
            <PointTree @selectPoint="selectPoint" />
            <!--右侧内容区-->
            <div class="device-control-right" v-if="deviceData" v-loading="loading">
                <el-descriptions title="设备基本信息" class="mb10" :column="3" border>
                    <el-descriptions-item>
                        <template slot="label">名称</template>
                        {{ deviceData.name }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">类型</template>
                        {{
                            devTypeOptions.filter(item => item.value == deviceData.devType)[0] &&
                            devTypeOptions.filter(item => item.value == deviceData.devType)[0].label
                        }}
                    </el-descriptions-item>

                    <el-descriptions-item>
                        <template slot="label">接入方式</template>
                        {{ deviceData.devAccessMethod }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">识别码</template>
                        {{ deviceData.ndid }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">型号</template>
                        {{
                            devModelOptions.filter(item => item.value == deviceData.devModel)[0] &&
                            devModelOptions.filter(item => item.value == deviceData.devModel)[0].label
                        }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template slot="label">接入时间</template>
                        {{ deviceData.time }}
                    </el-descriptions-item>
                </el-descriptions>
                <el-tabs v-model="dataSet" type="card" class="device-control-box-card" @tab-click="handleClick">
                    <el-tab-pane
                        lazy
                        :label="item.name"
                        :name="item.id"
                        v-for="item in deviceData.dataSetList"
                        :key="item.id"
                    ></el-tab-pane>
                    <el-form :inline="true">
                        <el-form-item label="指标:">
                            <el-input
                                v-model="formInline.searchValue"
                                autocomplete="off"
                                clearable
                                placeholder="请输入关键词"
                            ></el-input>
                        </el-form-item>
                        <el-form-item v-if="dataSet.indexOf('_history') > -1">
                            <timepicker ref="timepk" :interval="3"></timepicker>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" size="mini" icon="el-icon-search" @click="handleClick">
                                查询
                            </el-button>
                        </el-form-item>
                    </el-form>
                    <div style="overflow: auto; height: calc(100vh - 388px)">
                        <div class="content">
                            <el-card
                                class="box-card"
                                v-for="(item, index) in tableData"
                                :key="index"
                                :style="
                                    'color:#fff;opacity:0.8;background-image:linear-gradient(' +
                                    settings.themeColor +
                                    ',#ccc);'
                                "
                            >
                                <div slot="header" class="clearfix" :style="'background:' + settings.themeColor">
                                    <span style="flex: 1">{{ item.name }}</span>
                                    <i
                                        class="el-icon-s-marketing ml10"
                                        style="font-size: 26px; cursor: pointer"
                                        @click="getDeviceDataTrend(item)"
                                    ></i>
                                </div>
                                <div class="box-card-content" v-if="dataSet.indexOf('_history') == -1">
                                    <div v-for="(child, childIndex) in item.children" :key="childIndex">
                                        {{ child.anotherName }}:
                                        {{ child.dataValue === 3.1415926 ? '暂无数据' : child.dataValue }}
                                    </div>
                                    <div class="mt10" style="color: rgb(0, 102, 80)">
                                        统计时间：{{ item.children.length ? item.children[0].time : '' }}
                                    </div>
                                </div>
                                <div v-else-if="item.children.length">
                                    <div style="display: flex; align-items: center">
                                        <el-tag
                                            size="mini"
                                            effect="dark"
                                            type="danger"
                                            style="width: 40px; text-align: center"
                                            class="mr10"
                                        >
                                            MAX
                                        </el-tag>
                                        {{
                                            item.children[0].maxValue === 3.1415956
                                                ? '暂无数据'
                                                : item.children[0].maxValue
                                        }}
                                    </div>
                                    <div style="display: flex; align-items: center" class="mt10">
                                        <el-tag
                                            size="mini"
                                            effect="dark"
                                            type="success"
                                            style="width: 40px; text-align: center"
                                            class="mr10"
                                        >
                                            AVG
                                        </el-tag>
                                        {{
                                            item.children[0].avgValue === 3.1415956
                                                ? '暂无数据'
                                                : item.children[0].avgValue
                                        }}
                                    </div>
                                    <div style="display: flex; align-items: center" class="mt10">
                                        <el-tag
                                            size="mini"
                                            effect="dark"
                                            type="warning"
                                            style="width: 40px; text-align: center"
                                            class="mr10"
                                        >
                                            MIN
                                        </el-tag>
                                        {{
                                            item.children[0].minValue === 3.1415956
                                                ? '暂无数据'
                                                : item.children[0].minValue
                                        }}
                                    </div>
                                </div>
                            </el-card>
                            <el-empty description="暂无数据" v-if="tableData.length === 0"></el-empty>
                        </div>
                    </div>
                    <el-pagination
                        v-if="tableData.length"
                        background
                        align="right"
                        @size-change="handleSizeChange"
                        @current-change="pageChange"
                        :current-page="formInline.pageNum"
                        :page-sizes="[20, 30, 40, 50, 100]"
                        :page-size="formInline.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                    ></el-pagination>
                </el-tabs>
            </div>
            <el-dialog
                :close-on-click-modal="false"
                :title="dialogData.name"
                :visible.sync="dialogVisible"
                width="80%"
                class="dfghs"
                @close="dialogClose"
                :destroy-on-close="true"
            >
                <el-form :inline="true">
                    <el-form-item>
                        <timepicker ref="timepk2" :interval="3"></timepicker>
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            type="primary"
                            size="mini"
                            icon="el-icon-search"
                            @click="getDeviceDataTrend(dialogData)"
                        >
                            查询
                        </el-button>
                    </el-form-item>
                </el-form>
                <!-- <div class="title">趋势曲线</div> -->
                <div id="main" class="mt10" v-if="echartsData && echartsData.length"></div>
                <el-empty description="暂无数据" v-else style="height: 60vh"></el-empty>
            </el-dialog>
        </div>
    </Page>
</template>
<script>
import { getDeviceData, deviceRtData, deviceHisData, getDeviceDataTrend } from '@/api/app/device.js'
import { queryByCode, queryCsDictTree, queryByid } from '@/api/app/setting.js'
import PointTree from '../components/pointTree'
import * as echarts from 'echarts'
import timepicker from '@/views/components/TimePicker/index4.vue'

export default {
    name: 'GovernDeviceControl',
    components: { timepicker, PointTree },
    data() {
        return {
            pickerOptions: {
                shortcuts: [
                    {
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date()
                            console.log(end)
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近六个月',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
                            picker.$emit('pick', [start, end])
                        }
                    },
                    {
                        text: '最近一年',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 360)
                            picker.$emit('pick', [start, end])
                        }
                    }
                ]
            },
            formLabelWidth: '68px',
            deviceData: null,
            dataSet: '',
            loading: false,
            devTypeOptions: [],
            devModelOptions: [],
            tableData: [],
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            pointData: {},
            formInline: {
                date: [],
                pageNum: 1,
                pageSize: 20,
                lineId: '',
                id: '',
                startTime: '',
                endTime: '',
                searchValue: ''
            },
            total: 0,
            dialogVisible: false,
            dialogForm: {
                startTime: '',
                endTime: '',
                date: []
            },
            dialogData: {},
            echartsData: null
        }
    },
    computed: {
        vth() {
            return window.sessionStorage.getItem('appheight') - 260
        },
        settings() {
            return this.$store.state.settings
        }
    },
    created() {
        queryByCode('Direct_Connected_Device').then(res => {
            queryCsDictTree(res.data.id).then(res => {
                this.devTypeOptions = res.data.map(item => {
                    return {
                        value: item.id,
                        label: item.name,
                        ...item
                    }
                })
            })
            queryByid(res.data.id).then(res => {
                this.devModelOptions = res.data.map(item => {
                    return {
                        value: item.id,
                        label: item.name,
                        ...item
                    }
                })
            })
        })
        this.dialogForm.endTime = this.$tools.formatDate()
        // 今日0点
        this.dialogForm.startTime = this.$tools.formatDate(new Date(new Date().setHours(0, 0, 0, 0)))
        this.dialogForm.date = [this.dialogForm.startTime, this.dialogForm.endTime]
    },
    mounted() {},
    methods: {
        dialogClose() {},
        dateChange(e) {},
        formInlineDateChange(e) {},
        getDeviceDataTrend(e) {
            this.dialogData = e
            this.dialogVisible = true
            this.$nextTick(() => {
                getDeviceDataTrend({
                    endTime: this.$refs.timepk2.timeValue[1],
                    lineId: this.formInline.lineId,
                    startTime: this.$refs.timepk2.timeValue[0],
                    statisticalParams: e.children
                }).then(res => {
                    if (res.data.length && res.data[0].length) {
                        this.echartsData = res.data
                        this.$nextTick(() => {
                            this.initChart(res.data)
                        })
                    } else {
                        this.echartsData = null
                    }
                })
            })
        },
        initChart(data) {
            var chartDom = document.getElementById('main')
            var myChart = echarts.init(chartDom)
            let arr = []
            data.forEach(item => {
                arr.push(...item)
            })
            console.log(
                arr
                    .map(item => item.statisticalData)
                    .sort((a, b) => {
                        return b - a
                    })
            )
            console.log(arr)
            console.log(
                arr
                    .map(item => item.statisticalData)
                    .sort((a, b) => {
                        return b - a
                    })[0] * 1.5
            )
            var option
            option = {
                grid: {
                    right: '10px',
                    bottom: '10px',
                    left: '10px',
                    top: '40px',
                    containLabel: true
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: data.map(item => {
                        return item[0].anotherName
                    })
                },
                xAxis: {
                    type: 'category',
                    data: data[0].map(item => {
                        return item.time
                    }),
                    axisLabel: {
                        formatter: function (value, index) {
                            return value.split(' ').join('\n')
                        }
                    }
                },
                yAxis: {
                    name: `单位:(${data[0][0].unit})`,
                    type: 'value',
                    axisLine: {
                        show: true
                    },
                    minInterval: 1,
                    min: 0,
                    max: parseInt(
                        arr
                            .map(item => item.statisticalData)
                            .sort((a, b) => {
                                return b - a
                            })[0] * (1.5).toFixed(0)
                    )
                },
                series: data.map(item => {
                    return {
                        data: item.map(item => {
                            return item.statisticalData
                        }),
                        markPoint: {
                            symbol: 'circle',
                            symbolSize: 8,
                            label: {
                                show: false
                            },
                            data: [
                                { type: 'max', name: 'Max' },
                                { type: 'min', name: 'Min' }
                            ]
                        },
                        type: 'line',
                        showSymbol: false,
                        smooth: true,
                        name: item[0].anotherName
                    }
                })
                // series: [
                //     {
                //         data: [820, 932, 901, 934, 1290, 1330, 1320],
                //         type: 'line',
                //         smooth: true,
                //     },
                // ],
            }
            option && myChart.setOption(option)
window.echartsArr.push(myChart)
        },
        pageChange(e) {
            this.formInline.pageNum = e
            this.handleClick()
        },
        handleSizeChange(val) {
            this.formInline.pageNum = 1
            this.formInline.pageSize = val
            this.handleClick()
        },
        selectPoint(e) {
            this.loading = true
            console.log(e, 123)
            getDeviceData(e.pid, 'history', e.id).then(res => {
                res.data.dataSetList.forEach(item => {
                    // dataSetList.push({
                    //     ...item,
                    //     name: '历史' + item.name,
                    //     id: item.id + '_history',
                    // })
                    if (item.type === 'history') {
                        item.id = item.id + '_history'
                    }
                })
                // this.deviceData.dataSetList.push(...dataSetList)
                this.deviceData = res.data
                if (res.data.dataSetList.length === 0) {
                    this.dataSet = ''
                    this.tableData = []
                    this.$nextTick(() => {
                        this.loading = false
                    })
                } else {
                    this.dataSet = this.deviceData.dataSetList[0].id
                    this.handleClick()
                }
            })
            this.formInline.lineId = e.id
            this.pointData = e
        },
        handleClick(tab, event) {
            if (tab) {
                this.tableData = []
                this.formInline.pageNum = 1
            }
            if (this.dataSet.indexOf('_history') > -1) {
                this.$nextTick(() => {
                    this.formInline.startTime = this.$refs.timepk.timeValue[0]
                    this.formInline.endTime = this.$refs.timepk.timeValue[1]
                    this.formInline.id = this.dataSet.replace('_history', '')
                    deviceHisData(this.formInline).then(res => {
                        console.log(res)
                        this.tableData = res.data.records
                        this.total = res.data.total
                        this.$nextTick(() => {
                            this.loading = false
                        })
                    })
                })
            } else {
                this.formInline.id = this.dataSet
                deviceRtData(this.formInline).then(res => {
                    this.tableData = res.data.records
                    this.total = res.data.total
                    this.$nextTick(() => {
                        this.loading = false
                    })
                })
            }
        }
    }
}
</script>
<style lang="scss" >
::v-deep .dfghs .el-dialog .el-dialog__body {
    max-height: 70vh !important;
    padding: 10px !important;
    // overflow-y: auto;
}

 .device-control {
    display: flex;

    .device-control-right {
        flex: 1;
    }
    .el-descriptions--small.is-bordered .el-descriptions-item__cell {
        padding: 8px 10px !important;
    }
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }

    .content {
        box-sizing: border-box;
        overflow: auto;
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        grid-template-rows: max-content;
        grid-gap: 10px;
        justify-content: center;

        .box-card {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            color: #fff;
            background-image: linear-gradient(rgb(44, 162, 180), rgb(6, 78, 96));
            opacity: 0.8;
            min-height: 150px;
            font-size: 13px;

            .el-card__header {
                padding: 0;

                .clearfix {
                    box-sizing: border-box;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    height: 35px;
                    padding: 0 10px;
                    background: rgb(6, 78, 96);
                    color: #fff;
                }
            }

            .el-card__body {
                flex: 1;
                margin-bottom: 0;

                .box-card-content {
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                }
            }
        }
    }

    #main {
        width: 100%;
        height: 60vh;
    }
}

::v-deep .device-control-box-card {
    // height: calc(100vh - 250px);
    overflow-y: scroll;
}
</style>
