<template>
    <div>
        <div class="top">
            <div class="topBlock">
                <div class="topTit" style="display: flex;">
                    <div>欢迎使用</div>
                    <div style="color: #0354D7;margin: 0 15px;"><span v-if="userinfo.orgName">{{userinfo.orgName}}—</span>{{ userinfo.schoolName }}</div>
                    <div>AI平台！</div>
                </div>
                <div class="topDetail">
                    <!-- 探索AI教育的无限可能，提升教学效率与学习体验 -->
                     {{ fromL.basics.brief }}
                </div>
            </div>
            <img style="width: 96px;height: 96px;" src="../assets/img/root.png" alt="">
        </div>
        <div class="TabList">
            <div class="TabListCon" @click="openApp(item)" v-for="(item,index) in appSignL(fromL.admin.index.list)" :key="index">
                    <div v-for="(p,pin) in AppCon(item.url)" :key="pin+'p'">
                        <img style="height: 25px;object-fit: contain;transform: scale(1.5);margin-bottom: 12px;"     
                        :src="p.icon" 
                        alt="">
                        <div class="TabListName">
                            {{ p.name }}
                        </div>
                    </div>

                   
                    <div class="TabListBri">
                        <el-tooltip class="item" effect="light" :content="item.description" placement="bottom">
                            <span>
                                {{ item.description }}
                            </span>
                        </el-tooltip>
                    </div>
            </div>
        </div>
        <div class="footCon">
            <div class="footConLeft">
                <div><img style="margin-bottom: 12px;height: 41px;width: 36px;" src="../assets/img/sucai2.svg" alt=""></div>
                <div style="font-size: 20px;font-weight: 600;color: #1f2937;margin-bottom: 8px;">CocoFlow</div>
                <div style="color: #4b5563;font-size: 14px;">汇聚丰富的教育AI应用，搭建属于您的专属教育应用</div>
            </div>

            <div class="footList">
                <div class="footListCon" v-for="(item,index) in CocoFlowList" @click="openNewWindow(item)" :key="index">
                    <div><img style="margin-bottom: 12px;height: 24px;width: 22px;" :src="JSON.parse(item.json).icon" alt=""></div>
                    <div class="TabListName">{{ item.name }}</div>
                    <div class="TabListBri">
                        <el-tooltip class="item" effect="light" :content="item.detail" placement="bottom">
                            <span>
                                {{ item.detail }}
                            </span>
                        </el-tooltip>
                    </div>
                    <div class="cha" @click.stop="delApp(item.lid)">
                        <img style="width: 20px;" src="../assets/img/cha.svg" alt="">
                    </div>
                </div>
                <!-- v-if="userinfo.type == 1 && userinfo.role == 1" -->
                <div :style="{width : CocoFlowList.length ? '' : '187px'}" v-if="CocoFlowList.length < 4" @click="openUsuallyApp" class="footListCon footListCon2">
                    <div style="margin-bottom: 8px;font-size: 40px;color: #0354D7;">+</div>
                    <div class="TabListBri">添加常用应用</div>
                </div> 
            </div>
        </div>

        <!-- 常见应用弹框 -->
        <el-dialog
        title="应用列表"
        :visible.sync="dialogVisible"
        class="moreDia"
        :close-on-click-modal="false"
        :modal="false"
        width="60%"
        :before-close="handleClose">
            <div v-loading="loading" style="display: grid;grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));gap: 16px;height: 300px;overflow: auto;">
                <div v-for="(item,index) in isAdd(usuallyList)" class="tabCon" @click="addApp(item.id)"  :key="index" style="min-width: 308px;">
                        <div class="AppList">
                            <img class="appImg" :src="JSON.parse(item.json).icon" alt="">
                            <div class="con">
                                <div class="tit">{{ item.name }}</div>
                                <div class="bri">
                                    <el-tooltip class="item" effect="light" :content="item.detail" placement="bottom">
                                        <span>
                                            {{ item.detail }}
                                        </span>
                                    </el-tooltip>
                                </div>
                            </div>
                            <div style="position: absolute;top: 6px;right: 15px;" v-if="tab.includes(item.id)">
                                ✔
                            </div>
                    </div>
                </div>
            </div>
            <div style="height: 45px;line-height: 45px;text-align: end;">
                <el-button @click="handleClose">取消</el-button>
                <el-button @click="addUsuallyApp" type="primary">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import store from '../store'
import { API_CONFIG } from "@/common/apiConfig";

    export default {
        computed: {
            ...mapGetters(['userinfo','fromL']),
              // 如果hk，com没有图标，默认使用cn的
              AppCon(){
                return function(c) {
                    let k = JSON.parse(JSON.stringify(c))
                    let data = k.filter(e=>{
                        return e.region == this.userinfo.schoolArea || e.region == this.userinfo.orgArea
                    })

                    let data2 = k.filter(e=>{
                        return e.region == 'cn'
                    })
                    
                    // 如果hk，com没有图标，默认使用cn的
                    if (!data[0].icon){
                        data[0].icon = data2[0].icon
                        data[0].activeIcon = data2[0].activeIcon
                    }
                    return data
                };
            },
            // 筛选是否为管理员可见，是否被删除
            appSignL(){
                return function(val){
                    
                    let data = []
                    if (this.userinfo.type == 1 && this.userinfo.role == 1) {
                        val.forEach( e =>{
                            if (e.menuName || e.status == 0) {
                               data.push(e)
                            }
                        })
                    } else {
                        val.forEach( e =>{
                            if (e.menuName || (e.isAdmin == '0' && e.status == 0)) {
                               data.push(e)
                            }
                        })
                    }
                    return data
                }
            },
            isAdd(){
                return function(val){
                    const difference = val.filter(item1 => 
                        !this.CocoFlowList.some(item2 => item1.id === item2.id)
                    );
                    // console.log('difference',difference);
                    
                //    let data = val.filter(e=>{
                //     return !this.CocoFlowList.includes(e.id) 
                //    })
                    return difference
                }
            }
        },
        data() {
            return {
                dialogVisible:false, 
                //常见ai应用列表
                usuallyList:[], 
                loading:false,
                 //选中应用列表
                tab:[],
                // 已添加ai应用数组
                CocoFlowList:[]
            }
        },
        methods: {
            // 删除应用
            delApp(val){
                this.$confirm('确定删除吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let params = [
                            {
                                functionName: API_CONFIG.ajax_del_usuallyApp.functionName,
                                aid: val, 
                            },
                        ];
                        
                    this.$ajax
                        .post(API_CONFIG.baseUrl, params)
                        .then(() => {
                            this.$message.success('删除成功')
                            this.getData()
                        })
                        .catch((err) => {
                            console.log(err);
                            this.$message.error("删除失败");
                        });
                   
                }).catch(() => {
                    // 取消操作
                });

                
                
            },
            handleClose(){
                this.usuallyList= []
                this.tab= []
                this.dialogVisible = false
            },
            // 弹框选着添加应用
            addApp(val){
                // let data = this.CocoFlowList.filter(e=>{
                //     return e.id == val 
                // })
                // if (data.length != 0) return this.$message.info('常用列表已添加')
                let kpl = [...this.tab,...this.CocoFlowList]
                console.log(kpl);
                

                const index = this.tab.indexOf(val);
                if (index !== -1) {
                    this.tab.splice(index, 1); // 删除第一个匹配项
                } else {
                    if (kpl.length > 3) return this.$message.info('只能添加四个常用应用哦')
                    this.tab.push(val);    // 添加元素到末尾
                }
            },
            // 打开常见应用弹框
            openUsuallyApp(){
                this.dialogVisible = true
                this.loading = true
                let params = [
                    {
                        functionName: API_CONFIG.ajax_usuallyApp.functionName,
                        uid: this.userinfo.userid, 
                        cn: this.userinfo.schoolArea ? this.userinfo.schoolArea : this.userinfo.orgArea, //学校id
                    },
                ];
                
                this.$ajax
                    .post(API_CONFIG.baseUrl, params)
                    .then((res) => {
                        this.usuallyList = res.data[0]
                        this.loading = false

                    })
                    .catch((err) => {
                        console.log(err);
                        this.loading = false
                        this.$message.error("获取工具数据失败");
                    });
            },
            // 添加常用确定按钮
            async addUsuallyApp(){
                const uploadYn = async files => {
                    for (let index = 0; index < files.length; index++) {
                        await this.XAdd(files[index]);
                        console.log(index);
                    }
                }
                await uploadYn(this.tab);
                console.log('完成了');
                this.getData()
                this.handleClose()
            },
            // 循环添加常见应用
            XAdd(val){
                return new Promise((resolve) => {
                    let params = [
                        {
                            functionName: API_CONFIG.ajax_add_usuallyApp.functionName,
                            oid:this.userinfo.organizeid,
                            aid: val,
                            uid: this.userinfo.userid,
                        },
                    ];
                    
                    this.$ajax
                        .post(API_CONFIG.baseUrl, params)
                        .then(() => {
                            resolve(1)
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                    })
            },

            // 获取已添加cocoFlow应用
            getData(){
                let params = [
                    {
                        functionName: API_CONFIG.ajax_addedUsuallyApp.functionName,
                        uid: this.userinfo.userid, 
                    },
                ];
                
                this.$ajax
                    .post(API_CONFIG.baseUrl, params)
                    .then((res) => {
                        this.CocoFlowList = res.data[0]
                    })
                    .catch((err) => {
                        console.log(err);
                        this.$message.error("获取工具数据失败");
                    });
            },

            // 打开平台应用
            async openApp(val){
                // 点击相同应用不刷新
                if (this.appSign == val.toolId) return
                // 更新标识
                await store.commit('user/SET_AppSIGN', val.toolId)
                
                let url = ''
                val.url.forEach(e => {
                     // if (e.region == this.userinfo.schoolArea || e.region == this.userinfo.orgArea) {
                    if (e.region == this.$region) {
                        url = e.url
                    }
                });

                let _userinfo = this.userinfo, //登录用户信息
                { userid: _userid, organizeid: _oid, type: _type, org: _org, role: _role, classid: _classId } = _userinfo; // 解构赋值获取用户信息
                const _TscreenType = 1, _SscreenType = 3; // 常量定义
                let queryString = ''
                if(val.argumentList && val.argumentList.length){
                    const paramsMap = {
                    userid: _userid,
                    org: _org,
                    oid: _oid,
                    tType: _type,
                    role: _role,
                    classId: _classId,
                    TscreenType: _TscreenType,
                    SscreenType: _SscreenType
                    };

                    const canshu = val.argumentList
                    .filter(param => paramsMap[param] !== undefined)
                    .map(param => `${param}=${paramsMap[param]}`);

                    queryString = canshu.length ? (url.includes('?') ? '&' : '?') + canshu.join('&') : ''; // 生成查询字符串
                }

                let _url = url + queryString
                console.log('_url',_url);


                  let kpl = ` <iframe 
                                v-if="appSign && urlAddress"
                                allow= "camera *; microphone *;display-capture;midi;encrypted-media;"
                                frameborder="no" 
                                border="0" 
                                style="border:0;width:100%;height:100%;" 
                                src="${_url}" 
                                ref="pageCon"
                                >
                            </iframe>`

                let pl = {json:kpl ,stateL :true,toolId :val.toolId}

                // this.$emit('AddAppJson',pl)
                
                this.$emit('cutUrl',pl)
        
                // document.querySelector('#pageCon').innerHTML = '';
                

                // window.topU.U.MD.D.I.openApplicationWai(val.toolId, url, dom,val.argumentList)
                
            },
            // 打开CocoFlow应用
            openNewWindow(val) {
                console.log(val);
                
                // // 基本用法：打开指定 URL
                window.open(val.url, "_blank");
            },
        },
    }
</script>

<style scoped>
.moreDia >>> .el-dialog{
    border-radius: 10px;
}
.moreDia >>> .el-dialog__body{
    height: 345px;
    /* overflow: auto; */
    border-top: 1px #e7e7e7 solid;
}
.conBlock{
    background-color: #fff;
    padding: 24px;
    box-sizing: border-box;
    margin-bottom: 24px;
    border-radius: 10px;
}
.tabCon{
    transition: all 0.3s ease; /* 统一过渡效果 */
    border-radius: 10px;
    cursor: pointer;
}

.con{
    flex: 1;
    margin-left: 12px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
.tit{
    color: #1f2937;font-size: 16px;height: 24px;line-height: 24px;
    -webkit-line-clamp: 1;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
.bri{
    color: #6b7280;font-size: 12px;height: 16px;line-height: 16px;
    overflow: hidden;
    -webkit-line-clamp: 1;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
.appImg{
    width: 48px;
    height: 48px;
    border-radius: 50%;
    object-fit: cover;
}
.AppList{
    flex-wrap: wrap;display: flex;
    justify-content: space-between;
    border: 1px rgb(243 244 246 / var(--tw-border-opacity, 1)) solid;
    border-radius: 10px;padding: 16px;box-sizing: border-box;
    position: relative;
}
.footCon{
    display: flex;
    justify-content: space-between;
    padding: 16px;
    box-sizing: border-box;
    background-color: #eff6ff;
    border-radius: 10px;
    background-image: radial-gradient(#E6F0FF 1px, transparent 1px);
    background-size: 20px 20px;
}
.footListCon2{
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    max-width: 187px;
}
.footListCon{
    background-color: #fff;
    border-radius: 10px;
    padding: 24px;
    box-sizing: border-box;
    transition: all 0.3s ease; /* 统一过渡效果 */
    min-height: 156px;
    max-width: 187px;
    background-image: radial-gradient(#E6F0FF 1px, transparent 1px);
    background-size: 20px 20px;
    cursor: pointer;
    position: relative;
}
.footListCon:hover{
    transform: translateY(-5px); /* 向上位移 */
    box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
}
.cha{
    display: none;position: absolute;top: 10px;right: 10px;
}
.footListCon:hover .cha{
    display: block;
}
.footConLeft{
    padding: 25px;
    min-width: 50px;
    box-sizing: border-box;
}
.footList{
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px; /* 网格间距 */
}
.TabList{
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px; /* 网格间距 */
    margin-bottom: 16px;
}

.TabListCon{
    width: 170px;
    height: 140px;
    padding: 24px;
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 10px;
    width: 100%;
    box-shadow: 0 0 #0000, 0 0 #0000, 0 1px 2px 0 rgb(0 0 0 / 0.05);
    transition: all 0.3s ease; /* 统一过渡效果 */
    background-image: radial-gradient(#E6F0FF 1px, transparent 1px);
    background-size: 20px 20px;
    cursor: pointer;
}
.TabListCon:hover{
    transform: translateY(-5px); /* 向上位移 */
    box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
}
.TabListName{
    color: #1f2937;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 4px;
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
.TabListBri{
    color: #4b5563;
    font-size: 12px;
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
.top{
    display: flex;
    min-height: 144px;
    justify-content: space-between;
    background-color: #fff;
    align-items: center;
    padding: 24px;
    box-sizing: border-box;
    margin-bottom: 32px;
    border-radius: 10px;
    box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)
}
.topBlock{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.topTit{
    font-size: 30px;
    height: 100%;
    color: #000;
    font-weight: 600;
}
.topDetail{
    color: #64748B;
    margin-top: 16px;
}
</style>