<template>
    <Cn-page :loading="loading" noPadding>
        <view slot="body" class="canneng-index">
            <uni-nav-bar rightWidth="300rpx" leftWidth="300rpx" dark :fixed="true" status-bar background-color="#fff"
                color="#111" @clickRight="selectEngineering">
                <template slot="left">
                    <text style="font-size: 32rpx; font-weight: 500">灿能物联</text>
                </template>
                <template slot="right">
                    <text class="hide-txt mr5" style="font-size: 28rpx">{{
                        userInfo.authorities === 'engineering_user'
                            ? '创建工程'
                            : select.engineeringName || emptyEngineeringName
                    }}
                    </text>
                    <uni-icons type="bottom" size="16" color="#111"
                        v-if="select.engineeringName && userInfo.authorities != 'engineering_user'"></uni-icons>
                </template>
            </uni-nav-bar>
            <view class="index">
                <!-- 运维 -->
                <YunWei :devCount="devCount" v-if="userInfo.authorities === 'operation_manager'" />
                <!-- 营销 -->
                <ZhuanZhi :devCount="devCount" v-if="userInfo.authorities === 'market_user'" />
                <!-- 工程 -->
                <GongCheng ref="gongCheng" :devCount="devCount" v-if="userInfo.authorities === 'engineering_user'" />
                <!-- 正式 -->
                <ZhuYongHu :devCount="devCount" v-if="userInfo.authorities === 'app_vip_user'" />
                <!-- 游客 -->
                <YouKe :devCount="devCount" v-if="userInfo.authorities === 'tourist'"></YouKe>
                <!-- 工程列表 -->
                <template v-show="engineeringList.length" v-if="userInfo.authorities === 'engineering_user'">
                    <!-- <view class="canneng-index-title mt20 canneng-index-title-with-icon">
                        <uni-icons type="list" size="18" color="#376cf3" />
                        <text>工程列表</text>
                    </view> -->
                    <view class="canneng-index-title mt20">
                        <view class="canneng-index-title-with-icon">
                            <uni-icons type="list" size="18" color="#376cf3" />
                            <text>工程列表</text>
                        </view>
                        <view class="nav-menu nav-menu-btn boxClick" @click="jump">关键指标概览 </view>
                    </view>
                    <Engineering ref="engineering" :store="store" @refresh="store.search()" />
                </template>
                <!-- 设备列表 -->
                <template v-else v-show="engineeringList.length">
                    <view class="canneng-index-title mt20">
                        <view class="canneng-index-title-with-icon">
                            <uni-icons custom-prefix="iconfont" type="icon-shebei4" size="18" color="#376cf3" />
                            <text>设备列表</text>
                        </view>
                        <view class="nav-menu nav-menu-btn boxClick" @click="jump">关键指标概览 </view>
                    </view>
                    <Device ref="device" :store="store" />
                </template>
            </view>
            <view class="back-top boxClick" v-show="showBackTop" @click="backToTop">
                <uni-icons type="arrow-up" size="22" color="#fff"></uni-icons>
            </view>
        </view>
    </Cn-page>
</template>
<script>
import YunWei from './comp/indexYunWei.vue'
import GongCheng from './comp/indexGongCheng.vue'
import ZhuYongHu from './comp/indexZhuYongHu.vue'
import ZhuanZhi from './comp/indexZhuanZhi.vue'
import YouKe from './comp/indexYouKe.vue'
import Device from './comp/device.vue'
import Engineering from './comp/engineering.vue'
import list from '../../common/js/list'
import { getDevCount } from '../../common/api/device.js'
import { queryEngineering } from '@/common/api/engineering.js'
import { checkAppUpdate } from '@/common/js/update.js'

export default {
    mixins: [list],
    components: {
        YunWei,
        GongCheng,
        ZhuYongHu,
        ZhuanZhi,
        YouKe,
        Device,
        Engineering,
    },
    data() {
        return {
            loading: false,
            userInfo: {},
            devCount: {},
            select: {
                engineeringName: '',
                engineeringId: '',
            },
            engineeringList: [],
            navTabHeight: 0,
            timer: null,
            showBackTop: false,
        }
    },
    computed: {
        emptyEngineeringName() {
            if (this.userInfo.authorities === 'tourist') {
                return '创建工程'
            } else if (this.userInfo.authorities === 'market_user') {
                return '请联系管理员配置工程'
            } else {
                return '创建工程'
            }
        },
    },

    methods: {
        selectEngineering() {
            if (this.userInfo.authorities === 'engineering_user') {
                uni.navigateTo({
                    url: '/pages/engineering/new',
                })
            } else if (this.select.engineeringName) {
                uni.navigateTo({
                    url: '/pages/home/selectEngineering',
                })
            } else {
                if (this.userInfo.authorities === 'tourist') {
                    return uni.showToast({
                        title: '此功能仅对正式用户开放',
                        icon: 'none',
                    })
                } else if (this.userInfo.authorities === 'market_user') {
                    return uni.showToast({
                        title: '请联系管理员配置工程',
                        icon: 'none',
                    })
                }
                uni.navigateTo({
                    url: '/pages/engineering/new',
                })
            }
        },
        async init() {
            let engineering = uni.getStorageSync('engineering')
            let res = await queryEngineering()
            this.engineeringList = res.data
            uni.setStorageSync('engineeringList', this.engineeringList)
            if (this.engineeringList.length === 0) {
                console.log('没有工程')
                uni.removeStorageSync(this.$cacheKey.engineering)
                this.select.engineeringName = ''
                this.select.engineeringId = ''
                this.projectList = []
            } else {
                if (!engineering) {
                    uni.setStorageSync('engineering', res.data[0])
                    this.select.engineeringName = res.data[0].name
                    this.select.engineeringId = res.data[0].id
                } else {
                    if (this.engineeringList.findIndex((item) => item.id === engineering.id) === -1) {
                        uni.setStorageSync('engineering', res.data[0])
                        this.select.engineeringName = res.data[0].name
                        this.select.engineeringId = res.data[0].id
                    } else {
                        this.select.engineeringName = engineering.name
                        this.select.engineeringId = engineering.id
                    }
                }
                this.store.params.engineerId = this.select.engineeringId
                this.getDevCount()
                console.log(this.$refs.device, 'this.$refs.device')
                this.$nextTick(() => {
                    this.$refs.device && this.$refs.device.init()
                    this.$refs.engineering && this.$refs.engineering.init()
                })
            }
            this.$refs.gongCheng?.init()
        },
        getDevCount() {
            if (!this.select.engineeringId) return
            if (!uni.getStorageSync(this.$cacheKey.access_token)) {
                clearInterval(this.timer)
                return
            }
            getDevCount(this.select.engineeringId).then((res) => {
                // console.log(`12312`,res)
                // Object.assign(this.devCount, res.data)
                this.devCount = res.data
                this.devCount.currentOffLineDevs?.forEach((item) => {
                    item.runStatus = 1
                })
                this.devCount.offLineDevs?.forEach((item) => {
                    item.runStatus = 1
                })
                this.devCount.engineeringListLength = this.engineeringList.length
                uni.setStorage({
                    key: this.$cacheKey.messageCount,
                    data: this.devCount,
                })
                // let messagePage =
                //     this.devCount.runCount +
                //     this.devCount.eventCount +
                //     this.devCount.alarmCount +
                //     this.devCount.harmonicCount
                let messagePage =
                    this.devCount.eventCount +
                    this.devCount.harmonicCount +
                    (uni.getStorageSync(this.$cacheKey.userInfo).authorities == 'operation_manager'
                        ? this.devCount.alarmCount + this.devCount.runCount
                        : 0)
                // console.log('🚀 ~ messagePage:', messagePage)
                let minePage = this.devCount.feedBackCount

                if (messagePage) {
                    uni.setTabBarBadge({
                        index: 1,
                        text: messagePage ? (messagePage > 99 ? '99+' : messagePage + '') : '',
                    })
                } else {
                    uni.removeTabBarBadge({
                        index: 1,
                    })
                }
                if (minePage) {
                    uni.setTabBarBadge({
                        index: 2,
                        text: minePage + '',
                    })
                } else {
                    uni.removeTabBarBadge({
                        index: 2,
                    })
                }
                // #ifdef APP-PLUS
                plus.runtime.setBadgeNumber(messagePage + minePage)
                // #endif
            })
        },
        // 动态配置导航栏按钮
        jump() {
            uni.navigateTo({
                url: `/pages/index/comp/monitoringPoint`,
            })
        },
        backToTop() {
            uni.pageScrollTo({
                scrollTop: 0,
                duration: 300,
            })
            this.showBackTop = false
        },
    },
    onPageScroll(e) {
        this.showBackTop = e.scrollTop > 200
    },
    onLoad() {
        // #ifdef APP-PLUS
        checkAppUpdate()
        // #endif


        // 页面加载时，动态配置导航栏按钮
        if (!uni.getStorageSync(this.$cacheKey.access_token)) {
            uni.reLaunch({
                url: '/pages/user/login',
                success: () => {
                    // #ifdef APP-PLUS
                    plus.navigator.closeSplashscreen()
                    // #endif
                },
            })
        } else {
            setTimeout(() => {
                // #ifdef APP-PLUS
                plus.navigator.closeSplashscreen()
                // #endif
            }, 1000)
        }
        this.timer = setInterval(this.getDevCount, 1000 * 60) // 定时请求

        this.store =
            uni.getStorageSync(this.$cacheKey.userInfo).authorities === 'engineering_user'
                ? this.DataSource('/cs-harmonic-boot/homePage/getEngineeringHomePage')
                : this.DataSource('/cs-device-boot/EquipmentDelivery/queryEquipmentByProject')
        // #ifdef APP-PLUS
        setTimeout(() => {
            // 获取nav高度
            uni.createSelectorQuery()
                .select('.uni-navbar')
                .boundingClientRect((rect) => {
                    this.navTabHeight = rect.height
                    console.log('calc(100vh - ' + this.navTabHeight + ')')
                })
                .exec()
        }, 1000)
        // #endif
    },
    onShow() {


        this.userInfo = uni.getStorageSync(this.$cacheKey.userInfo)

        let access_token = uni.getStorageSync(this.$cacheKey.access_token)
        console.log(access_token)
        if (!access_token) {
            uni.reLaunch({
                url: `/pages/user/login`,
            })
        } else {
            this.init()
        }
    },
    mounted() {
        uni.setTabBarItem({
            index: 2,
            visible: true,
        })
        if (uni.getStorageSync(this.$cacheKey.userInfo).authorities === 'tourist') {
            uni.setTabBarItem({
                index: 2,
                visible: false,
            })
            uni.showToast({
                title: '已同步设备历史数据',
                icon: 'none',
            })
        }
    },
}
</script>
<style lang="scss" scoped>
.popup-content {
    background: #fff;
}

.index {
    padding: 20rpx 0 0;
}

.canneng-index-title {
    padding: 0 20rpx;
    /* font-weight: 500; */
    display: flex;
    align-items: center;
}

.canneng-index-title-with-icon {
    display: inline-flex;
    align-items: center;
    gap: 8rpx;
    font-size: 30rpx;
}

/deep/ .uni-card {
    background: $uni-theme-white;
}

/deep/ .uni-drawer__content {
    width: 100vw !important;
}

.nav-menu {
    height: 40rpx;
    padding: 4rpx 20rpx;
    // margin-left: 20rpx;
    // margin-bottom: 20rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    border-radius: 8rpx;
    background: #ebeaec;
    color: #666;

    &-active {
        background: #dfe5f7;
        color: $uni-theme-color;
    }

    &-btn {
        background: $uni-theme-color;
        color: #fff;
    }

    margin-left: auto;
}

.back-top {
    position: fixed;
    right: 30rpx;
    bottom: 60rpx;
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background: #376cf3;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 16rpx rgba(55, 108, 243, 0.35);
    z-index: 1;
}
</style>
