<template>
    <div class='equipment-facilities'>
        <!-- 左侧菜单 -->
        <SystemMenu class='left' @chooseSystem='changeSystem' />
        <div class='right' v-show='showRight'>
            <div class='top' :key='listKey'>
                <!-- <van-cell :title='`消防电系统原理示意图`' :border='false' is-link :value='`19条`' @click='handleClick' />
                <van-cell :title='`消防喷淋系统示意图`' :border='false' is-link value='无' @click='handleClick' />
                <van-cell :title='`消防窗喷系统示意图`' :border='false' is-link value='无' @click='handleClick' />
                <van-cell :title='`配电室低压柜及出线明细`' :border='false' is-link value='无' @click='handleClick' />
                <van-cell :title='`消防泵房引出管路分布图`' :border='false' is-link value='无' @click='handleClick' />
                <van-cell :title='`楼层分布+其他数据`' :border='false' is-link value='无' @click='handleClick' />-->
                <van-cell
                    v-for='(item,index ) in listData[currentSmsxt]'
                    :key='index'
                    :title='item.text'
                    :border='false'
                    is-link
                    :class='item.class'
                    :arrow-direction='item.arrow'
                    :value='`${item.count||""}`'
                    v-show='!item.hide'
                    @click='handleClick(item)'
                />
            </div>
            <!-- 分割线 -->
            <div class='divider'></div>
            <!-- 设备卡片 -->
            <div class='card-container'>
                <m-card
                    class='card'
                    :type='item.type'
                    :name='item.name'
                    :unit='item.unit'
                    :total='item.total'
                    :number='item.number'
                    v-for='item in cardList'
                    :key='item.category_name'
                    @click.native='goToEquipment(item)'
                />
                <!-- 更多主要设备 -->
                <m-card class='card' :type='4' name unit v-if='!showMoreCardList' :total='0' @click.native='goToMoreEquipment' />
                <m-card
                    v-show='moreCardList.length && showMoreCardList'
                    class='card'
                    :type='item.type'
                    :name='item.name'
                    :unit='item.unit'
                    :total='item.total'
                    :number='item.number'
                    v-for='(item,index) in cardList'
                    :key='index'
                    @click.native='goToEquipment(item)'
                />
            </div>
            <div class='close' v-show='showMoreCardList' @click='showMoreCardList=false'>收起</div>
        </div>
        <!-- 原理图 -->
        <ImagePreview :key='imgKey' class='update-img-preview' :visible.sync='showImgPreview' :imgList='imgList' />
    </div>
</template>
<script>
import Vue from 'vue'
import { Cell, Toast } from 'vant'
Vue.use(Cell).use(Toast)
import { mapGetters, mapMutations } from 'vuex'
import { querySystemCount, querySystemCard, querySystemImage, querySystemTuJianImage, queryRoomCount, queryMoreAsset } from '@/api/equipmentList'

import { appGraphElementQuery } from '@/api/public'
import MCard from '@/components/equipmentFacilities/Card'
import SystemMenu from '@/components/systemMenu'
import ImagePreview from '@/components/ImagePreview'
import { cloneDeep } from 'lodash'
export default {
    name: 'EquipmentFacilities',
    props: {},
    components: { SystemMenu, MCard, ImagePreview },
    computed: {
        ...mapGetters(['plazaId', 'smsxt', 'categoryId', 'floorsArr']),
    },
    data() {
        return {
            currentSmsxt: '1001', //系统值,默认供电系统
            systemText: '供电系统',
            module: '1002', // 广场管理说明书图片上传视图查询条件  1001 项目概况 1004其他事项 1003楼层分布 1002 设备设施
            neTypename: '位置布置图',
            listData: {
                //上部列表数据
                1001: [
                    //供电
                    { text: '供电系统原理图', dataType: 'img', typecode: '2010', count: '无' },
                    { text: '机房平面布置图', dataType: 'room' },
                    { text: '配电室低压出线柜及出线明细', dataType: 'dyg', class: 'dyg' },
                    { text: '楼层分布', dataType: 'floor', value: ' ' },
                    { text: '电井控制商铺范围', dataType: 'electricWell' },
                    { text: '主要设备清单', dataType: 'mainEquipment' },
                    { text: '重要维修及重要维保', dataType: 'wxwb' },
                    { text: '其他事项', dataType: 'otherMatter' },
                ],
                1002: [
                    //暖通
                    { text: '空调系统原理图', dataType: 'img', typecode: '2011', count: '无' },
                    { text: '分水器支路分布图', dataType: 'fbt', categoryId: 'FZQZL' },
                    { text: '机房平面布置图', dataType: 'room' },
                    { text: '楼层分布', dataType: 'floor' },
                    { text: '主要设备清单', dataType: 'mainEquipment' },
                    { text: '重要维修及重要维保', dataType: 'wxwb' },
                    { text: '其他事项', dataType: 'otherMatter' },
                ],
                1003: [
                    //消防
                    { text: '系统原理图', id: '1003', dataType: 'moreImg', count: '', arrow: 'down', class: 'more-img-cell' },
                    { text: '', dataType: '', count: '', arrow: 'none', class: 'more-img-cell-border' }, // 1px边框
                    { text: '消防电系统原理示意图', dataType: 'img', typecode: '2014', count: '无', hide: true, class: 'img-cell' },
                    { text: '消防喷淋系统示意图', dataType: 'img', typecode: '2015', count: '无', hide: true, class: 'img-cell' },
                    { text: '消防窗喷系统示意图', dataType: 'img', typecode: '2016', count: '无', hide: true, class: 'img-cell' },
                    { text: '消火栓系统示意图', dataType: 'img', typecode: '2017', count: '无', hide: true, class: 'img-cell' },
                    { text: '消防泵房引出管路分布图', dataType: 'fbt', categoryId: 'XFBFYCFL' },
                    { text: '机房平面布置图', dataType: 'room' },
                    { text: '楼层分布+附加数据', dataType: 'floor' },
                    { text: '主要设备清单', dataType: 'mainEquipment' },
                    { text: '重要维修及重要维保', dataType: 'wxwb' },
                    { text: '其他事项', dataType: 'otherMatter' },
                ],
                1004: [
                    //弱电
                    { text: '系统原理图', id: '1004', dataType: 'moreImg', count: '', arrow: 'down', class: 'more-img-cell' },
                    { text: '', dataType: '', count: '', arrow: 'none', class: 'more-img-cell-border' }, // 1px边框
                    { text: '门禁管理系统原理图', dataType: 'img', typecode: '2019', count: '无', hide: true, class: 'img-cell' },
                    { text: 'BA楼宇智能化系统原理图', dataType: 'img', typecode: '2020', count: '无', hide: true, class: 'img-cell' },
                    { text: '机房平面布置图', dataType: 'room' },
                    { text: '楼层分布+附加数据', dataType: 'floor' },
                    { text: '主要设备清单', dataType: 'mainEquipment' },
                    { text: '重要维修及重要维保', dataType: 'wxwb' },
                    { text: '其他事项', dataType: 'otherMatter' },
                ],
                1005: [
                    //给排水
                    { text: '系统原理图', id: '1005', dataType: 'moreImg', count: '', arrow: 'down', class: 'more-img-cell' },
                    { text: '', dataType: '', count: '', arrow: 'none', class: 'more-img-cell-border' }, // 1px边框
                    { text: '给水系统原理示意图', dataType: 'img', typecode: '2021', count: '无', hide: true, class: 'img-cell' },
                    { text: '排水系统原理示意图', dataType: 'img', typecode: '2022', count: '无', hide: true, class: 'img-cell' },
                    { text: '机房平面布置图', dataType: 'room' },
                    { text: '楼层分布', dataType: 'floor' },
                    { text: '主要设备清单', dataType: 'mainEquipment' },
                    { text: '重要维修及重要维保', dataType: 'wxwb' },
                    { text: '其他事项', dataType: 'otherMatter' },
                ],
                1006: [
                    //电梯
                    { text: '系统原理图', id: '1006', dataType: 'moreImg', count: '', arrow: 'down', class: 'more-img-cell' },
                    { text: '', dataType: '', count: '', arrow: 'none', class: 'more-img-cell-border' }, // 1px边框
                    { text: '扶梯原理图', dataType: 'img', typecode: '2023', count: '无', hide: true, class: 'img-cell' },
                    { text: '直梯原理图', dataType: 'img', typecode: '2024', count: '无', hide: true, class: 'img-cell' },
                    { text: '楼层分布', dataType: 'floor' },
                    { text: '主要设备清单', dataType: 'mainEquipment' },
                    { text: '重要维修及重要维保', dataType: 'wxwb' },
                    { text: '其他事项', dataType: 'otherMatter' },
                ],
                1007: [
                    // 燃气
                    { text: '燃气系统原理示意图', dataType: 'img', typecode: '2025', count: '无' },
                    { text: '楼层分布', dataType: 'floor' },
                    { text: '主要设备清单', dataType: 'mainEquipment' },
                    { text: '重要维修及重要维保', dataType: 'wxwb' },
                    { text: '其他事项', dataType: 'otherMatter' },
                ],
                1008: [
                    // 土建

                    // 2026	东外立面
                    // 2029	北外立面
                    // 2028	南外立面
                    // 2027	西外立面
                    // { text: '建筑立面图', dataType: 'img', typecode: '2026', count: '无' },
                    { text: '建筑立面图', dataType: 'img', typecode: ['2026', '2027', '2028', '2029'], count: '无' },
                    { text: '楼层分布', dataType: 'floor' },
                    { text: '其他事项', dataType: 'otherMatter' },
                ],
            },
            listKey: `list_${new Date().getTime()}`,
            cardList: [],
            moreCardList: [],
            showMoreCardList: false,
            showRight: false, //是否显示右侧内容
            showImgPreview: false, //是否展示图片预览
            imgList: [], //图片数组
            imgKey: `img${new Date().getTime()}`,
            fbtArr: [], //分布图使用的楼层数据
        }
    },
    watch: {
        // 前五个系统更改,查询机房平面布置图数量
        smsxt: {
            handler(newV, oldV) {
                let smsxtArr = ['1001', '1002', '1003', '1004', '1005']
                if (smsxtArr.includes(newV)) {
                    // 查询机房平面布置图数量
                    this.getRoomCount()
                }
                // 暖通,消防,查询 分水器支路分布图,消防泵房引出管路分布图 对应的楼层图例数据
                if (['1002', '1003'].includes(newV)) {
                    let dict = {
                        1002: 'FZQZL',
                        1003: 'XFBFYCFL',
                    }
                    this.getTuliData({ smsxt: newV, system_code: dict[newV] })
                }
            },
            immediate: true,
        },
    },
    async created() {
        window.vm = this
        // let initSys = {
        //     text: '供电',
        //     categoryId: 'GDXT',
        //     smsxt: '1001',
        // }
        this.systemText = '供电系统'
        this.currentSmsxt = '1001'
        this.SETCATEGORYID('GDXT')
        this.SETSMSXT('1001')
        this.showRight = false
        // 查询图片数量,设备卡片
        await Promise.all([this.getPicCount(), this.getCard()])
        this.showRight = true
        // this.changeSystem(initSys)
    },
    beforeMount() {},
    mounted() {},
    methods: {
        ...mapMutations(['SETCATEGORYID', 'SETSMSXT']),
        /**
         * 左侧菜单切换事件
         * @param { String } text 系统名称
         * @param { String } category 系统拼音简称  NTXT ...
         * @param { String }  currentSmsxt 系统id? 1001 - 1008
         */
        async changeSystem({ text, categoryId, smsxt }) {
            this.showMoreCardList = false
            this.showRight = false
            this.currentSmsxt = smsxt
            this.systemText = text + '系统'
            // console.log(this.systemText)
            /**
             * 查询图片数量,设备卡片
             */
            await Promise.all([this.getPicCount(), this.getCard()])
            this.showRight = true
        },
        /**
         * 查询图片数量
         */
        async getPicCount() {
            let getParams = {
                plazaId: this.plazaId,
                system: this.currentSmsxt,
            }
            let res
            Toast.loading({
                message: '加载中...',
                forbidClick: true,
            })
            try {
                res = await querySystemCount({ getParams })
            } catch (error) {}
            if (!res?.data) {
                return false
            }
            let data = res.data

            let currentSys = this.listData[this.currentSmsxt]
            // console.log(this.listData, currentSys)
            currentSys.map((item) => {
                if (item.dataType === 'img') {
                    let detail = data.filter((v) => v.typecode == item.typecode)[0]
                    // console.log(detail)
                    item.count = detail?.cnt ? detail?.cnt + '张' : '无' // + '张' || '无'
                }
            })
            // console.log(this.currentSmsxt)
            // 土建装饰单独处理 将东西南北合并到一起
            if (this.currentSmsxt === '1008') {
                // console.log(data)
                let count = data.reduce((prev, current) => {
                    return prev + current.cnt
                }, 0)
                // console.log(count)
                currentSys.map((item) => {
                    if (item.dataType === 'img') {
                        item.count = count ? count + '张' : '无' // + '张' || '无'
                    }
                })
            }
            // console.log(currentSys)
            this.listKey = `list_${new Date().getTime()}`
            this.$set(this.listData, this.currentSmsxt, currentSys)
            Toast.clear()
            // console.log(this.listData)
        },
        /**
         * 查询机房平面布置图数量
         */
        async getRoomCount() {
            let getParams = {
                plazaId: this.plazaId,
                systemCode: this.smsxt,
            }
            // 查询机房平面布置图数量
            let res = await queryRoomCount({ getParams })
            // 取出listData中对应的系统数据
            let data = this.listData[this.smsxt]
            data.map((item, index, arr) => {
                if (item.dataType === 'room') {
                    item.count = res?.count ? res?.count + '张' : '无'
                }
            })
            this.listKey = `list_${new Date().getTime()}`
        },
        /**
         * 分水器支路分布图,消防泵房引出管路分布图 对应的楼层图例数据
         */
        async getTuliData({ smsxt, system_code }) {
            let params = {
                BuildingID: '1',
                CategoryID: system_code,
                ProjectID: this.plazaId,
                Floors: this.floorsArr.map((item) => {
                    return {
                        FloorId: item.gname,
                        FloorName: item.code,
                    }
                }),
            }
            // console.log(params)
            let res = await appGraphElementQuery(params)
            // console.log(res)
            if (!res?.Data) {
                return false
            }
            let Data = res.Data || []
            // 过滤有Statistics的条数
            Data = Data.filter((v) => v.Statistics?.length)

            let fbtArr = []
            Data.map((item) => {
                fbtArr.push({
                    code: item.FloorName,
                    gname: item.FloorId,
                })
            })
            this.fbtArr = fbtArr
            let count = Data.length ? Data.length + '张' : '无'
            let systemData = this.listData[smsxt]
            console.log(systemData)
            systemData.map((item, index, arr) => {
                if (item.dataType === 'fbt') {
                    arr[index].count = count
                }
            })
            this.$set(this.listData, smsxt, systemData)
            this.listKey = `list_${new Date().getTime()}`
            //     .then(res => {
            //   this.floorData = res.Data.map(floor => {
            //     floor.Open = false;
            //     return floor;
            //   });
            // })
        },
        /**
         * 查询设备卡片
         */
        async getCard() {
            this.cardList = []
            let getParams = {
                plazaId: this.plazaId,
                smsxt: this.smsxt,
            }
            let res
            try {
                res = await querySystemCard({ getParams })
            } catch (error) {}
            // console.log('设备卡片')
            // console.log(res.data)
            if (!res && !res?.data?.length) {
                return false
            }
            let data = res.data
            // 取出assetTypeList
            let cardList = data[0]?.assetTypeList || []
            // console.log(cardList)
            cardList.map((item) => {
                item.total = item.asset_num // card 第二行台数
                item.name = item.category_name //card 第一行名称
                // 设备卡片单位处理
                if (item.name === '屋面logo') {
                    item.unit = '个'
                } else if (item.name === '玻璃护栏') {
                    item.unit = '段'
                } else {
                    item.unit = '台'
                }
                /**
                 * type 1: 正常运维 2:重要维保 3:重要维修
                 */
                // 默认正常
                item.type = 1
                item.number = 0
                if (item.is_exception || item.is_exception_num) {
                    // 有异常
                    item.type = 3
                    item.number = item.is_exception_num
                } else if (item.is_detecting || item.is_detecting_num) {
                    // 检测中
                    item.type = 2
                    item.number = item.is_detecting_num
                }
            })
            this.cardList = cardList
            // console.log('=============')
            // console.log(this.cardList)
            // console.log('=============')
        },
        handleClick(item) {
            switch (item.dataType) {
                // 点击系统原理图, 显示/隐藏 具体的原理图
                case 'moreImg':
                    this.handleMoreImg(item)
                    break
                // 原理图
                case 'img':
                    this.handleImg(item)
                    break
                // 机房平面布置图
                case 'room':
                    this.handleRoom(item)
                    break
                // 主要设备清单
                case 'mainEquipment':
                    this.handleMainAsset(item)
                    break
                // 维修维保
                case 'wxwb':
                    this.handleWxwb(item)
                    break
                // 楼层分布
                case 'floor':
                    this.handleFloor(item)
                    break
                case 'fbt':
                    this.handleFbt(item)
                    break
                // 电井间商铺控制范围
                case 'electricWell':
                    this.hanldeElectricWell(item)
                    break
                // 配电室低压柜及出线明细
                case 'dyg':
                    this.hanldeDyg(item)
                    break
                // 其他事项
                case 'otherMatter':
                    this.handleOtherMatter(item)
                    break
                default:
                    break
            }
        },
        /**
         * 点击系统原理图
         * 显示隐藏详细的系统原理图
         */
        handleMoreImg(item) {
            console.log(item)
            const currentItem = this.listData[item.id]
            if (item.arrow === 'down') {
                currentItem.map((v) => {
                    v.dataType === 'img' && (v.hide = false)
                })
                item.arrow = 'up'
            } else {
                currentItem.map((v) => {
                    v.dataType === 'img' && (v.hide = true)
                })
                item.arrow = 'down'
            }
        },
        /**
         * 显示原理图预览
         */
        handleImg(item) {
            if (item.count === '无') {
                return false
            }
            this.showImage(item)
        },
        /**
         *  显示原理图
         */
        async showImage(item) {
            console.log('显示原理图')
            console.log(item)
            this.imgList = []
            this.imgKey = 'img_' + new Date().getTime()
            if (Array.isArray(item.typecode)) {
                return this.getTuJianImage(item)
            }
            let getParams = {
                plazaId: this.plazaId,
                module: this.module,
                neTypename: '位置布置图',
                typecode: item.typecode,
                system: this.smsxt,
            }
            let res = await querySystemImage({ getParams })
            // console.log(res)
            if (!res && !res?.data) {
                return false
            }
            let data = res.data
            let imgList = []
            data.map((item) => {
                imgList.push(item.url)
            })
            this.imgList = imgList

            imgList.length && (this.showImgPreview = true)
        },
        /**
         * 土建立面图(typecode为数组,查询多种图)
         */
        async getTuJianImage(item) {
            let data = {
                    plazaId: this.plazaId,
                    module: this.module,
                    neTypename: '位置布置图',
                    system: this.smsxt,
                },
                postParams = {
                    typecode: item.typecode,
                }
            let res = await querySystemTuJianImage({ data, postParams })
            // console.log(res)
            if (!res && !res?.data) {
                return false
            }
            let resData = res.data
            let imgList = []
            resData?.data.map((item) => {
                imgList.push(item.url)
            })
            this.imgList = imgList
            imgList.length && (this.showImgPreview = true)
        },
        /**
         * 跳转 机房平面布置图
         */
        handleRoom(item) {
            if (!item.count || item.count === '无') {
                return false
            }
            this.$router.push({ name: 'EngineRoomPicture', params: {} })
        },

        handleMainAsset() {
            this.$router.push({ name: 'MainEquipment' })
        },
        handleWxwb() {
            this.$router.push({ name: 'MaintenanceRecordView', params: { isInit: true } })
        },
        /**
         * 配电室低压柜及出线明细
         */
        hanldeDyg() {
            this.$router.push({ name: 'LowVoltageCabinet', params: { initPage: true } })
        },
        /**
         * 其他事项
         */
        handleOtherMatter(item) {
            this.$router.push({ name: 'OtherMatters', params: {} })
        },
        /**
         * 跳转 楼层分布
         */
        handleFloor(item) {
            let title = this.systemText + ' - 楼层分布'

            this.$router.push({ name: 'SystemFloor', query: { title } })
        },
        /**
         * 分水器支路分布图
         */
        handleFbt(item) {
            console.log(item)
            let currentSystem = this.listData[this.smsxt]
            let fbt = currentSystem.filter((v) => v.dataType === 'fbt')[0]
            if (!fbt || fbt.count === '无') {
                return false
            }
            const { categoryId, text } = item
            this.SETCATEGORYID(categoryId)
            let query = { title: text }
            // mockData
            // this.fbtArr = [
            //     {
            //         code: 'RF',
            //         gname: 'g80',
            //     },
            // ]
            if (this.fbtArr.length) {
                query.fbtArr = JSON.stringify(this.fbtArr)
                query.fbt = true
            }
            this.$router.push({ name: 'SystemFloor', query })
        },
        /**
         * 跳转 电井间控制商铺范围
         */
        hanldeElectricWell(item) {
            this.$router.push({ name: 'ElectricWell', params: {} })
        },
        /**
         * 点击卡片,跳转设备列表页面
         */
        goToEquipment(data) {
            console.log(data)
            let { name, category_code } = data
            this.$router.push({ name: 'EquipmentList', query: { title: name, category_code }, params: { from: 'indexPage' } })
        },
        /**
         * 点击更多设备卡片,跳转设备列表页面
         */
        async goToMoreEquipment(e) {
            // this.$router.push({ name: 'MoreEquipmentList', params: {} })
            console.log(e.target)
            // TODO: 更多设备
            return false
            this.showMoreCardList = true
            this.moreCardList = cloneDeep(this.cardList)
            console.log()
            //
            // let data = {
            //     // page: 1,
            //     // size: 400,
            //     // subPage: 1,
            //     // subSize: 100,
            //     plazaId: this.plazaId,
            //     onlyMainAsset: true,
            // }
            // let postParams = {
            //     system_code: this.smsxt,
            // }
            // let res = await queryMoreAsset({ data, postParams })
            // if (!res?.data?.data) {
            //     return false
            // }
            // console.log(res.data.data)
        },
    },
}
</script>
<style lang='less' scoped>
.equipment-facilities {
    width: 100%;
    height: calc(100% - 100px);
    padding: 0;
    display: flex;
    .left {
        width: 80px;
        height: 100%;
    }
    .right {
        flex: 1;
        height: 100%;
        padding: 16px 16px 16px 12px;
        overflow: auto;
        .top {
            width: 100%;
            /deep/ .van-cell {
                font-size: 14px;
                font-weight: 400;
                color: #333333;
                background: #f8f9fa;
                border-radius: 4px;
                margin-bottom: 4px;
                .van-cell__value {
                    width: 40px;
                    max-width: 50px;
                    flex: none;
                }
            }
            // 系统原理图
            .more-img-cell {
                margin-bottom: 0 !important;
            }
            .more-img-cell-border {
                height: 1px;
                overflow: hidden;
                width: calc(100% - 20px);
                background: #fff;
                border: none;
                border-radius: 0;
                border-bottom: 1px solid #e4e6e7;
                margin: 0;
                line-height: 0;
                font-size: 0;
                padding: 0;
                margin: 0 auto;
            }
            .img-cell {
                background: #eff0f1;
                border-radius: 0;
            }
            .img-cell:not(:last-child) {
                margin-bottom: 0 !important;
            }
            .dyg {
                /deep/ .van-cell__value {
                    width: 0;
                }
            }
        }
        .divider {
            border-bottom: 1px solid #e6e6e6;
            margin: 20px 0 10px 0;
        }
        .card-container {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            flex-flow: wrap;
            // .card {
            //     flex: 1;
            //     width: calc(50% - 10px);
            //     margin: 0 10px 10px 0;
            //     min-width: calc(50% - 10px); // 加入这两个后每个item的宽度就生效了
            //     max-width: calc(50% - 10px); // 加入这两个后每个item的宽度就生效了
            //     height: 110px;
            //     margin-right: auto;
            // }
            .card {
                width: calc(50% - 5px);
                margin-bottom: 9px;
                height: 90px;
            }
            .card:not(:nth-child(2n)) {
                margin-right: 9px;
            }
        }
        .close {
            position: fixed;
            background-color: #fff;
            width: 50px;
            height: 50px;
            line-height: 50px;
            border-radius: 50px;
            text-align: center;
            bottom: 80px;
            right: 30px;
        }
    }
}
</style>