<template>
<el-container>
    <el-main>
        <el-row>
            <el-col :xs="20" :sm="20" :md="20" :lg="5" :xl="5">
                天车:<el-select v-model="selectedRootDevice" placeholder="请选择天车" @change="selectRootDeviceChanged">
                    <el-option v-for="item in rootDevices" :key="item.id" :label="item.name" :value="item" />
                </el-select>
            </el-col>
            <el-col :xs="20" :sm="20" :md="20" :lg="15" :xl="15">
                设备:
                <el-cascader style="width:50%" filterable :options="selectedRootDevice.children" :props="{ checkStrictly: true }" clearable @change="selectDeviceChanged" />
            </el-col>
            <el-col :xs="20" :sm="20" :md="20" :lg="4" :xl="4" />
        </el-row>

        <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
            <el-col v-for="(item) in dataSources" :key="item.id" :xs="10" :sm="6" :md="8" :lg="5" :xl="12" :value="item.id">
                <line-chart :chart-data="item.valueList" :maxValue="item.maxValue" :minValue="item.minValue" :title="item.deviceInfo+':'+item.dataType.name" />
                <!-- <line-chart  /> -->
                <!-- <LineChart1 ref="line_chart"/> -->

            </el-col>
        </el-row>

    </el-main>
</el-container>
</template>

<script>
import LineChart1 from '../components/LineChart1.vue'
import LineChart from '../components/LineChart.vue'
// const lineChartData = {
//   newVisitis: {
//     expectedData: [100, 120, 161, 134, 105, 160, 165],
//     actualData: [120, 82, 91, 154, 162, 140, 145]
//   },
//   messages: {
//     expectedData: [200, 192, 120, 144, 160, 130, 140],
//     actualData: [180, 160, 151, 106, 145, 150, 130]
//   },
//   purchases: {
//     expectedData: [80, 100, 121, 104, 105, 90, 100],
//     actualData: [120, 90, 100, 138, 142, 130, 130]
//   },
//   shoppings: {
//     expectedData: [130, 140, 141, 142, 145, 150, 160],
//     actualData: [120, 82, 91, 154, 162, 140, 130]
//   }
// }

export default {

    components: {
        LineChart1,
        LineChart
    },
    data() {
        return {
            selectedRootDevice: {},
            dataSources: [],
            client: null,
            //clientList: [],
            // lineChartData: lineChartData.newVisitis,
            chartDataArray: [],
            xData: ['2020-02', '2020-03', '2020-04', '2020-05'],
            yData: [30, 132, 80, 134]
        }
    },
    computed: {
        // allDataSources() {
        //     return this.$store.getters.allDataSources
        // },
        rootDevices() {
            return this.$store.getters.rootDevices
        },
        deviceList() {
            return this.$store.getters.deviceList
        },

        allDataTypes() {
            return this.$store.getters.allDataTypes
        }
    },
    mounted() {
        this.$store.dispatch('device/getRootDevices').then(res => {
            //this.initAllMqtt()
            if (this.rootDevices.length > 0) {
                this.selectedRootDevice = this.rootDevices[0]
                this.dataSources = this.selectedRootDevice.childrenDataSources
                this.initMqtt(this.rootDevices[0],this.rootDevices[0].childrenDataSources)
            }

        })
        // this.$store.dispatch('device/getAllDevices')
        // this.initMqtt()

        // const {
        //     name,
        //     xData,
        //     yData
        // } = this
        // console.log('refs', this.$refs)
        //  this.$store.dispatch('dataSource/getAllDataSources').then(res => {
        // this.subscribeAll()
        // })
    },
    created() {
        console.log('created')

        // this.mqttReceive()

        // this.$store.dispatch("dataType/getAllDataTypes")
    },
    destroyed() {
        // console.log('clientList size', this.clientList.length)
        this.client.end()
        // for (var i = 0; i < this.clientList.length; ++i) {
        //     this.clientList[i].end()
        // }
    },
    methods: {
        // initAllMqtt() {
        //     console.log('init all mqtt')
        //     for (let i = 0; i < this.rootDevices.length; ++i) {
        //         this.initMqtt(this.rootDevices[i])
        //     }
        // },
        initMqtt(crane,sources) {
            console.log('init ' + crane.name + ' mqtt')
            const vm = this
            const commonApi = 'ws://' + crane.extra + ':8083'
            var mqtt = require('mqtt')
            var options = {
                // mqtt客户端的id
                clientId: crane.name + Math.random().toString(16).substr(2, 8),
                username: 'admin',
                password: '123456'
            }
            vm.client = mqtt.connect(commonApi, options)

            vm.client.on('connect', function () {
                console.log(crane.name + ' mqtt connected success!')
                vm.subscribeAll(crane,sources)
            })
            vm.client.on('error', function (err) {
                console.log('err=>', err)
                vm.client.end()
            })
            //this.clientList.push(mClient)
            //console.log('clientList size', this.clientList.length)
        },

  
        subscribeAll(crane,sources) {
            const vm = this
            console.log('subscribeAll for:', crane.name)
            console.log(crane.name + ' childrenDatasources length ',sources.length)
            for (let i = 0; i < sources.length; ++i) {
                let topic = sources[i].publishTopic
                console.log(crane.name + ' topic', topic)

                vm.client.subscribe(topic, function (err) {
                    if (!err) {
                        console.log(crane.name + ' ' + topic + ':subscribe success!')
                    } else {
                        // 打印错误
                        console.log('err', err)
                    }
                })

       
                vm.client.on('message', function (topic, message) {
                    // console.log(topic,message.toString())
                    let obj = JSON.parse(message.toString())
                    let tmpData = vm.findDataSourceByTopicFromDataSources(topic,sources)
                    console.log(tmpData.name+" length",tmpData.valueList.length)
                    let data = {
                        name: obj.name,
                        // value: [new Date(obj.createTime), obj.value]
                        value: [new Date(), obj.value]
                    }
                   // console.log(crane.name + ' ' + topic + '-data:' + data.name + ',' + data.value)
                    // console.log('date',vm.dateFormat(obj.createTime))
                    if (tmpData.valueList.length < 60) {
                        tmpData.valueList.push(data)
                        // tmpData.dateList.push(obj.createTime)
                    } else {
                        tmpData.valueList.shift()
                        tmpData.valueList.push(data)
                    }

                    console.log(tmpData.publishTopic, data)
                })
            }
        },
       
        dateFormat(time) {
            const date = new Date(time)
            const year = date.getFullYear()
            // 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
            const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
            const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
            const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
            const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
            const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
            const milliSeconds = date.getMilliseconds()
            // 拼接
            return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds + ':' + milliSeconds
            // return year + "-" + month + "-" + day;
        },
        findDataSourceByTopic(topic) {
            console.log('start to find ', topic)
            for (let j = 0; j < this.dataSources.length; ++j) {
                let tmpTopic = this.dataSources[j].publishTopic
                if (tmpTopic === topic) {
                    console.log('findded ', topic)
                    return this.dataSources[j]
                }
            }
        },
        findDataSourceByTopicFromDataSources(topic,dataSources) {
            console.log('start to find ', topic)
            for (let j = 0; j < dataSources.length; ++j) {
                let tmpTopic = dataSources[j].publishTopic
                if (tmpTopic === topic) {
                    console.log('findded ', topic)
                    return dataSources[j]
                }
            }
        },
        findDeviceById(devices, id) {
            var tmp
            for (let i in devices) {
                console.log('device id ' + devices[i].id, id)
                if (devices[i].id === id) {
                    console.log('finded', devices[i])
                    tmp = devices[i]
                    return tmp
                } else {
                    console.log('find children', devices[i])
                    tmp = this.findDeviceById(devices[i].children, id)
                    if (tmp != null) break
                }

            }
            return tmp

        },

        handleSetLineChartData(type) {
            this.lineChartData = lineChartData[type]
        },
        selectDeviceChanged(data) {

            console.log('select device change ', data)

            this.dataSources = data.childrenDataSources

            let selectedDeviceID = data[data.length - 1]
            this.selectedDeviceID = selectedDeviceID

            console.log('selected deviceID ', data[data.length - 1])
            let device = this.findDeviceById(this.rootDevices, selectedDeviceID)
            // var tmpList = []
            // tmpList.push(device)
            // this.$store.commit('device/SET_DEVICE_LIST', tmpList)
           
            this.client.end()
            this.dataSources = device.dataSources
            this.initMqtt(this.selectedRootDevice,this.dataSources)
            //this.subscribeAll(device) 
            
        },
        selectRootDeviceChanged(data) {
            console.log('selectRootDeviceChanged', data)
            this.$store.commit('device/SET_DEVICE_LIST', data.allChildren)
            
            this.selectedRootDevice=data

            this.client.end()
            this.dataSources =this.selectedRootDevice.childrenDataSources
            this.initMqtt(this.selectedRootDevice,this.selectedRootDevice.childrenDataSources)

            // this.dataSources=data.childrenDataSources
        },

        selectDeviceChange(data) {
            console.log('select device change ', data)
            var selectedDeviceID = data[data.length - 1]
            console.log('selected deviceID ', data[data.length - 1])
            var device = this.findDeviceById(this.rootDevices, selectedDeviceID)
            console.log('selected device ', device)
            this.addDevice.fatherId = device.id
        }
    }
}
</script>
