<template>
    <section class="homeAllApp">
        <!-- {{ sortedApps }} -->
        <div class="htaTitle"><strong>所有应用</strong><em @click="markertApp" v-if="network"><img
                    src="~@/assets/images/other/AppMarketIcon.png">发现更多精品应用</em></div>
        <section class="hAllContainer" v-if="organizationLevels&&organizationLevels.includes('Premium')">
            <div class="htaBox" v-for="(item, index) in sortedApps" :key="index">
                <div class="htH3">{{ item.category }}</div>
                <ul>
                    <li v-for="(its, i) in item.apps" :key="i" @click="loadAppMenu(its.appCode, its.appName)">
                        <span class="imgLeft"><img :src="its.appLogo.indexOf('https') > -1 ? its.appLogo : contextUrl + its.appLogo"
                                v-if="its.appLogo"></span>
                        <span><strong>{{ its.appName }}</strong></span>
                    </li>
                </ul>
            </div>
            <div class="notApp" v-if="sortedApps.length == 0">
                <p><img src="~@/assets/images/other/notAppIcon.png"></p>
                <p class="textinfo">暂无可操作的应用，可联系组织或部门管理员为您授权</p>
            </div>            
        </section>            
        <section class="hAllContainer" v-else>
            <div class="htaBox" v-for="(item, index) in appcateArrList" :key="index">
                <div class="htH3">{{ item.title }}</div>
                <ul>
                    <li v-for="(its, i) in item.children" :key="i" @click="loadAppMenu(its.appid, its.name)">
                        <span class="imgLeft"><img :src="its.img.indexOf('https') > -1 ? its.img : contextUrl + its.img"
                                v-if="its.img"></span>
                        <span><strong>{{ its.name }}</strong></span>
                    </li>
                </ul>
            </div>
            <div class="notApp" v-if="appcateArrList.length == 0">
                <p><img src="~@/assets/images/other/notAppIcon.png"></p>
                <p class="textinfo">暂无可操作的应用，可联系组织或部门管理员为您授权</p>
            </div>            
        </section>
    </section>
</template>
<script>
import { Loading } from 'element-ui';
export default {
    inject: [
        'addTab',
    ],
    data() {
        return {
            applistArr: [],
            tabs: [],
            appcateArrList: [],//工作台应用分类
            contextUrl: obpmConfig.obpmFilePath,
            network: true,//获取__network__全局变量状态，判断显示隐藏
            homeTemplateBoradType: localStorage.getItem('homeTemplateBoradType') || '',
            categories:[],//获取应用级别自定义角色授权的应用
            apps:[],
            organizationLevels:null,
        }        
    },
    computed: {
        sortedApps() {
            return this.categories
            .map(category => ({
                category,
                apps: this.apps
                .filter(app => app.category === category)
                .sort((a, b) => a.appSeq - b.appSeq)
            }))
        }
    },
    mounted() {
        this.network = localStorage.getItem("__network__") == 'true' ? true : false //获取__network__全局变量状态，判断显示隐藏
        if (this.homeTemplateBoradType == 'rtpayTemplate') {
            this.network = false
        }
        if (localStorage.getItem('HomeApplist_board') && JSON.parse(localStorage.getItem('HomeApplist_board')).employeeIdStr == localStorage.getItem('employeeId')) {//前端走缓存，职员id一样，多次刷新不走接口，走缓存
            this.appcateArrList = JSON.parse(localStorage.getItem('HomeApplist_board')).appcateArrListStr
        }
        else {
            this.organizationLevels=organizationLevels.split(',')//obpm.config.js定义全局变量organizationLevels
            console.log('organizationLevels',organizationLevels)//obpm.config.js定义全局变量organizationLevels
            if(this.organizationLevels&&this.organizationLevels.includes('Premium')){
                this.appLevelsList()
            }else{
                this.applistIframe()//工作台查询应用分类
            }
        }
    },
    methods: {
        markertApp() {//点击应用市场跳转         
            var param = {
                id: "applicationMarket",
                name: '应用市场',
                linkType: 'applicationMarket',
                actionContent: "",
                icon: "-1",
                key: ""
            }
            console.log(this.$listeners)
            this.addTab(param)
        },
        applistIframe() {//查询应用列表
            let data = {//只查询电脑端应用
                search_clientype: "电脑端",
            }
            this.$api.getApplicationsAll(data, {
                onSucess: response => {

                    if (response.data && response.data.errmsg == "ok") {
                        console.log(response.data)
                        if (response.data.data.data.length) {
                            let arr = []
                            response.data.data.data.forEach((item, index) => {
                                let obj = {}
                                let obj2 = {}
                                obj.title = item.items['__4ReuvgLxTKieJDzGu2L'].value
                                obj.cateSort = item.items['__sJO2jdvlNEznauT5KQa'].value //分类排序  

                                obj.children = []
                                obj2.img = item.items['__oTDoKOfuYRsmXS7DfDk'].value ? JSON.parse(item.items['__oTDoKOfuYRsmXS7DfDk'].value)[0].path : ""  //应用图标
                                obj2.name = item.items['__M0NXUq24HGrzQrmjLwj'].value  //应用名称 
                                obj2.appid = item.items['__ZLG2HsnA374L6Ww4X6P'].value //应用id   
                                obj2.appSort = item.items['__zsh5fkZEXwof08KVNMe'].value //应用id

                                obj.children.push(obj2)
                                arr.push(obj)

                            })
                            console.log(arr)
                            arr.sort((a, b) => { return Number(a.cateSort) - Number(b.cateSort) }) //分类排序cateSort 

                            const titleMap = {}
                            const transferObj = arr.reduce((prev, next) => {
                                if (titleMap[next.title]) {
                                    prev[next.title].children.push(...next.children)
                                } else {
                                    titleMap[next.title] = true
                                    prev[next.title] = { children: next.children }
                                }
                                return prev
                            }, {})


                            let arr2 = []
                            for (let i in transferObj) {
                                let obj = {}
                                obj.title = i
                                transferObj[i].children.sort((a, b) => { return Number(a.appSort) - Number(b.appSort) }) //应用排序cateSort 
                                obj.children = transferObj[i].children
                                arr2.push(obj)
                            }

                            let arr3 = []
                            arr2.forEach(item => {
                                item.children.forEach(its => {
                                    let obj = {}
                                    obj.appid = its.appid
                                    obj.name = its.name
                                    arr3.push(obj)
                                })
                            })

                            if (location.host.indexOf("v5qy.test.baibaodun.cn") > -1) {
                                if (localStorage.getItem("domainId") != '__2gH5luUlviULa7KnmqW') {//临时过滤使用--后期删除--测试117环境
                                    arr2.forEach((item, index) => {
                                        item.children.forEach((its, ix) => {
                                            if (its.name == '组织权益') {
                                                if (item.children.length == 1) {
                                                    arr2.splice(index, 1)
                                                }
                                                item.children.splice(ix, 1)
                                            }
                                        })
                                    })
                                }
                            } else {
                                if (localStorage.getItem("domainId") != '__Qqg3L4GhNXG4iRAmcTB') {//临时过滤使用--后期删除--正式环境
                                    arr2.forEach((item, index) => {
                                        item.children.forEach((its, ix) => {
                                            if (its.name == '组织权益') {
                                                if (item.children.length == 1) {
                                                    arr2.splice(index, 1)
                                                }
                                                item.children.splice(ix, 1)    //不在这个组织，组织权益应用隐藏删除                                      
                                            }
                                        })
                                    })
                                }
                            }
                            console.log(arr2)
                            this.appcateArrList = arr2

                            //前端缓存本地代码块--切换不同组织的所有应用列表
                            let HomeApplist_board = { employeeIdStr: localStorage.getItem('employeeId'), appcateArrListStr: this.appcateArrList }
                            localStorage.setItem('HomeApplist_board', JSON.stringify(HomeApplist_board))

                        }

                    }
                }
            });
        },
        loadAppMenu(appId, name) {//点击应用列表查询左边应用菜单 
            console.log(this.$parent.$parent.$parent.$parent)
            console.log('当前appId', appId)
            let httpsUrl = location.origin;//获取url各个环境地址--比如http://localhost:4000
            if (appId == '__TS2n9hoVZ2MjWTPyJH9') {//警保指挥调度台应用直接跳转
                this.$nextTick(() => {
                    let url = `${httpsUrl}/static/signon/dispatchVue`//各个环境地址-调度台react版本地址--更换dispatchVue版本地址
                    window.open(url, "_blank");//新窗口打开
                })
                return
            }
            if (appId == '__Hab04s0VNDPrjFZ3Xlo') {//挂图作战直接打开项目中心首页
                console.log(this.$parent.$parent)
                this.$parent.$parent.$parent.$parent.navtopmenuclick(1)
                return
            }
            if (appId != "km" && appId != "pm" && appId != "qm") {
                this.$root.appid = appId;
            }

            if (appId == '__aNKPFCBuZfyQNzlnlZ9') { //商城pc前端入口
                console.log(this.$parent.$parent)
                this.$parent.$parent.$parent.$parent.navtopmenuclick(100)
                return
            }
            if (appId == '__ZG0ZtjrEhvNbj2rlOsF') { //企业钱包前端入口
                console.log(this.$parent.$parent)
                this.$parent.$parent.$parent.$parent.navtopmenuclick(101)
                return
            }
            // let options={
            //      target:document.querySelector(".homeAllApp"),                 
            //      text: '加载中...',
            //      spinner: 'el-icon-loading',
            // }
            // const loading = Loading.service(options);//开始加载 

            let flag = 1
            this.$store.dispatch("loadMenus", { appId, name, flag });
            if (appId == '__d1qEDy3wYq8VF5KvUoE') {//智能人事（__xkeybkGaZa1SboC9GL1）、机构用户管理（__d1qEDy3wYq8VF5KvUoE）
                let obj = { name, appId }
                localStorage.setItem('appidSupervise', JSON.stringify(obj))
            }
            // this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            //     loading.close();//关闭加载
            // });
        },
        appLevelsList(){
            let appLevelsListArr = this.$root.roleLevelsPermissionData&&this.$root.roleLevelsPermissionData.workspaceApps||[]
            if(appLevelsListArr.length){
                let arr=appLevelsListArr.sort((a, b) => {
                    if (a.categorySeq !== b.categorySeq) {
                        return a.categorySeq - b.categorySeq;
                    } else {
                        return a.appSeq - b.appSeq;
                    }
                });
                this.apps=arr                     
                this.categories=[...new Set(arr.map(app => app.category))]//去重
            }
        }
    },
}
</script>
<style lang="scss" scoped>
.homeAllApp {
    display: flex;
    flex-direction: column;

    .htaTitle {
        border-bottom: 1px solid rgba(0, 0, 0, 0.06);
        // font-size: 18px;
        color: rgba(0, 0, 0, 0.85);
        padding: 16px;
        display: flex;
        align-items: center;
        margin-bottom: 16px;

        strong {
            flex: 1;
            color: #3c4766;
            font-size: 16px;
        }

        em {
            color: rgba(0, 0, 0, 0.65);
            font-size: 14px;
            display: flex;
            align-items: center;
            cursor: pointer;

            img {
                width: 20px;
                height: 20px;
                margin-right: 8px;
            }
        }
    }

    .htaBox {
        padding: 0px 0 0px 16px;

        .htH3 {
            color: #3c4766;
            font-size: 14px;
            font-weight: 700;
            margin-bottom: 16px;
        }

        ul {
            display: flex;
            flex-wrap: wrap;
            align-content: flex-start;
            margin-bottom: 12px;

            li {
                background: #fff;
                width: 190px;
                height: 52px;
                display: flex;
                margin-bottom: 24px;
                align-items: center;
                text-align: center;
                cursor: pointer;
                border: 1px solid #fff;
                border-radius: 4px;

                &:hover {
                    border: 1px solid #EFF2F6;
                    border-radius: 4px;
                }

                span {
                    &.imgLeft {
                        margin-left: 8px;
                        margin-right: 8px;
                    }

                    img {
                        width: 36px;
                        height: 36px;
                    }

                    strong {
                        //    color: rgba(0, 0, 0, 0.85);
                        color: #3c4766;
                        font-size: 14px;
                        font-weight: normal;
                    }
                }
            }
        }
    }
}

.notApp {
    display: flex;
    justify-content: center;
    flex-direction: column;
    margin: 0 auto;
    text-align: center;
    margin-top: 50px;

    .textinfo {
        color: rgba(0, 0, 0, 0.65);
        font-size: 15px;
        margin-top: 24px;
    }
}
</style>