<script setup>
import {computed, reactive, ref,watch} from 'vue'
import { useWindowSize } from '@vueuse/core'
import apiDataEDB from '@/api/dataEDB'
import { showDialog , showToast } from 'vant';
import {useEDBDelete} from '../hooks/useEDBDelete'
import {deleteClassifyItemEmpty} from '../util/util'

const {edbClassifyDelete}=useEDBDelete()
const { width } = useWindowSize()

const props=defineProps({
    modelValue:{
        type:Boolean,
        default:false
    }
})
const emits=defineEmits(['update:modelValue','change'])


// 处理分类数据 index为要过滤的层级数
// 如index 为3 则获取arr的前三层数据
function formatClassifyArr(arr,index){
    index--
    arr.length&&arr.forEach(item=>{
        item.Children.length&&formatClassifyArr(item.Children,index)
        if(!item.Children.length||index<=0){
            delete item.Children
        }
    })
}

const langType=ref('zh')
function langTypeChange(type){
    langType.value=type
}

const selectClassifyArr=ref([])//当前选择的哪些目录
function findClassifyList(arr,id){
    let temarr=[]
    arr.forEach(item=>{
        if(item.ClassifyId===id){
            if(item.Children?.length){
                temarr=item.Children
            }else{// 如果选中了最后一级目录或者这个目录没有子目录则就返回他本身
                temarr=arr
            }
        } 
    })
    return temarr
}
//显示的目录数据
const showClassifyArrData=computed(()=>{
    if(selectClassifyArr.value.length===0) return classifyList.value
    let arr=classifyList.value
    for (let index = 0; index < selectClassifyArr.value.length; index++) {
       arr=findClassifyList(arr,selectClassifyArr.value[index].ClassifyId)
    }
    return arr
})
//点击目录
function handleSelectClassify(item){
    // 如果当前选择的分类的最后一个在当前这个显示的目录里则将最后一个替换掉
    const last=selectClassifyArr.value[selectClassifyArr.value.length-1]
    // console.log(last);
    const flag=showClassifyArrData.value.some(e=>e.ClassifyId===last?.ClassifyId)
    if(flag){
        selectClassifyArr.value[selectClassifyArr.value.length-1]=item
        return
    }
    if(item.ClassifyId!==selectClassifyArr.value[selectClassifyArr.value.length-1]?.ClassifyId){
        selectClassifyArr.value.push(item)
    }
}
//返回上级目录
function handleBackClassify(index){
    if(index===-1){
        const flag=showClassifyArrData.value.some(item=>item.ClassifyId===selectClassifyArr.value[selectClassifyArr.value.length-1]?.ClassifyId)
        if(flag){
            selectClassifyArr.value.length=selectClassifyArr.value.length-2
        }else{
            selectClassifyArr.value.length=selectClassifyArr.value.length-1
        }
        return
    }
    selectClassifyArr.value.length=selectClassifyArr.value.length-index
}
// 显示选择的父级目录
const showParentClassifyData=computed(()=>{
    const id=selectClassifyArr.value[selectClassifyArr.value.length-1]?.ClassifyId
    const flag=showClassifyArrData.value.some(item=>item.ClassifyId===id)
    if(flag) return selectClassifyArr.value.slice(0,selectClassifyArr.value.length-1)
    return selectClassifyArr.value
})

// 关闭弹窗
function handleClose(){
    let selectClassifyId=selectClassifyArr.value[selectClassifyArr.value.length-1]?.ClassifyId||0
    let selectClassifyNameArr=selectClassifyArr.value.map(item=>getClassifyItemName(item))


    emits('change',{selectClassifyNameStr:selectClassifyNameArr.join('/'),selectClassifyId})
    emits('update:modelValue',false)
}

// 设置显示的分类名称（中英文）
function getClassifyItemName(item){
    return langType.value==='zh'?item.ClassifyName:item.ClassifyNameEn||item.ClassifyName
}

// 获取分类数据
let classifyList=ref([])
async function getEDBClassifyList(){
    const res=await apiDataEDB.edbClassifyList()
    if(res.Ret===200){
        deleteClassifyItemEmpty(res.Data.AllNodes||[])
        classifyList.value=res.Data.AllNodes||[]
    }
}
getEDBClassifyList()

// 分类操作数据
const classifyState=reactive({
    show:false,
    title:'',
    name:'',//输入框中的值
    placeholderText:'',
    type:'add',//新增、编辑
    parentText:'',
    parentId:0,
    classifyId:0,
})
watch(
    ()=>classifyState.show,
    (n)=>{
        if(!n){
            classifyState.title=''
            classifyState.name=''
            classifyState.placeholderText=''
            classifyState.type='add'
            classifyState.parentText=''
            classifyState.parentId=0
            classifyState.classifyId=0
        }
    }
)
function handleAddLevel1(){
    classifyState.title='添加一级目录'
    classifyState.placeholderText='请输入一级目录名称'
    classifyState.show=true
}
async function handleConfirmClassifyState(){
    let params={}
    if(classifyState.type==='add'){
        params={
            ClassifyName:classifyState.name,
            Level:classifyState.level,
            ParentId:classifyState.parentId
        }
    }else{
        params={
            ClassifyName:classifyState.name,
            ClassifyId:classifyState.classifyId
        }
    }
    const res=classifyState.type==='add'?await apiDataEDB.edbClassifyAdd(params):await apiDataEDB.edbClassifyEdit(params)
    if(res.Ret===200){
        getEDBClassifyList()
        classifyState.show=false
    }
}

// 显示分类操作按钮数据
const classifyOptState=reactive({
    show:false,
    actions:[],
    data:{}
})
watch(
    ()=>classifyOptState.show,
    (n)=>{
        if(!n){
            classifyOptState.actions=[]
            classifyOptState.data={}
        }
    }
)
// 显示分类的具体操作选项
function handleShowClassifyOpt(item){
    let optArr=[
        {name:'重命名',type:'edit'},
        {name:'删除',type:'delete',color:"#C54322"},
    ]
    if(item.Button.AddButton){//添加权限
        optArr.unshift({name:'添加下级目录',type:'add'})
    }
    if(!item.Button.DeleteButton){//删除
        optArr=optArr.filter(item=>item.type!='delete')
    }
    if(item.Button.MoveButton){//移动权限
        // 一级目录不能移动至
        if(selectClassifyArr.value.length){
            optArr.push({name:'移动至',type:'move'})
        }
    }
    classifyOptState.actions=optArr
    classifyOptState.data=item
    classifyOptState.show=true
}
function handleSelectOpt(e){
    if(e.type==='add'){
        const temarr=[...showParentClassifyData.value,{...classifyOptState.data}]
        const selectClassifyNameArr=temarr.map(item=>getClassifyItemName(item))
        classifyState.parentText=selectClassifyNameArr.join('/')

        classifyState.title=e.name
        classifyState.placeholderText='请输入目录名称'
        classifyState.type='add'
        classifyState.parentId=classifyOptState.data.ClassifyId
        classifyState.show=true
    }
    if(e.type==='edit'){
        const temarr=[...showParentClassifyData.value]
        const selectClassifyNameArr=temarr.map(item=>getClassifyItemName(item))
        classifyState.parentText=selectClassifyNameArr.join('/')

        classifyState.title='重命名'
        classifyState.placeholderText='请输入目录名称'
        classifyState.type='edit'
        classifyState.name=classifyOptState.data.ClassifyName
        classifyState.classifyId=classifyOptState.data.ClassifyId
        classifyState.show=true
    }
    if(e.type==='delete'){
        let data=classifyOptState.data
        edbClassifyDelete(data).then(res=>{
            // console.log(res===true);
            if(res===true){
                getEDBClassifyList()
            }
        })
    }
    if(e.type==='move'){
        classifyMoveState.selectValue=''
        classifyMoveState.tabIndex=0
        const level=showParentClassifyData.value.length
        const arr=JSON.parse(JSON.stringify(classifyList.value))
        formatClassifyArr(arr,level)
        classifyMoveState.options=arr||[]
        classifyMoveState.classifyId=classifyOptState.data.ClassifyId
        classifyMoveState.show=true
    }
    classifyOptState.show=false
}

// 移动分类数据
const classifyMoveState=reactive({
    show:false,
    selectValue:'',
    options:[],
    classifyId:0,//要移动的分类id
})
function handleSelectMoveClassifyChange({value,selectedOptions,tabIndex}){
    // classifyMoveState.tabIndex=tabIndex
}
function handleConfirmMove(){
    if(!classifyMoveState.selectValue){
        showToast('请选择要移动至的目录')
        return
    }
    
    // 只会将目录移动到某个目录里面所有下面有很多都是0
    apiDataEDB.edbCatalogMove({
        ClassifyId:classifyMoveState.classifyId,
        ParentClassifyId:classifyMoveState.selectValue,
        EdbInfoId:0,
        PrevClassifyId:0,
        NextClassifyId:0,
        PrevEdbInfoId:0,
        NextEdbInfoId:0,
    }).then(res=>{
        if(res.Ret===200){
            showToast('移动成功')
            getEDBClassifyList()
            classifyMoveState.show=false
        }
    })
}


defineExpose({classifyList,langTypeChange})
</script>

<template>
    <van-popup 
        :show="props.modelValue"
        position="right"
        closeable
        :style="{width:width>650?'400px':'100%',height:'100%'}"
        @click-close-icon="handleClose"
    >
        <div class="edb-classify-wrap">
            <div class="top-box">
                <van-icon name="arrow-left" size='20' @click="handleBackClassify(-1)" v-if="showParentClassifyData.length>0"/>
                <div class="catalog-text-box">
                    <span 
                        v-for="item,index in showParentClassifyData" 
                        :key="item.ClassifyId"
                        @click="handleBackClassify(selectClassifyArr.length-index)"
                    >{{getClassifyItemName(item)}}</span>
                </div>
            </div>
            <ul class="classify-box">
                <li class="classify-item" v-for="item in showClassifyArrData" :key="item.UniqueCode">
                    <span 
                        class="van-ellipsis title"
                        :style="{color:selectClassifyArr[selectClassifyArr.length-1]?.ClassifyId===item.ClassifyId?'#0052D9':''}"
                        @click.stop="handleSelectClassify(item)"
                    >{{getClassifyItemName(item)}}</span>
                    <img style="width:22px;height:22px;cursor: pointer;" src="@/assets/imgs/dataEDB/icon_opt.png" alt="" @click.stop="handleShowClassifyOpt(item)">
                </li>
            </ul>
            <div class="bot-btn-box">
                <van-button type="primary" block @click="handleAddLevel1">添加一级目录</van-button>
            </div>
        </div>
    </van-popup>

    <!-- 分类操作选项 -->
    <van-action-sheet
        v-model:show="classifyOptState.show"
        :actions="classifyOptState.actions"
        cancel-text="取消"
        @select="handleSelectOpt"
    />

    <!-- 创建/编辑分类 -->
    <van-dialog 
        v-model:show="classifyState.show" 
        :title="classifyState.title" 
        show-cancel-button
        @confirm="handleConfirmClassifyState"
    >
        <div class="edit-classify-wrap">
            <p class="van-ellipsis" v-if="classifyState.parentText" style="margin-bottom:8px">上级目录：{{classifyState.parentText}}</p>
            <input class="input-box" type="text" :placeholder="classifyState.placeholderText" v-model="classifyState.name">
        </div>
    </van-dialog>

    <!-- 移动分类 -->
    <van-popup 
        v-model:show="classifyMoveState.show" 
        round 
        position="bottom"
    >
        <van-cascader
            v-model="classifyMoveState.selectValue"
            title="移动至"
            :options="classifyMoveState.options"
            :field-names="{text:'ClassifyName',value:'ClassifyId',children:'Children'}"
            @close="classifyMoveState.show = false"
            @change="handleSelectMoveClassifyChange"
        />
        <div style="width:300px;margin:0 auto;padding:20px 0">
            <van-button type="primary" round block @click="handleConfirmMove">确定</van-button>
        </div>
    </van-popup>
</template>

<style lang="scss" scoped>
.edb-classify-wrap{
    height: 100%;
    display: flex;
    flex-direction: column;
    .top-box{
        height: calc(var(--van-popup-close-icon-margin) + 50px);
        background-color: #fff;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        padding-right: calc(var(--van-popup-close-icon-margin) + var(--van-popup-close-icon-size));
        padding-top: var(--van-popup-close-icon-margin);
        padding-left: 28px;
        .catalog-text-box{
            margin-left: 20px;
            flex: 1;
            overflow-x: auto;
            display: flex;
            &::-webkit-scrollbar{
                display: none;
                height: 0;
            }
            span{
                display: block;
                flex-shrink: 0;
                font-size: 32px;
                font-weight: 600;
                &::after{
                    content:'/'
                }
                &:last-child::after{
                    content:''
                }
            }
        }
    }
    .classify-box{
        flex: 1;
        overflow-y: auto;
        padding: 0 32px;
        .classify-item{
            display: flex;
            align-items: center;
            padding: 10px 0;
            .title{
                flex: 1;
                display: block;
            }
        }
    }
    .bot-btn-box{
        padding: 48px;
        flex-shrink: 0;
    }
    
}

.edit-classify-wrap{
    padding: 32px 48px;
    .input-box{
        width: 100%;
        box-sizing: border-box;
        display: block;
        padding: 24px 32px;
        background-color: #f6f6f6;
        border-radius: 12px;
    }
}


@media screen and (min-width:$media-width){
    .edb-classify-wrap{
        .top-box{
            height: calc(var(--van-popup-close-icon-margin) + 50px);
            padding-left: 14px;
            .catalog-text-box{
                margin-left: 10px;
                span{
                    font-size: 16px;
                }
            }
        }
        .classify-box{
            padding: 0 16px;
            .classify-item{
                padding: 5px 0;
            }
        }
        .bot-btn-box{
            padding: 24px;
        }
    }
    .edit-classify-wrap{
        padding: 16px 24px;
        .input-box{
            padding: 12px 16px;
            border-radius: 6px;
        }
    }
}
</style>