<template>
    <Cn-page :loading="loading">
        <template slot="body">
            <view class="device">
                <view class="nav" :style="{ top: navTabHeight + 'px' }">
                    <view class="nav-menu" @click="selectEngineering"
                    >{{
                            select.engineeringName
                                ? select.engineeringName.length > 6
                                    ? select.engineeringName.substring(0, 6) + '...'
                                    : select.engineeringName
                                : '全部工程'
                        }}
                        <uni-icons type="bottom" size="14"></uni-icons>
                    </view>
                    <picker
                        @change="projectNameChange"
                        @cancel="select.selectProject = false"
                        :value="select.projectNameIndex"
                        :range="filterProjectList"
                        range-key="text"
                        v-if="select.engineeringId"
                    >
                        <view class="nav-menu" @click="select.selectProject = true">
                            {{
                                select.projectName
                                    ? select.projectName.length > 6
                                        ? select.projectName.substring(0, 6) + '...'
                                        : select.projectName
                                    : '全部项目'
                            }}
                            <uni-icons type="top" size="14" v-if="select.selectProject"></uni-icons>
                            <uni-icons type="bottom" size="14" v-else></uni-icons>
                        </view>
                    </picker>
                    <picker
                        @change="runStatusChange"

                        :value="select.runStatusIndex"
                        :range="projectType"
                        range-key="text"
                    >
                        <view class="nav-menu">
                            {{
                                select.runStatusName
                                    ? select.runStatusName.length > 12
                                        ? select.runStatusName.substring(0, 12) + '...'
                                        : select.runStatusName
                                    : '全部状态'
                            }}
                            <uni-icons type="top" size="14" v-if="select.runStatusSelect"></uni-icons>
                            <uni-icons type="bottom" size="14" v-else></uni-icons>
                        </view>
                    </picker>
                </view>

                <view class="nav" style="padding: 0 10px !important">
                    <view style="flex: 1"></view>
                    <template v-if="transfer || share">
                        <view class="nav-menu nav-menu-btn" @click="cancel">取消</view>
                        <view class="nav-menu nav-menu-btn" @click="submit">确定</view>
                    </template>
                    <template v-else-if="store.data.length">
                        <view
                            class="nav-menu nav-menu-btn"
                            @click="selectDevice('transfer')"
                            v-if="
                                userInfo.authorities === 'app_vip_user' || userInfo.authorities === 'engineering_user'
                            "
                        >移交
                        </view>
                        <view
                            class="nav-menu nav-menu-btn"
                            @click="selectDevice('share')"
                            v-if="userInfo.authorities === 'app_vip_user'"
                        >分享
                        </view>
                    </template>
                </view>

                <view class="content device" :style="{ minHeight: minHeight }">
                    <uni-swipe-action>
                        <uni-swipe-action-item
                            v-for="(item, index) in store.data"
                            :threshold="0"
                            :right-options="item.isTop == 0 ? options1 : options12"
                            @click="bindClick($event, item)"
                        >
                            <Cn-device-card :device="item" :key="index">
                                <template v-slot:title>
                                    <!-- 卡片标题 -->
                                    <switch
                                        v-if="transfer || share"
                                        :checked="checkList.indexOf(item.equipmentId) > -1"
                                        style="transform: scale(0.8); position: relative; left: 20rpx"
                                        @change="switchChange(item)"
                                    />
                                    <view class="star-icon" v-else>
                                        <uni-icons type="search" size="25" color="#376cf3"></uni-icons>
                                    </view>
                                </template>
                            </Cn-device-card>
                        </uni-swipe-action-item>
                    </uni-swipe-action>
                    <uni-load-more
                        v-if="store.status == 'loading' || (store.data && store.data.length > 0)"
                        :status="store.status"
                    ></uni-load-more>
                    <Cn-empty v-else></Cn-empty>
                </view>
                <view class="back-top boxClick" v-show="showBackTop" @click="backToTop">
                    <uni-icons type="arrow-up" size="22" color="#fff"></uni-icons>
                </view>
            </view>
        </template>
    </Cn-page>
</template>
<script>
import { getProjectList } from '@/common/api/project'
import { queryDictData } from '@/common/api/dictionary'
import list from '@/common/js/list'
import { engineeringPinToTop } from '@/common/api/device'

export default {
    mixins: [list],
    data() {
        return {
            loading: true,
            transfer: false,
            share: false,
            checkList: [],
            select: {
                projectName: '',
                projectNameIndex: 0,
                projectSelect: false,
                engineeringName: '',
                engineeringId: '',
                runStatusName: '',
                runStatusIndex: 0,
                runStatusSelect: false,
            },
            userInfo: {},
            minHeight: 0,
            navTabHeight: 0,
            engineeringList: [],
            projectList: [],
            projectType: [
                {
                    text: '全部',
                    value: '',
                },
                {
                    text: '离线',
                    value: 1,
                },
                {
                    text: '在线',
                    value: 2,
                },
            ],
            pageOptions: {},
            showBackTop: false,
            options1: [
                {
                    text: '置顶',
                    style: {
                        backgroundColor: '#376cf3',
                    },
                },
            ],
            options12: [
                {
                    text: '取消',
                    style: {
                        backgroundColor: '#ccc',
                    },
                },
            ],
        }
    },
    watch: {
        select: {
            handler(val, oldVal) {
                if (this.loading) return
                this.store.params.projectId =
                    val.projectNameIndex === 0 ? '' : this.filterProjectList[val.projectNameIndex].value
                this.store.params.runStatus = val.runStatusIndex === 0 ? '' : this.projectType[val.runStatusIndex].value
                this.store.params.engineerId = val.engineeringId || ''
                this.store.reload()
            },
            deep: true,
        },
    },
    computed: {
        filterProjectList() {
            return this.projectList.filter(
                (item) => item.engineeringId === this.select.engineeringId || item.value === '-1',
            )
        },
    },
    created() {
        this.userInfo = uni.getStorageSync(this.$cacheKey.userInfo)
    },
    onLoad(options) {
        let engineering = uni.getStorageSync('engineering')
        this.pageOptions = options
        switch (options.type) {
            case 'onLineDevs':
                this.select.runStatusIndex = 2
                this.select.runStatusName = '在线'
                break
            case 'offLineDevs':
                this.select.runStatusIndex = 1
                this.select.runStatusName = '离线'
                break
            case 'currentOnLineDevs':
                this.select.runStatusIndex = 2
                this.select.engineeringName = engineering.name
                this.select.engineeringId = engineering.id
                this.select.runStatusName = '在线'
                break
            case 'currentOffLineDevs':
                this.select.runStatusIndex = 1
                this.select.engineeringName = engineering.name
                this.select.engineeringId = engineering.id
                this.select.runStatusName = '离线'
                break
            case 'allEngineering':
                this.select.engineeringName = ''
                this.select.engineeringId = ''
                break
            case 'nowEngineering':
                this.select.engineeringName = engineering.name
                this.select.engineeringId = engineering.id
                break
            default:
                break
        }
        this.init()
    },
    onShow() {
        let engineering = uni.getStorageSync('onceSelectEngineering')
        if (engineering) {
            uni.removeStorageSync('onceSelectEngineering')
            this.select.engineeringId = engineering.id
            this.select.engineeringName = engineering.name
            this.select.projectNameIndex = 0
            this.select.projectName = ''
            this.getProjectList()
        }
        this.store && this.store.reload()
    },
    methods: {
        bindClick(e, item) {
            engineeringPinToTop({
                targetId: item.equipmentId,
                targetType: 1,
                userId: uni.getStorageSync(this.$cacheKey.userInfo).userIndex,
            }).then((res) => {
                if (res.code == 'A0000') {
                    this.$util.toast('操作成功!')
                    this.store.search()
                } else {
                    this.$util.toast(res.message)
                }
            })
        },
        selectEngineering() {
            uni.navigateTo({
                url: '/pages/home/selectEngineering?from=once',
            })
        },
        deviceIcon(e) {
            let str = ''
            switch (e) {
                case 1:
                    str = '/static/device_bad.png'
                    break
                case 2:
                    str = '/static/device.png'
                    break
                default:
                    str = '/static/device.png'
                    break
            }
            return str
        },
        switchChange(e) {
            console.log(e)
            let index = this.checkList.indexOf(e.equipmentId)
            if (index > -1) {
                this.checkList.splice(index, 1)
            } else {
                this.checkList.push(e.equipmentId)
            }
        },
        cancel() {
            this.transfer = false
            this.share = false
            this.checkList = []
        },
        submit() {
            console.log(this.checkList)
            if (this.checkList.length === 0) {
                this.$util.toast('请选择设备')
                return
            }
            if (this.transfer) {
                uni.navigateTo({ url: '/pages/device/transfer?id=' + this.checkList.join(',') })
            } else if (this.share) {
                uni.navigateTo({ url: '/pages/device/share?id=' + this.checkList.join(',') })
            }
            this.cancel()
        },
        async init() {
            console.warn('init')
            this.getEngineeringList()
            this.getProjectList()
            this.getDeviceList()
        },
        getDeviceList() {
            this.store = this.DataSource('/cs-device-boot/EquipmentDelivery/queryEquipmentByProject')
            this.store.params.engineerId = this.select.engineeringId
            this.store.params.runStatus =
                this.select.runStatusIndex === 0 ? '' : this.projectType[this.select.runStatusIndex].value
            this.store.params.pageSize = 50
            this.store.firstCallBack = (res) => {
                this.loading = false
                uni.createSelectorQuery()
                    .select('.uni-navbar')
                    .boundingClientRect((rect1) => {
                        if (!rect1) return
                        this.navTabHeight = rect1.height
                        uni.createSelectorQuery()
                            .select('.nav')
                            .boundingClientRect((rect2) => {
                                if (!rect2) return
                                // #ifdef H5
                                this.minHeight = 'calc(100vh - ' + (this.navTabHeight + rect2.height + 50) + 'px)'
                                // #endif
                                // #ifdef APP-PLUS
                                this.minHeight = 'calc(100vh - ' + (this.navTabHeight + rect2.height) + 'px)'
                                console.log(this.minHeight)
                                // #endif
                            })
                            .exec()
                    })
                    .exec()
            }
            this.store.reload()
        },

        getProjectList() {
            getProjectList({
                pageNum: 1,
                pageSize: 9999,
                engineeringId: this.select.engineeringId,
            }).then((res) => {
                console.log(res)
                let arr = [
                    {
                        text: '全部项目',
                        value: '-1',
                    },
                    ...res.data.records.map((item) => {
                        return {
                            text: item.name,
                            value: item.id,
                            ...item,
                        }
                    }),
                ]
                this.projectList = arr
                uni.setStorageSync('projectList', arr)
            })
        },
        getEngineeringList() {
            this.engineeringList = uni.getStorageSync('engineeringList')
        },
        queryDictData() {
            queryDictData('项目类型').then((res) => {
                this.projectType = [
                    {
                        text: '全部类型',
                        value: '',
                    },
                    ...res.data.map((item) => {
                        return {
                            text: item.anotherName,
                            value: item.id,
                        }
                    }),
                ]
            })
        },
        submitFeedBack() {
            uni.navigateTo({ url: '/pages/home/feedback' })
        },
        runStatusChange(e) {
            this.select.runStatusSelect = false
            this.select.runStatusIndex = e.detail.value
            if (e.detail.value === 0) {
                this.select.runStatusName = ''
                return
            }
            this.select.runStatusName = this.projectType[e.detail.value].text
        },
        projectNameChange(e) {
            this.select.selectProject = false
            console.log(e)
            this.select.projectNameIndex = e.detail.value
            if (e.detail.value === 0) {
                this.select.projectName = ''
                return
            }
            this.select.projectName = this.projectList[e.detail.value].text
        },
        registerDevice() {
            uni.showModal({
                title: '提示',
                content: '请选择设备类型',
                confirmText: '直连设备',
                cancelText: '网关接入',
                cancelColor: '#007aff',
                success: ({ confirm, cancel }) => {
                    if (confirm) {
                        uni.navigateTo({
                            url: '/pages/device/new',
                        })
                    } else if (cancel) {
                        uni.navigateTo({
                            url: '/pages/gateway/list',
                        })
                    }
                },
            })
        },
        registerGateway() {
            uni.navigateTo({
                url: '/pages/gateway/new',
            })
        },
        navMenuClick(index) {
            this.navMenuActive = index
        },
        jump(item) {
            console.log(12321, item)
            uni.navigateTo({
                url:
                    '/pages/device/APF/detail?id=' +
                    item.equipmentId +
                    '&isPrimaryUser=' +
                    item.isPrimaryUser +
                    '&ndid=' +
                    item.ndid,
            })
        },
        selectDevice(type) {
            if (this.store.data.findIndex((item) => item.isPrimaryUser === '1') === -1) {
                this.$util.toast('没有可操作的设备')
            } else {
                this[type] = true
            }
        },
        backToTop() {
            uni.pageScrollTo({
                scrollTop: 0,
                duration: 300,
            })
            this.showBackTop = false
        },
    },
    onPageScroll(e) {
        this.showBackTop = e.scrollTop > 200
    },
}
</script>
<style lang="scss">
/deep/ .button-group--right {
    padding: 0 0 20rpx;
}

.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>
