<template>
    <div class="index">
        <div class="header">
            <div class="header-left">
                <img src="../assets/image/logo.png" alt="">
            </div>

            <div class="header-center">
                <div class="header-warning" v-if="statusData[1114]">
                    <img src="../assets/img/warning.gif" alt="">
                </div>
                <div @click="toRouter(item)" :class="item.routerList.indexOf(routerNow) != -1 ? 'active' : ''"
                    v-for="item, index in headerList" :key="index">
                    <div class="img"> <img :src="item.img" alt=""></div>
                    <div class="name">{{ item.name }}</div>
                </div>
            </div>
            <div class="header-right" v-if="userInfo">
                <img src="../assets/image/avatar.png" alt="">
                <div class="user-data">
                    <div class="name">欢迎，{{ userInfo.nickName }}</div>
                    <div class="time" v-if="time"> {{ time.year.year }}-{{ time.year.month }}-{{ time.year.date }}</div>
                </div>
                <div class="login-out" @click="loginOut"></div>
            </div>
        </div>
        <div class="index-content">
            <div class="left collapse" v-if="manageList.indexOf(routerNow)==-1">
                <el-collapse v-model="activeNames">
                    <template v-for="item, index in leftList">
                        <el-collapse-item :name="index + 1" :key="index" v-if="!item.isRouter">
                            <template slot="title" class="collapse-title">
                                <div class="img"><img :src="item.img" alt=""></div> {{ item.name }}
                            </template>
                            <ul class="table-ul">
                                <li class="table-li" @click="toRouter1(item1)"
                                    :class="item.routerList.indexOf(routerNow) != -1 && routerIndex == item1.index ? 'active' : ''"
                                    v-for="item1, index1 in item.list" :key="index1">{{ item1.deviceTypeName }} <div
                                        class="status" :class="item1.deviceState == 0 ? 'outline' : 'online'"
                                        v-if="item1.deviceState >= 0 && item1.deviceState">{{
                    item1.deviceState == 0 ? '离线' : '在线' }}</div>
                                </li>
                            </ul>
                        </el-collapse-item>
                        <div @click="toRouter1(item)" :class="routerNow == item.router ? 'active' : ''" class="no-list"
                            v-else>
                            <div class="img"><img :src="item.img" alt=""></div>{{ item.name }}
                        </div>
                    </template>

                </el-collapse>
            </div>
            <!-- 管理的左侧 -->
            <div class="left collapse" v-else>
                <el-collapse v-model="activeNames1">
                    <template v-for="item, index in leftList1">
                        <el-collapse-item :name="index + 1" :key="index" v-if="!item.isRouter">
                            <template slot="title" class="collapse-title">
                                <div class="img"><img :src="item.img" alt=""></div> {{ item.name }}
                            </template>
                            <ul class="table-ul">
                                <li class="table-li" @click="toRouter2(item1)"
                                    :class="routerNow == item1.router? 'active' : ''"
                                    v-for="item1, index1 in item.list" :key="index1">{{ item1.deviceTypeName }}
                                </li>
                            </ul>
                        </el-collapse-item>
                        <div @click="toRouter2(item)" :class="routerNow == item.router ? 'active' : ''" class="no-list"
                            v-else>
                            <div class="img"><img :src="item.img" alt=""></div>{{ item.name }}
                        </div>
                    </template>

                </el-collapse>
            </div>
            <div class="right">
                <router-view v-if="!loading"></router-view>
            </div>
        </div>
    </div>
</template>

<script>
import { getnowtime } from '../assets/js/nowTime'
export default {
    data() {
        return {
            time: null,//当前时间
            headerActive: 0,
            headerList: [
                { name: '实时数据', router: 'realTime', routerList: ['realTime'], img: require('../assets/image/header-img1.png') },
                // { name: '设定值参数', router: 'status', index: 1, routerList: ['formula', 'irrigateSet', 'PIDSet', 'systemSet', 'upload', 'sensorSet'], img: require('../assets/image/header-img0.png') },
                { name: '设定值参数', router: 'status', index: 1, routerList: ['formula', 'status', 'exitSettings', 'skylight', 'systemSet-con', 'fan', 'upload-con', 'sensorSet-con', 'alarmSettings', 'synthesis-con', 'waterPump', 'geothermalFan', 'uptake', 'downtake', 'rollByRoll', 'snowRemoval', "targetTemperature", "targetHumidity", "targetCo2", "sunroofControl", "outsizeSunshade", "insizeSunshade", "wetFan", "LED", 'electromagneticControl', "coercionMist", "circulationCan", "internalInsulation", "forceOutput", "intrinsicParameter", "parameterSet",], img: require('../assets/image/header-img0.png') },
                { name: '图库数据', router: 'imageData', routerList: ['imageData'], img: require('../assets/image/header-img1.png') },
                { name: '视频监控', router: 'videoMonitoring', routerList: ['videoMonitoring'], img: require('../assets/image/header-img2.png') },
                //  history history
                { name: '历史数据', router: 'historyData', index: 1, routerList: ['historyData'], img: require('../assets/image/header-img3.png') },
                //dataAnalysis dataAnalysis
                { name: '数据分析', router: 'dataAnalysis', index: 1, routerList: ['dataAnalysis'], img: require('../assets/image/header-img4.png') },
                // { name: '设备菜单', router: '', routerList: [], img: require('../assets/image/header-img5.png') },
                //systemManage systemManage
                // manage
                { name: '管理', router: 'manage', routerList: ['manage','dataDevice','deviceStatusSet','deviceSet','deviceInfoManage','weatherData','mobileControl','userInfoControl','deviceManage','videoManage'], img: require('../assets/image/header-img6.png') },

                { name: '大数据', router: 'largeScreen', routerList: ['largeScreen'], img: require('../assets/image/header-img8.png') }
            ],

            activeNames: [3],
            leftList: [
                { name: '首页', img: require('../assets/image/index-icon.png'), list: [], router: 'realTime', isRouter: true, },
                { name: '温室', routerList: ['realTime', 'dataAnalysis', 'historyData', 'exitSettings', 'videoMonitoring','imageData', 'skylight', 'control', 'systemSet-con', 'fan', 'upload-con', 'sensorSet-con', 'synthesis-con', 'alarmSettings', 'waterPump', 'geothermalFan', 'uptake', 'downtake', 'rollByRoll', 'snowRemoval', "targetTemperature", "targetHumidity", "targetCo2", "sunroofControl", "outsizeSunshade", "insizeSunshade", "wetFan", "LED", 'electromagneticControl', "coercionMist", "circulationCan", "internalInsulation", "forceOutput", "intrinsicParameter", "parameterSet"], img: require('../assets/image/left-img0.png'), list: [] },
                // { name: '二号温室', img: require('../assets/image/left-img1.png'), list: [] },
                { name: '施肥机', routerList: ['formula', 'dataAnalysis', 'historyData', 'irrigateSet', 'videoMonitoring','imageData', 'PIDSet', 'systemSet', 'upload', 'sensorSet', 'realTime', 'history', 'dataAnalysis'], img: require('../assets/image/left-img2.png'), list: [] },
                { name: '生态气象站', routerList: ['realTime', 'historyData', 'exitSettings', 'skylight', 'control', 'systemSet-con','imageData', 'fan', 'upload-con', 'sensorSet-con', 'synthesis-con', 'alarmSettings', 'waterPump', 'geothermalFan', 'uptake', 'downtake', 'rollByRoll', 'snowRemoval', "targetTemperature", "targetHumidity", "targetCo2", "sunroofControl", "outsizeSunshade", "insizeSunshade", "wetFan", "LED", 'electromagneticControl', "coercionMist", "circulationCan", "internalInsulation", "forceOutput", "intrinsicParameter", "parameterSet"], img: require('../assets/image/left-img3.png'), list: [] },
            ],
            leftList1: [
                { name: '管理', img: require('../assets/image/index-icon.png'), list: [], router: 'manage', isRouter: true, },
                { name: '用户管理', routerList: [''], img: require('../assets/image/left-img0.png'), list: [
                    {deviceTypeName:'控制器设备状态值设置',router:'deviceStatusSet',index:0},
                    {deviceTypeName:'控制器设备设定值设置',router:'deviceSet',index:1},
                    {deviceTypeName:'设备信息管理',router:'deviceInfoManage',index:2},
                    {deviceTypeName:'设备绑定气象站数据',router:'weatherData',index:3},
                    {deviceTypeName:'大数据设备信息',router:'dataDevice',index:4},
                    {deviceTypeName:'手机控制模块信息',router:'mobileControl',index:5},
                ] },
            ],
            manageList:['deviceStatusSet',
'deviceSet',
'deviceInfoManage',
'weatherData',
'dataDevice',
'mobileControl',
'userInfoControl',
'deviceManage',
'videoManage',],
            activeNames1: [3,2],
            routerNow: 'realTime',
            deviceName: 1,
            routerIndex: 1,
            equipmentList: [],
            userInfo: null,
            loading: true,//页面加载
            IDTimer: null,
            deviceId: '',
            limitUserId: [],
            statusData: [],
            roleId:2,
        }
    },
    watch: {
        "$route"(newName, oldName) {
            this.gerRouter();
            var store = this.$store.state
            if (!store.equipmentName) {
                this.getByid()
            }
        },
    },
    mounted() {
        const that = this
        this.getTime()
        var router = this.$route.query
        if (router.token && router.userid) {
            this.deviceId = router.deviceId ? router.deviceId : ''
            localStorage.setItem('token', router.token)

            this.api.getUser({ userId: router.userid }).then(res => {
                var data = res.data.data
                data.userid = router.userid
                localStorage.setItem('userInfo', JSON.stringify(data))
                this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
                this.gerRouter();
                this.getEqbyid(true)
            })
            return
        } else {
            if (localStorage.getItem('token')) {
                this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
            }
            this.gerRouter();
            this.getEqbyid(true)
        }
        this.IDTimer && clearInterval(this.IDTimer)
        this.IDTimer = setInterval(() => {
            that.getEqbyid(false)
        }, 120000);

        // 获取用户id权限
        this.get_user_getjurisdiction()
        //获取用户身份
        this.getRole()
    },
    beforeDestroy() {
        this.IDTimer && clearInterval(this.IDTimer)
    },
    methods: {
        getRole(){
            var user=   JSON.parse(localStorage.getItem('userInfo'))
      this.api.selUserbyid(user.userid).then(res=>{
        if(res.data.code==200){
            this.roleId=res.data.data.roleId
            if(this.roleId==1){
                this.leftList1= [
                { name: '管理', img: require('../assets/image/index-icon.png'), list: [], router: 'manage', isRouter: true, },
                { name: '用户管理', routerList: [''], img: require('../assets/image/left-img0.png'), list: [
                    {deviceTypeName:'控制器设备状态值设置',router:'deviceStatusSet',index:0},
                    {deviceTypeName:'控制器设备设定值设置',router:'deviceSet',index:1},
                    {deviceTypeName:'设备信息管理',router:'deviceInfoManage',index:2},
                    {deviceTypeName:'设备绑定气象站数据',router:'weatherData',index:3},
                    {deviceTypeName:'大数据设备信息',router:'dataDevice',index:4},
                    {deviceTypeName:'手机控制模块信息',router:'mobileControl',index:5},
                ] },
                { name: '管理员管理', routerList: [''], img: require('../assets/image/left-img0.png'), list: [
                    {deviceTypeName:'用户信息管理',router:'userInfoControl',index:6},
                    {deviceTypeName:'设备管理',router:'deviceManage',index:7},
                    // {deviceTypeName:'摄像头信息管理',router:'videoManage',index:8},
                ] },
            ]
            }else{
                this.leftList1= [
                { name: '管理', img: require('../assets/image/index-icon.png'), list: [], router: 'manage', isRouter: true, },
                { name: '用户管理', routerList: [''], img: require('../assets/image/left-img0.png'), list: [
                    {deviceTypeName:'控制器设备状态值设置',router:'deviceStatusSet',index:0},
                    {deviceTypeName:'控制器设备设定值设置',router:'deviceSet',index:1},
                    {deviceTypeName:'设备信息管理',router:'deviceInfoManage',index:2},
                    {deviceTypeName:'设备绑定气象站数据',router:'weatherData',index:3},
                    {deviceTypeName:'大数据设备信息',router:'dataDevice',index:4},
                    {deviceTypeName:'手机控制模块信息',router:'mobileControl',index:5},
                ] },
            ]
            }
        }
      })
        },
        // 获取用户id权限
        get_user_getjurisdiction() {
            let userInfo = localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")) : { userid: -1 };
            let userId = userInfo.userid
            this.api.user_getjurisdiction(userId).then(res => {
                if (res.data.code == 200) {
                    this.limitUserId = res.data.data;
                    const foundObject = this.limitUserId.find(item => item.id == 3);
                    const foundName = this.headerList.findIndex(item => item.name == '二维码追溯');
                    if (foundObject) {
                        if (foundName == -1) {
                            this.headerList.push({ name: '二维码追溯', router: 'setsuyuan', index: 1, routerList: ['setsuyuan'], img: require('../assets/image/header-img4.png') })
                        }
                    } else {
                        if (foundName != -1) {
                            this.headerList.splice(foundName, 1)
                        }
                    }


                }
            })
        },


        //获取设备名称/配方名称
        getByid() {
            var store = this.$store.state
            var data = {
                deviceId: store.equipmentList[store.equipmentIndex - 1].deviceId,
            };
            this.api.getByid(data).then((res) => {
                if (res.data.code == 200) {
                    store.equipmentName = res.data.data
                } else {
                    this.$message.error(res.data.msg);
                }
                this.loading = false
            });
        },
        //排序
        compare(property) {
            return function (a, b) {
                let value1 = a[property];
                let value2 = b[property];
                return value1 - value2;
            };
        },
        //获取设备
        getEqbyid(selTrue) {
            var userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : { userid: -1 }
            var store = this.$store.state
            this.api.getEqbyid(userInfo.userid).then((res) => {
                if (res.data.code == 200) {
                    this.$store.state.equipmentList = res.data.data.map((item, index) => {
                        return {
                            ...item,
                            router: 'formula',
                            index: index + 1,
                        };
                    });
                    if (!localStorage.getItem('equipmentSelList')) {
                        localStorage.setItem('equipmentSelList', JSON.stringify(res.data.data))
                        // this.$store.state.equipmentSelList=res.data.data
                    }
                    this.leftList[1].list = []
                    this.leftList[2].list = []
                    this.leftList[3].list = []
                    this.$store.state.equipmentList.forEach((el, index) => {
                        //链接中的deviceId
                        if (this.deviceId && this.deviceId == el.deviceId) {
                            this.$store.state.equipmentIndex = index + 1
                        }
                        if (el.deviceName == 1) {
                            this.leftList.forEach((el1, index1) => {
                                if (el1.name == '施肥机') {
                                    this.leftList[index1].list.push(el)
                                }
                            })
                        } else if (el.deviceName == 10) {
                            this.leftList.forEach((el1, index1) => {
                                if (el1.name == '温室') {
                                    this.leftList[index1].list.push(el)
                                }
                            })
                        } else {
                            this.leftList.forEach((el1, index1) => {
                                if (el1.name == '生态气象站') {
                                    this.leftList[index1].list.push(el)
                                }
                            })
                        }
                    })
                    this.api.geteqetdata(userInfo.userid).then((res) => {
                        if (res.data.code == 200) {
                            var list = this.$store.state.equipmentList
                            this.$store.state.equipmentList = list.concat(res.data.data.map(function (item, index) {
                                return {
                                    deviceId: item.deviceId,
                                    userId: item.userId,
                                    deviceTypeName: item.deviceName,
                                    index: list[list.length - 1].index + index + 1,
                                    router: 'formula',
                                    deviceName: '30'
                                };
                            }))

                            this.$store.state.equipmentList.forEach((el, index) => {
                                if (el.deviceName == '30') {
                                    this.leftList.forEach((el1, index1) => {
                                        if (el1.name == '生态气象站') {
                                            this.leftList[index1].list.push(el)
                                        }
                                    })
                                }
                            })
                            this.leftList.forEach((el1, index1) => {
                                if (el1.name == '温室') {
                                    this.leftList[index1].list.sort(this.compare('equipmentStatu'))
                                }
                                if (el1.name == '施肥机') {
                                    this.leftList[index1].list.sort(this.compare('equipmentStatu'))
                                }
                                if (el1.name == '生态气象站') {
                                    this.leftList[index1].list.sort(this.compare('equipmentStatu'))
                                }
                            })
                            this.gerRouter()
                            this.getByid()
                            var data = {
                                deviceId: store.equipmentList[store.equipmentIndex - 1].deviceId,
                            };
                            this.api.getControlGetState(data).then(res => {
                                if (res.data.code == 200) {
                                    this.statusData = res.data.data;

                                }
                            })
                        }
                    })

                }
            })

        },
        gerRouter() {
            var store = this.$store.state
            this.routerIndex = this.$route.query.index ? this.$route.query.index : store.equipmentIndex
            this.routerNow = this.$route.name;

            if (store.equipmentList.length) {
                this.deviceName = store.equipmentList[this.routerIndex - 1].deviceName
            } else {

            }

        },
        loginOut() {
            this.api.loginOut().then((res) => {

                if (res.data.code == 200) {
                    this.$message({
                        message: '退出登录成功',
                        type: "success",
                    });
                    localStorage.removeItem('token')
                    localStorage.removeItem('userInfo')
                    localStorage.removeItem('equipmentSelList')
                    this.$router.push({ name: 'login' })
                } else {
                    this.$message.error("请求出错");
                }
            })
        },
        toHome() {
            this.$router.push({ name: 'home' })
        },
        toRouter(item) {
            if (item.router) {
                if (item.http) {
                    window.location.href = item.http;
                } else if (item.router == 'formula' && this.$route.query.index != item.index) {
                    this.$store.state.equipmentIndex = item.index
                    this.$router.push({ path: `/${item.router}?id=${item.index ? item.index : 1}` })

                } else if (item.router == 'history' && this.$route.query.index != item.index) {
                    this.$router.push({ path: `/history?index=${item.index ? item.index : 1}` })

                } else if (item.router == 'dataAnalysis' && this.$route.query.index != item.index) {
                    this.$router.push({ path: `/dataAnalysis` })

                } else if (item.router == 'status') {
                    if (this.deviceName == '30') {
                        this.$message('气象站无该页面');
                        return
                    }
                    if (this.deviceName == '10') {
                        this.$router.push({ path: `/control` })
                    } else {
                        this.$router.push({ path: `/formula` })
                    }

                } else if (item.router == 'realTime') {

                    this.$router.push({ path: `/realTime` })

                } else if (item.router == 'videoMonitoring') {
                    if (this.deviceName == '30') {
                        this.$message('气象站无该页面');
                        return
                    }
                    this.$router.push({ path: `/videoMonitoring` })

                } else if (item.router == 'status' && item.routerList.indexOf(this.routerNow) != -1) {

                    return

                } else if (item.router == 'largeScreen') {
                    // item.id == 2 东北;
                    // item.id == 1 丽水;
                    // item.id == 5 石门;
                    const foundObject = this.limitUserId.find(item => item.id == 2 || item.id == 1 || item.id == 5);
                    if (!foundObject) {
                        this.$message('您当前没有权限查看!')
                        return
                    } else {
                        this.$router.push({ name: item.router })
                    }

                } else if (item.router != this.routerNow && !item.http) {

                    this.$router.push({ name: item.router })
                }
            } else {
                this.$message('当前页面正在努力开发中');
            }
        },
        toRouter1(item) {
            if (item.router) {
                if (item.http) {
                    window.location.href = item.http;
                } else if (item.router == 'formula' && this.$route.query.index != item.index) {
                    if (this.routerNow == 'realTime') {
                        this.$store.state.equipmentIndex = item.index
                        this.$router.push({ path: `/realTime?index=${item.index ? item.index : 1}&name=${item.deviceName}` })
                    } else if (this.routerNow == 'history') {
                        this.$store.state.equipmentIndex = item.index
                        this.$router.push({ path: `/history?index=${item.index ? item.index : 1}` })
                    } else if (this.routerNow == 'dataAnalysis') {
                        this.$store.state.equipmentIndex = item.index
                        this.$router.push({ path: `/dataAnalysis?index=${item.index ? item.index : 1}` })
                    } else if (this.routerNow == 'historyData') {
                        this.$store.state.equipmentIndex = item.index
                        this.$router.push({ path: `/historyData?index=${item.index ? item.index : 1}` })
                    } else if (this.routerNow == 'imageData') {
                        this.$store.state.equipmentIndex = item.index
                        this.$router.push({ path: `/imageData?index=${item.index ? item.index : 1}` })
                    } else {

                        if (item.deviceName == 10) {
                            // 限制页面随意跳转
                            this.$store.state.equipmentIndex = item.index
                            this.routerIndex = item.index
                            if (this.routerNow != 'skylight' && this.leftList[1].routerList.indexOf(this.$route.name) != -1) {
                                return
                            }
                            this.$router.push({ path: `/control?change=${item.index}` })
                        } else if (item.deviceName == 1 ) {
                            if(this.routerNow == 'irrigateSet'){
                                this.$store.state.equipmentIndex = item.index
                                this.routerIndex = item.index
                            }else{
                                this.$store.state.equipmentIndex = item.index
                                this.routerIndex = item.index
                                this.$router.push({ path: `/irrigateSet?change=${item.index}` })
                            }
                           
                          
                            
                        } else if (item.deviceName == 30) {
                            this.$message('气象站无该页面');
                        }
                    }
                } else if (item.router == 'formula' && this.$route.query.index == item.index) {
                    return
                } else if (item.router != this.routerNow && !item.http) {
                    this.$router.push({ name: item.router })
                }
            } else {
                this.$message('当前页面正在努力开发中');
            }
        },
        toRouter2(item){
            if (item.router != this.routerNow && !item.http) {
                    this.$router.push({ name: item.router })
             }
        },
        getTime() {
            this.time = getnowtime()
            const that = this
            setInterval(() => {
                that.time = getnowtime()
            }, 1000);
        },
    },

}
</script>

<style lang="scss"></style>