//ppt分类模块

import {ref,reactive} from 'vue'
import { useRouter } from 'vue-router';
import { showToast,showDialog,Dialog  } from 'vant';
import {useUserInfo} from '@/hooks/common'
import {pptBtn,enPPTBtn,useAuthBtn} from '@/hooks/useAuthBtn'
const  {checkAuthBtn} = useAuthBtn()
const permissionBtn = window.location.pathname.startsWith('/ppten')?enPPTBtn:pptBtn
import {
    apiPPTClassify,
    apiPPTCatalogueCopy,
    apiPPTCatalogueDel,
    apiPPTCatalogueRename,
    apiPPTDel,
    apiPPTShare,
    apiPPTCopy,
    cancelShareAuth,
    setShareAuth,
    getSharedDetail,
    userSearch,
} from '@/api/ppt'
import {useCachedViewsStore} from '@/store/modules/cachedViews'

const cachedViewsStore=useCachedViewsStore()

const userInfo =useUserInfo()



export function useClassify(){
    const router=useRouter()
    // ppt分类数据
    const classifyState = reactive({
        privateList:[],
        publicList:[],
        sharedList:[],
        activeType:['myPPT','pubPPT','sharedPPT'],//一级分类是否展开
        myActiveType:[],//我的ppt文件夹是否展开
        pubActiveType:[],//公共ppt文件夹是否展开
        sharedActiveType:[],//共享ppt文件夹是否展开
    })
    // 获取ppt分类数据
    const getPPTClassifyData=async()=>{
        const res=await apiPPTClassify()
        if(res.Ret===200){
            const temPriArr=res.Data.PrivateList||[]
            classifyState.privateList=temPriArr.map(item=>{
                 item.PptList=item.PptList?.map(_item=>{
                    return {
                        ..._item,
                        IsSingleShareBoolean:_item.IsSingleShare?true:false
                    }
                })
                return item
            })
            //需求池690 我的PPT分类默认收起
            /* classifyState.myActiveType=classifyState.privateList.map(item=>{
                return item.GroupId
            }) */
            classifyState.publicList=res.Data.PublicList||[]
            classifyState.sharedList=res.Data.GrantList||[]
        }
    }

    // 显示目录编辑弹窗
    const fileOptState=reactive({
        show:false,
        data:{},//当前点击的目录数据
        showReName:false,//显示重命名弹窗
        reNameVal:"",
    })
    const handleShowFileOpt=e=>{
        fileOptState.data=e
        fileOptState.reNameVal=e.GroupName
        fileOptState.show=true
    }
    // 复制ppt目录
    const handlePPTCatalogueCopy=async()=>{
        const res=await apiPPTCatalogueCopy({GroupId:fileOptState.data.GroupId})
        if(res.Ret===200){
            showToast('复制成功')
            getPPTClassifyData()
            fileOptState.show=false
        }
    }
    // 删除ppt目录
    const handlePPTCatalogueDel=()=>{
        if(fileOptState.data.PptList&&fileOptState.data.PptList.length!==0){
            showToast('该目录下有关联PPT，不允许删除');
            return
        }
        showDialog({
            title: '提示',
            message: '删除操作不可恢复，确认删除吗？',
            showCancelButton:true
        }).then(() => {
            // on close
            apiPPTCatalogueDel({GroupId:fileOptState.data.GroupId}).then(res=>{
                if(res.Ret===200){
                    getPPTClassifyData()
                    fileOptState.show=false
                }
            })
        });
    }
    // 目录重命名
    const handlePPTCatalogueReName=async ()=>{
        if(!fileOptState.reNameVal){
            showToast('请填写目录名称');
            return
        }
        const res=await apiPPTCatalogueRename({
            GroupId:fileOptState.data.GroupId,
            GroupName:fileOptState.reNameVal
        })
        if(res.Ret===200){
            getPPTClassifyData()
            fileOptState.data.GroupName=fileOptState.reNameVal
        }
    }

    // 显示ppt录编辑弹窗
    const PPTOptState=reactive({
        isCommon:false,//是否为公共ppt目录下的
        show:false,
        data:{},
        showCopy:false,//显示选择复制到目录的弹窗
        copyActions:[],//选择复制到目录数
        copySelectData:{},//复制选择的目录
        activeType:'',//该PPT的类型
    })
    // e ppt的数据
    const handleShowPPTOpt=(e,activeType)=>{
        PPTOptState.data=e
        PPTOptState.data.IsSingleShareBoolean=e.IsSingleShare?true:false
        PPTOptState.isCommon=userInfo.value.AdminId!=e.AdminId?true:false
        PPTOptState.show=true
        PPTOptState.activeType = activeType
    }
    // 删除ppt
    // back 则返回上一级
    const handlePPTDel=({back})=>{
        showDialog({
            title: '提示',
            message: '删除操作不可恢复，若该PPT被共享，则同步删除共享PPT，确认删除吗？',
            showCancelButton:true
        }).then(() => {
            // on close
            apiPPTDel({PptId:PPTOptState.data.PptId}).then(res=>{
                if(res.Ret===200){
                    if(back){
                        router.back()
                    }
                    getPPTClassifyData()
                    PPTOptState.show=false
                }
            }).catch(()=>{})
        });
    }
    //设置ppt是否共享
    const handlePPTShare=async (e)=>{
        const res=await apiPPTShare({
            PptId:PPTOptState.data.PptId
        })
        if(res.Ret===200){
            getPPTClassifyData()
            PPTOptState.data.IsSingleShareBoolean=e
        }
    }

    //设置共享 指定成员列表
    const researcherList = ref([]); //指定成员列表
    const getResearcherList = async () => {  
        const formatList = function(arr){ //vant数据格式化
            let result = [];
            for(let i = 0;i < arr.length;i++){
              let item = {};
              item.id = arr[i].ItemId;
              item.text = arr[i].ItemName;
              if(arr[i].Children && arr[i].Children.length > 0){
                item.children = formatList(arr[i].Children)
              }
              result.push(item)
            }
            return result
        } ;

        const { Data }  = await userSearch()
        researcherList.value = formatList(Data) || [];
        chooseMemberOptState.acitiveItem = researcherList.value[0].children || [];
    }


    // 显示设置共享ppt弹窗
    const PPTSetSharedOptState=reactive({
        show:false,
        chooseType:'1',//共享类型
        members:[], //选中成员的item
    })

    //设置为共享PPT
    const handleSetPPTShared = () => {
        if(PPTOptState.data.IsGrant) { //取消共享
            showDialog({
                title: '提示',
                message: '确定要取消共享吗？',
                showCancelButton:true
            }).then(_=>{
                cancelShareAuth({PptId:PPTOptState.data.PptId}).then(res=>{
                    if(res.Ret == 200){
                        showToast('取消共享成功');
                        getPPTClassifyData();
                        PPTOptState.show = false;
                    }
                }).catch(()=>{})
            }).catch(err=>{})
            return
        }

        //设置共享
        PPTSetSharedOptMethods.init();
        chooseMemberOptMethods.init();
        PPTOptState.show = false; 
        PPTSetSharedOptState.show = true;  
    }

    //设置共享弹窗方法
    const PPTSetSharedOptMethods = {
       init(){
            PPTSetSharedOptState.show = false;
            PPTSetSharedOptState.chooseType = '1';
            PPTSetSharedOptState.members = [];
       },
       cancel(){
            this.init();
            chooseMemberOptMethods.init();
       },
       save(){
            if(PPTSetSharedOptState.chooseType == '2' && !chooseMemberOptState.activeId.length) return showToast('请选择研究员！');
            setShareAuth({
                PptId:PPTOptState.data.PptId,
                GrantType:+PPTSetSharedOptState.chooseType,
                AdminIdStr: PPTSetSharedOptState.chooseType=='2' ? chooseMemberOptState.activeId.join(',') : ''
            }).then(res=>{
                if(res.Ret == 200){
                    showToast('设置共享成功');
                    getPPTClassifyData();
                    PPTSetSharedOptState.show = false;
                    PPTOptState.show = false;
                }
            })
       },
       chooseMember(){
             chooseMemberOptState.show = true;
       },
       delete(e){
         if(PPTSetSharedOptState.members.findIndex(_=>_.id == e.id) >= 0)  PPTSetSharedOptState.members.splice(PPTSetSharedOptState.members.findIndex(_=>_.id == e.id),1);
         if(chooseMemberOptState.activeId.findIndex(_=>_ == e.id) >= 0)  chooseMemberOptState.activeId.splice(chooseMemberOptState.activeId.findIndex(_=>_ == e.id),1);
         if(chooseMemberOptState.activeIdCopy.findIndex(_=>_ == e.id) >= 0) chooseMemberOptState.activeIdCopy.splice(chooseMemberOptState.activeIdCopy.findIndex(_=>_ == e.id),1);
       },
    }

    //选择用户弹框
    const handleChooseMember = () => {
        PPTSetSharedOptMethods.init();
        chooseMemberOptMethods.init();
        getSharedDetail({PptId:PPTOptState.data.PptId}).then(res=>{
            if(res.Ret == 200){
                 chooseMemberOptState.activeId = res.Data.AdminIdStr ? res.Data.AdminIdStr.split(',').map(_=>+_) : [];
                 chooseMemberOptState.activeIdCopy = chooseMemberOptState.activeId.slice(0);
                 PPTSetSharedOptState.chooseType = res.Data.GrantType.toString();
                 PPTSetSharedOptState.show = true;
                 PPTOptState.show = false;
                 PPTSetSharedOptState.members = chooseMemberOptMethods.idsForItems(chooseMemberOptState.activeId,researcherList.value);
            }
        })
    }

    //选取指定成员弹框
    const chooseMemberOptState = reactive({
        show:false,
        slideActive:0, //侧边框默认值
        acitiveItem:[], //侧边框选中的内容
        activeId:[], // 选中的id
        activeIndex:0, //分类选择index
        activeIdCopy:[], //选择成员未保存时的副本
    })

    const chooseMemberOptMethods = {
        change(){
            chooseMemberOptState.acitiveItem = researcherList.value[chooseMemberOptState.slideActive].children || [];
            chooseMemberOptState.activeIndex = 0;
        },
        init(options = {}){
            chooseMemberOptState.acitiveItem = researcherList.value[0].children || [];
            chooseMemberOptState.show = false;
            chooseMemberOptState.slideActive = 0;
            chooseMemberOptState.activeIndex = 0;
            if(!options.jumpActiveId) chooseMemberOptState.activeId = [];
            if(!options.jumpActiveIdCopy) chooseMemberOptState.activeIdCopy = [];
        },
        idsForItems(ids,lists){  //利用id转换items
            let result = [];
            for(let i = 0; i < lists.length;i++){
                if(ids.includes(lists[i].id)){
                    result.push(lists[i]);
                }
                if(lists[i].children && lists[i].children.length > 0){
                    let r = this.idsForItems(ids,lists[i].children);
                    result = result.concat(r);
                }
            }
            return result
        },
        cancel(){
            this.init({
                jumpActiveIdCopy:true,
                jumpActiveId:true
            });
            chooseMemberOptState.activeIdCopy = chooseMemberOptState.activeId.slice(0); 
        },
        save(){
            chooseMemberOptState.activeId = chooseMemberOptState.activeIdCopy.slice(0);
            PPTSetSharedOptState.members = chooseMemberOptMethods.idsForItems(chooseMemberOptState.activeId,researcherList.value);
            chooseMemberOptState.show = false;
        },

    }

    // 显示复制ppt选择目录弹窗
    // 如果是详情页中调用则会传一个pptid
    const handleShowPPTCopy=({pptid})=>{
        PPTOptState.copyActions=classifyState.privateList.map(item=>{
            return {
                text:item.GroupName,
                ...item
            }
        })
        if(pptid){
            PPTOptState.data.PptId=Number(pptid)
        }
        PPTOptState.showCopy=true
    }
    // 保存 复制ppt
    const handlePPTCopy=()=>{
        if(!PPTOptState.copySelectData.GroupId){
            showToast('请选择目录');
            return
        }
        
        apiPPTCopy({
            PptId:PPTOptState.data.PptId,
            GroupId:PPTOptState.copySelectData.GroupId
        }).then(res=>{
            if(res.Ret===200){
                setTimeout(() => {
                    showToast('复制成功');
                }, 100);
                
                getPPTClassifyData()
                PPTOptState.showCopy=false
            }
        })
    }
    // 关闭复制ppt选择目录弹窗钩子函数
    const handlePPTCopyBeforeClose=(action)=>{
        if(action==='confirm'&&!PPTOptState.copySelectData.GroupId){
            return false
        }else{
            return true
        }
    }


    // 跳转ppt详情
    const goPPTDetail=async (e)=>{
        await cachedViewsStore.removeCaches('PPTDetail')
        if(window.location.pathname.startsWith('/ppten')){
            router.push({
                path:"/ppten/detail",
                query:{
                    id:e.PptId
                }
            })
        }else{
            router.push({
                path:"/ppt/detail",
                query:{
                    id:e.PptId
                }
            })
        }
    }

    return {
        classifyState,
        getPPTClassifyData,

        fileOptState,
        handleShowFileOpt,
        handlePPTCatalogueCopy,
        handlePPTCatalogueDel,
        handlePPTCatalogueReName,

        PPTOptState,
        handleShowPPTOpt,
        handlePPTDel,
        handlePPTShare,
        handleShowPPTCopy,
        handlePPTCopy,
        handlePPTCopyBeforeClose,

        goPPTDetail,

        getResearcherList,
        researcherList,
        handleSetPPTShared,
        PPTSetSharedOptState,
        PPTSetSharedOptMethods,

        chooseMemberOptState,
        chooseMemberOptMethods,
        handleChooseMember,

        permissionBtn,
        checkAuthBtn,
    }
}