<script setup>
import {h, reactive,computed,ref,onMounted,onActivated} from 'vue'
import {useRouter,useRoute} from "vue-router"
import{ apiGetWechatQRCode } from '@/api/common'
import {apiSandBoxList,apiSandTableDetail} from "../../api/sandBox"
import {apiReportIndexPageAuthList} from "../../api/report"
import {apiApplyPermission} from "../../api/user"
import { ElMessage, ElMessageBox } from 'element-plus'
import SelfList from '@/components/SelfList.vue'
import { useStore } from 'vuex';
const router = useRouter()
const route = useRoute()
const store = useStore();
// -----------------------------------------------------数据
let sandBox = reactive({
    list:[],
    classifyList:[],
    // 请求参数
    sandBoxParams:{
        page_size:5,
        curr_page:1,
        chart_permission_id:0
    },
    // 沙盘图ID 手机小程序单个分享
    sandbox_id:"",
    total:0,
    // 二级分类列表
    secondClassifyList:[],
    selectedFirstId:0,
    selectedSecondId:0,
    // 所有有权限的二级分类以及下面的沙盘图数
    classifyDataList:[],
    // 没有权限  1:立即申请 2:联系销售
    noAuthor:0,
    // 销售信息
    salesData:{
        phone:'',
        name:''
    },
    // 申请权限时的用户信息
    applyer:{
        name:'',
        company:'',
        // 是否已经申请
        hasApply:false,
        // 状态
        status:''
    },
    // 请求是否完成
    isRequestFinished:false,
    // 是否加载完全部数据
    isTotalData:false,
    // 是否在加载中
    isLoading:false,
})
// 是否预览图片
let showPreViewImg = ref(false)
// 预览图片索引
let preViewImgIndex = ref(0)

// ------------------------------------------------------计算属性
// 预览图片的路径
const previewImageList = computed(()=>{
    return sandBox.list.map(item=> item.pic_url)
})

// ------------------------------------------------------方法
// 获取沙盘图数据
const getSandBoxList=()=>{
    sandBox.isLoading = true
    apiSandBoxList(sandBox.sandBoxParams).then(({data,code})=>{
        // 403 无权限
        if(code == 403){
            sandBox.applyer.name = data.customer_info.name
            sandBox.applyer.company = data.customer_info.company_name
            sandBox.applyer.hasApply = data.customer_info.has_apply
            sandBox.applyer.status = data.customer_info.status
            if(data.type == 'apply'){
                // 申请
                sandBox.noAuthor =1
            }else{
                if(data.jump){
                    sandBox.noAuthor =4
                    // jump 跳转，说明该用户是有部分权限，提示“暂无此权限”，跳转至有权限的分类
                    ElMessage({
                        message:"暂无此权限"
                    })
                    setTimeout(()=>{
                        router.replace({path:'/sandBox/list'})
                    },1000)
                }else{
                    // 联系销售
                    sandBox.noAuthor =2
                    sandBox.salesData.name=data.name
                    sandBox.salesData.phone=data.mobile
                }

            }
            return 
        }
        if(sandBox.sandBoxParams.curr_page == 1){
            sandBox.list = data.list || []
            sandBox.total = data.paging.totals
            document.body.scrollTop=document.documentElement.scrollTop=0
        }else{
            sandBox.list = [...sandBox.list, ...data.list]
        }
        if(sandBox.list.length == sandBox.total){
            sandBox.isTotalData = true
        }
        sandBox.noAuthor=0
    }).finally(()=>{
        sandBox.isRequestFinished=true
        sandBox.isLoading = false
    })
}

// 获取单个沙盘图
const getSandTableDetail=()=>{
    sandBox.isRequestFinished=false
    sandBox.isLoading = true
    sandBox.isTotalData = false
    apiSandTableDetail({sandbox_id:sandBox.sandbox_id}).then(({data,code})=>{
        // 403 无权限
        if(code == 403){
            sandBox.applyer.name = data.customer_info.name
            sandBox.applyer.company = data.customer_info.company_name
            sandBox.applyer.hasApply = data.customer_info.has_apply
            sandBox.applyer.status = data.customer_info.status
            if(data.type == 'apply'){
                // 申请
                sandBox.noAuthor =1
            }else{
                if(data.jump){
                    sandBox.noAuthor =4
                    // jump 跳转，说明该用户是有部分权限，提示“暂无此权限”，跳转至有权限的分类
                    ElMessage({
                        message:"暂无此权限"
                    })
                    setTimeout(()=>{
                        router.replace({path:'/sandBox/list'})
                    },1000)
                }else{
                    // 联系销售
                    sandBox.noAuthor =2
                    sandBox.salesData.name=data.name
                    sandBox.salesData.phone=data.mobile
                }

            }
            return 
        }
        sandBox.list = [data]
        sandBox.isTotalData = true
        sandBox.noAuthor=0
    }).finally(()=>{
        sandBox.isRequestFinished=true
        sandBox.isLoading = false
    })
}

//
const showMiniShare = (item)=>{
    if(item.miniCodeImg) return 
    let {chart_permission_id,sandbox_id} = item
    let params={
        sandbox_id,
        chart_permission_id,
        firstClassifyId : sandBox.selectedFirstId
    }
    console.log(params);
    apiGetWechatQRCode({
        CodePage:'pages-sandTable/sandTable',
        CodeScene:JSON.stringify(params)
    }).then(res=>{
        item.miniCodeImg = res.data
    })
}

//预览图片
const previewImage=(i)=>{
    preViewImgIndex.value = i
    showPreViewImg.value=true
    // 不让外层的页面可以滚动
    $('body').css("overflow","hidden")
}

// 取消预览图片
const cancelPreview = ()=>{
    // 恢复外层的页面滚动
    $('body').css("overflow","visible")
    showPreViewImg.value=false

}

//加载更多
const onLoad = ()=>{
    sandBox.sandBoxParams.curr_page++
    getSandBoxList()
}

//联系销售
const callToSales=()=>{
    if(!sandBox.applyer.hasApply){
        toApply('auto')
    }
    window.location.href=`tel:${sandBox.salesData.phone}`
}

//申请权限
const toApply = (type='')=>{
    if(store.state.userInfo.is_bind===0){
        ElMessageBox({
            title:`温馨提示`,
            message:'为了优化您的用户体验，<br>请登录后查看更多信息！',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonText:'去登录',
            confirmButtonClass:'self-elmessage-confirm-btn',
            showCancelButton:true,
            cancelButtonText:'取消',
            cancelButtonClass:'self-elmessage-cancel-btn'
        }).then(res=>{
            wx.miniProgram.reLaunch({url:'/pages/login'})
        }).catch(()=>{})
        return
    }
    if(type=='auto'){
        apiApplyPermission({
            company_name:sandBox.applyer.company,
            real_name:sandBox.applyer.name,
            source:7,
            from_page:'沙盘推演',
        }).then(res=>{
            console.log('自动申请成功');
        })
    }else{
        // 申请成功后将设置 has_apply
        let storeHasApply = store.state.userInfo.has_apply || false
        if(sandBox.applyer.hasApply || storeHasApply){
            ElMessageBox({
                title:'温馨提醒',
                message:h('p','您已提交过申请，请耐心等待'),
                center: true,
                dangerouslyUseHTMLString: true,
                confirmButtonText:'知道了',
                confirmButtonClass:'self-elmessage-confirm-btn'
            })
            return 
        }
        if(sandBox.applyer.status==='流失'||sandBox.applyer.status==='关闭'){
            apiApplyPermission({
                company_name:sandBox.applyer.company,
                real_name:sandBox.applyer.name,
                source:7,
                from_page:'沙盘推演',
            }).then(res=>{
                sandBox.applyer.hasApply=true
                const htmlStr = `<p>申请已提交</p><p>请等待销售人员与您联系</p>`;
                ElMessageBox({
                    title: "温馨提醒",
                    message: htmlStr,
                    center: true,
                    dangerouslyUseHTMLString: true,
                    confirmButtonText: "知道了",
                    confirmButtonClass: "self-elmessage-confirm-btn",
                });
            })
        }else{
            router.push({
                path:'/apply/permission',
                query:{
                    source:7,
                    fromPage:'沙盘推演'
                }
            })
        }
    }
}

// 获取分类列表 过滤无权限的分类
const getClassifyList= ()=>{
    apiReportIndexPageAuthList().then( async ({data:{permission_list}})=>{
        // 过滤掉'更多报告' 和 没有权限的分类
        sandBox.classifyList = permission_list.filter(item => item.sort!=100000)
        sandBox.classifyList.forEach(item=>{
            item.list=item.list.filter(it=>it.auth_ok)
        })
        sandBox.classifyList=sandBox.classifyList.filter(item=>item.list.length!=0)
        // 需求变化 增加全部标签 默认选中该标签
        sandBox.classifyList.unshift({
            classify_name: "全部",
            id: 0,
            list:[],
            sort: 0
        })
        // let classifyData= await apiSandBoxPermission()
        //  sandBox.classifyDataList = classifyData.data
        try {
            // 默认选中第一个有数据的二级分类
            // if(sandBox.selectedFirstId == 0){
            //     // 一级分类ID 和 二级分类ID 没有，不是通过分享进来的，或者路由参数中没有一级Id和二级Id
            //     // 找出第一个有数据的二级分类
            //     U:for (const item of sandBox.classifyList) {
            //         for (const it of item.list) {
            //             for (const classify of sandBox.classifyDataList) {
            //                 if(classify.chart_permission_id==it.chart_permission_id){
            //                     if(classify.total>0){
            //                         sandBox.selectedFirstId = item.id
            //                         sandBox.secondClassifyList = item.list
            //                         sandBox.selectedSecondId = it.chart_permission_id
            //                         break U
            //                     }
            //                     break
            //                 }
            //             }
            //         }
            //     }
            //     sandBox.sandBoxParams.chart_permission_id = sandBox.selectedSecondId
            // }else{
                // 通过分享进来
                if(sandBox.selectedFirstId != 0){
                    for (const item of sandBox.classifyList) {
                        if(item.id == sandBox.selectedFirstId){
                            // 根据selectedFirstId找出需要展示的二级分类列表
                            sandBox.secondClassifyList = item.list
                            break
                        }
                    }
                }
            // }
        } catch (error) {
            console.log(error);
        }
    })
}
// 切换一级分类
const selectFirstClassify = (item)=>{
    if(sandBox.selectedFirstId === item.id) return 
    sandBox.selectedFirstId = item.id
    sandBox.secondClassifyList = item.list
    selectSecondClassify(item.list[0])
}
// 切换二级分类
const selectSecondClassify = (item)=>{
    let chartPermissionId
    // item为undefined，选中为全部 没有二级分类列表
    if(!item){
        if(sandBox.selectedSecondId==0) return 
        chartPermissionId= 0
    }else{
        if(sandBox.selectedSecondId == item.chart_permission_id) return 
        chartPermissionId= item.chart_permission_id
    }
    sandBox.sandBoxParams.chart_permission_id = sandBox.selectedSecondId = chartPermissionId
    sandBox.sandBoxParams.curr_page=1
    sandBox.isLoading = false
    sandBox.isTotalData=false
    sandBox.list=[]
    getSandBoxList()
}

// ---------------------------------------------------------created
// 路由参数  分享
// 需要是数字类型
sandBox.sandBoxParams.chart_permission_id = sandBox.selectedSecondId = parseInt(route.query.chart_permission_id)  || 0 //二级分类ID 分享
sandBox.selectedFirstId = route.query.firstClassifyId || 0 //一级分类ID 分享
sandBox.sandbox_id = route.query.sandbox_id // 沙盘图ID 
// 获取分类
getClassifyList()

if(sandBox.sandbox_id){
    getSandTableDetail()
}else{
    getSandBoxList()
}

onMounted(() => {
  //向小程序发送消息
  let postData = {
    path: "/pages-sandTable/sandTable",
    params:{
        firstClassifyId:sandBox.selectedFirstId,
        chart_permission_id:sandBox.selectedSecondId
    },
    title: "沙盘推演",
    shareImg:''
  };
  wx.miniProgram.postMessage({ data: postData });
});

onActivated(()=>{
    //向小程序发送消息
    let postData = {
        path: "/pages-sandTable/sandTable",
        params:{
            firstClassifyId:sandBox.selectedFirstId,
            chart_permission_id:sandBox.selectedSecondId
        },
        title: "沙盘推演",
        shareImg:''
    };
    wx.miniProgram.postMessage({ data: postData });
})

</script>

<template>
    <template v-if="sandBox.noAuthor ==1 && sandBox.isRequestFinished">
        <div class="sandbox-noAuthor">
            <img :src="$store.state.globalImgUrls.activityNoAuth" />
            <span style="margin-top: 34px;">您在暂无权限查看沙盘推演</span>
            <span style="margin-top: 10px;">若想查看可以申请开通</span>
            <div class="apply-button" @click="toApply">立即申请</div>
            <!-- <template v-else>
                <img :src="$store.state.globalImgUrls.activityNoAuth" />
                <span style="margin-top: 34px;">您已提交过申请</span>
                <span style="margin-top: 10px;">请等待销售人员与您联系</span>
                <div class="apply-button" @click="$router.back()">返回</div>
            </template> -->
        </div>
    </template>
    <template v-if="sandBox.noAuthor ==2 && sandBox.isRequestFinished">
        <view class="sandbox-noAuthor">
            <img :src="$store.state.globalImgUrls.activityNoAuth" />
            <span style="margin-top: 34px;">您在暂无权限查看沙盘推演</span>
            <span style="margin: 10px 0 4px 0;">若想查看请联系对口销售</span>
            <div>
                <span>{{sandBox.salesData.name}}：</span>
                <span class="sales-mobile" @click="callToSales">{{sandBox.salesData.phone}}</span>
            </div>
        </view>
    </template>
    <!-- 部分有权限 分享进来没有权限 -->
    <template v-if="sandBox.noAuthor ==4 && sandBox.isRequestFinished" >
        <!-- 显示空白 一秒钟后跳转至有权限的沙盘图-->
    </template>
    <div class="sandBox-contain" v-if="sandBox.noAuthor ==0 && sandBox.isRequestFinished">
        <div class="classify-box">
            <div class="firstClassify-box">
                <div :class="['firstClassfy-item',item.id==sandBox.selectedFirstId?'firstClassfy-actice':'']" 
                v-for="item in sandBox.classifyList" :key="item.id" @click="selectFirstClassify(item)">
                    <span>{{item.classify_name}}</span>
                </div>
            </div>
            <div class="sec-nav-box" v-show="sandBox.secondClassifyList.length>0">
                <span
                    :class="['sec-item',item.chart_permission_id==sandBox.selectedSecondId?'active':'']"
                    v-for="item in sandBox.secondClassifyList"
                    :key="item.chart_permission_id"
                    @click="selectSecondClassify(item)"
                >{{item.chart_permission_name}}</span>
                <!-- <el-popover
                    :width="500"
                    trigger="click"
                >
                    <template #reference>
                        <img v-if="sandBox.secondClassifyList.length>6" style="width:16px;transform: rotate(90deg);cursor: pointer" src="@/assets/icon-more.png" alt="">
                    </template>
                    <template #default>
                        <div class="flex top-nav-filter-box">
                            <div 
                                :class="['item',item.chart_permission_id == sandBox.selectedSecondId&&'active']" 
                                v-for="item in sandBox.secondClassifyList.slice(6)" 
                                :key="item.chart_permission_id"
                                @click="selectSecondClassify(item)"
                            >{{item.chart_permission_name}}</div>
                        </div>
                    </template>
                </el-popover> -->
            </div>
        </div>
        <SelfList
        :finished="sandBox.isTotalData" 
        :isEmpty="sandBox.list.length===0&&sandBox.isTotalData"
        :loading="sandBox.isLoading"
        :count="sandBox.list.length"
        @listOnload="onLoad">
            <div class="sandBox-content">
                <div class="sandBox-item" v-for="(item,index) in sandBox.list" :key="item.sandbox_id">
                    <div class="sandBox-item-header">
                        <span>{{item.name}}</span>
                        <el-popover
                        :width="200"
                        :height="200"
                        trigger="hover"
                        @show="showMiniShare(item)"
                        popper-class="miniprogram-code">
                        <!-- popper-style="" -->
                            <template #reference>
                                <div class="sandBox-item-miniP"></div>
                            </template>
                            <div class="miniprogram-code">
                                <img :src="item.miniCodeImg" alt="小程序码" v-show="item.miniCodeImg" />
                            </div>
                        </el-popover>
                    </div>
                    <div class="sandBox-image">
                        <img :src="item.pic_url" :alt="item.name" @click="previewImage(index)"/>
                    </div>
                </div>
            </div>
        </SelfList>
    </div>
    
    <!-- 图片预览 -->
    <el-image-viewer
        v-if="showPreViewImg"
        :initial-index="preViewImgIndex"
        @close="cancelPreview"
        :url-list="previewImageList"
    />
</template>

<style lang="scss" scoped>
.top-nav-filter-box{
    flex-wrap: wrap;
    .item{
        margin: 5px 10px;
        width: 113px;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f6f6f6;
        border-radius: 4px;
        font-size: 16px;
        cursor: pointer;
        :hover{
            color: #fff;
            background-color: #F3A52F;
        }
    }
    .active{
        color: #fff;
        background-color: #F3A52F;
    }
}
// 小程序码
.miniprogram-code{
    display: flex;
    align-items: center;
    justify-content: center;
    img{
        width: 100%;
    }
}
    .sandbox-noAuthor{
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 50px;
        img{
            height: 360px;
        }
        span{
            font-style: normal;
            font-weight: 400;
            font-size: 16px;
            color: #333333;
        }
        .sales-mobile{
            color: #E3B377;
            cursor: pointer;
        }
        .apply-button{
            display: flex;
            align-items: center;
            justify-content: center;
            background: #E6B77D;
            width: 218px;
            border: none;
            height: 40px;
            border-radius: 41px;
            margin-top: 30px;
            font-style: normal;
            font-weight: 500;
            font-size: 16px;
            color: #FFFFFF;
            cursor: pointer;
        }
    }
    .sandBox-contain{
        // margin-top: 130px;
        .classify-box{
            padding: 30px 0 12px;
            background: #FFFFFF;
            // box-shadow: 0px 4px 8px 1px rgba(0, 0, 0, 0.04);
            position: sticky;
            top: 60px;
            width: 100%;
            max-width: 1240px;
            z-index: 10;
            .firstClassify-box{
                .firstClassfy-item{
                    display: inline-block;
                    width: 140px;
                    line-height: 40px;
                    text-align: center;
                    border-radius: 20px;
                    background-color: #F6F6F6;
                    font-size: 16px;
                    margin-right: 30px;
                    // margin-bottom:10px;
                    cursor: pointer;
                    span{
                        font-style: normal;
                        font-weight: 400;
                        font-size: 16px;
                        color: #333333;
                    }
                }
                .firstClassfy-actice{
                    background: #FFFBF5;
                    border: 1px solid #F3A52F;
                    box-shadow: 0px 6px 7px #FFF7EB;
                    border-radius: 20px;
                    span{
                        color: #F3A52F;
                    }
                }
                @media screen and (max-width: 1100px){
                    .firstClassfy-item{
                        width: 90px;
                        height: 30px;
                        line-height: 30px;
                        margin-right: 15px;
                        font-size: 14px;
                        span{
                            font-size: 14px;
                        }
                    }
                }
            }
            .sec-nav-box{
                margin-top: 30px;
                margin-left: -30px;
                .sec-item{
                    color: #666;
                    margin-left: 30px;
                    cursor: pointer;
                    margin-bottom: 8px;
                    display: inline-block;
                }
                .active{
                    color: #F3A52F;
                }
            }
        }
        .sandBox-noData{
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin-top: 50px;
            img{
                height: 360px;
            }
            span{
                margin-top: 30px;
                font-style: normal;
                font-weight: 400;
                font-size: 16px;
                color: #333333;
            }
        }
        .sandBox-content{
            .sandBox-item{
                padding: 30px 0;
                position: relative;
                .sandBox-item-header{
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    span{
                        font-style: normal;
                        font-weight: 600;
                        font-size: 16px;
                        color: #333333;
                    }
                    .sandBox-item-miniP{
                        height: 20px;
                        cursor: pointer;
                        width: 20px;
                        background-image: url(../../assets/icon-wechat.png);
                        background-size: contain;
                        &:hover{
                            background-image: url(../../assets/icon-wechat2.png);
                        }
                    }
                }
                .sandBox-image{
                    margin-top: 20px;
                    width: 100%;
                    // max-height: 558px;
                    border: 2px solid #ECECEC;
                    overflow: auto;
                    padding-bottom: 24px;
                    display:flex;
                    justify-content:center;
                    align-items:center;
                    img{
                        cursor: pointer;
                        max-width:100%;
                    }
                    .sandBox-source{
                        font-size: 20px;
                        font-weight: 400;
                        color: #666666;
                        -webkit-background-clip: text;
                        background-clip: text;
                        position: absolute;
                        bottom: 54px;
                        right: 30px;
                    }
                }
            }
            .loading-more{
                margin: 20px auto;  
                width: 112px;
                height: 30px;
                background: #FFFFFF;
                border-radius: 20px;
                border: 1px solid #F3A52F;
                color: #F3A52F;
                font-size: 14px;
                text-align: center;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
            }
            .more-loading{
                margin: 20px auto;  
                width: 112px;
                height: 30px;
                font-size: 16px;
                color: #999;
            }
        }
    }
</style>