<script setup>
import { ref,nextTick } from "vue";
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
import {businessCustomInterence} from '@/api/api.js'

const route = useRoute()
const router = useRouter()

const isApprove = ref('')
const approveList = ref([])
function getBusinessConfigList(){
    const EtaBusinessId = route.query.id
    if(!EtaBusinessId) return 
    businessCustomInterence.getConfigList({
        EtaBusinessId:Number(EtaBusinessId)
    }).then(res=>{
        if(res.Ret!==200) return
        const list = res.Data||[]
        const approveItem = list.find(i=>i.ConfigCode==='approval_flow')
        if(!approveItem) return
        if(!approveItem.ConfigValue.length){
            isApprove.value = approveItem.ConfigValue
            return
        }
        if(Number(approveItem.ConfigValue)===0){
            isApprove.value = Number(approveItem.ConfigValue)
            return
        }
        if(Number(approveItem.ConfigValue)>0){
            isApprove.value = 1
            approveList.value = approveItem.ConfigValue==3?[1,2]:[Number(approveItem.ConfigValue)]
        }
    })
}
getBusinessConfigList()



const authList = ref([])
const defaultCheckedKeys = ref([])
const treeLoading = ref(false)
const model = ref('auth')
const checkList = ref([])
function getBusinessAuthList(){
    const EtaBusinessId = route.query.id
    if(!EtaBusinessId) return 
    treeLoading.value = true
    businessCustomInterence.getAuthList({
        EtaBusinessId:Number(EtaBusinessId)
    }).then(res=>{
        if(res.Ret!==200) return 
        treeLoading.value = false
        if(!res.Data) return

        const {List,ChoiceList=[],HalfChoiceList=[]} = res.Data
        authList.value = List||[]
        checkList.value = ChoiceList
        authList.value.forEach(item=>{
            checkTree(item)
        })
        //this.defaultCheckedKeys = ChoiceList.filter((item)=>!HalfChoiceList.some((halfItem)=>item===halfItem))
        nextTick(()=>{
            authList.value.forEach(item=>{
                checkTree(item)
            })
            defaultCheckedKeys.value = checkList.value
            handleCheckChange(defaultCheckedKeys.value)
        })
        
    })
}
getBusinessAuthList()

function checkTree(data){
    //非叶子节点递归
    if(data.Children && data.Children.length){
        data.Children = data.Children.map(i=>{
            return checkTree(i)
        })
    }
    //叶子节点向上检查MenuId
    if(!data.Children||data.Children&&data.Children.length===0){
        checkDataList(data)
    }
    return data
}

function checkDataList(data){
    //获取data的MenuId 和 checkList对比 
    //如果MenuId不在checkList里，检查data.ParentId在不在checkList里，若在，则从checkList里去除
    if(!checkList.value.includes(data.MenuId)&&checkList.value.includes(data.ParentId)){
        const index = checkList.value.indexOf(data.ParentId)
        index!==-1&&checkList.value.splice(index,1)
        console.log('应该去除的节点',data.ParentId)
    }
    //向上检查MenuId
    const parentNode = findTreeNode(data.ParentId)
    if(parentNode){
        checkDataList(parentNode.data)
    }
}
//根据MenuId找到对应节点
const checkboxTree = ref(null)
function findTreeNode(MenuId){
    return checkboxTree.value.getNode(MenuId)
}

const checkAll = ref(false)
const isIndeterminate = ref(false)
function handleCheckChange(choiceList/* ,HalfChoiceList */){
    const keys = choiceList||checkboxTree.value.getCheckedKeys()

    const ChoiceList = Array.from(new Set([...keys]))
    const topLevelNodes = authList.value.map(i=>i.MenuId)
    let nodeLength = 0
    topLevelNodes.forEach(i=>{
        if(ChoiceList.includes(i)){nodeLength++}
        if(!ChoiceList.includes(i)){nodeLength--}
    })
    if(nodeLength===topLevelNodes.length){
        checkAll.value = true
        isIndeterminate.value = false
    }else{
        checkAll.value = false
        isIndeterminate.value = Boolean(ChoiceList.length)
    }
}



 async function handleBtnClik(type){
    if(type==='save'){
        //获取树形列表选择的项 getCheckedKeys getHalfCheckedKeys
        const keys = checkboxTree.value.getCheckedKeys()
        const halfKeys = checkboxTree.value.getHalfCheckedKeys()
        if(!keys.length&&!halfKeys.length){
            ElMessage.warning('请至少选择一个权限')
            return
        }
        //合成一个数组并去重
        const ChoiceList = Array.from(new Set([...keys,...halfKeys]))
        //请求接口
        const res = await businessCustomInterence.setAuthList({
            EtaBusinessId:Number(route.query.id),
            MenuIds:ChoiceList,
            HalfMenuIds:halfKeys
        })
        if(res.Ret!==200) return 
        ElMessage.success('权限设置成功')

     
    }
    router.push('/businessETAList')
}


</script>
<template>
<div class="business-auth-wrap">
    <div class="header">
        <div class="name">{{route.query.name||''}}</div>
        <div class="btn-wrap">
            <el-button @click="handleBtnClik('cancel')">取消</el-button>
            <el-button type="primary" @click="handleBtnClik('save')">保存</el-button>
        </div>
    </div>
    <div class="model-wrap">
        <el-button :type="model==='auth'?'primary':''" @click="model='auth'">菜单权限</el-button>
    </div>
    <div class="auth-wrap" v-show="model==='auth'">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" style="margin-bottom: 20px;">全选</el-checkbox>
        <el-tree 
            v-loading="treeLoading"
            ref="checkboxTree"
            :data="authList" 
            :props="{label:'Name',children:'Children'}" 
            :default-expand-all="false"
            show-checkbox 
            node-key="MenuId"
            :default-checked-keys="defaultCheckedKeys"
            @check-change="()=>{handleCheckChange()}">
        </el-tree>
    </div>
</div>
</template>
<style scoped lang="scss">
.business-auth-wrap{
    border: 1px solid #ECECEC;
    padding: 20px 30px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    .header{
        display: flex;
        justify-content: space-between;
        align-items: center;
        .name{
            font-size: 18px;
            font-weight: bold;
        }
    }
    .model-wrap{
        display: flex;
        gap:20px;
        align-items: center;
        .block{
            display: inline-block;
            height:20px;
            width:1px;
            background-color: #333;
        }
    }
    .auth-wrap,.interence-wrap{
        margin-top:20px;
    }
    .interence-item{
        display: flex;
        gap:25px;
    }

    :deep(.el-tree) {
        border-top: 1px solid #E5E7ED;
        border-left: 1px solid #E5E7ED;
        border-right: 1px solid #E5E7ED;
        width: 98%;
        margin-bottom: 40px;
        .el-tree-node__label{
            margin:10px;
        }
        .el-tree-node__content{
            min-width: 200px;
            width: 200px;
            white-space: normal;
            box-sizing: border-box;
        }
        .el-tree-node{
            .el-tree-node{
                .el-tree-node__children{
                    width: 100%;
                }
                .el-tree-node{
                    &:not(:first-child){
                    /* .el-tree-node__content{
                        border-right: 1px solid #E5E7ED;
                    } */
                        border-top: 1px solid #E5E7ED;
                    }
                    .el-tree-node__content{
                        border-right: 1px solid #E5E7ED;
                    }
                }
    
            }
        }
        .el-tree-node__content {
            padding: 5px 10px !important;
            height: auto;
            .el-tree-node__expand-icon.el-icon-caret-right {
            //display: none;
            }
        }
        > .el-tree-node {
            padding: 0 !important;
            display: flex;
            border-bottom: 1px solid #E5E7ED;

            > .el-tree-node__children {
            width: 100%;
            > .el-tree-node {
                &:not(:first-child) {
                border-top: 1px solid #E5E7ED;
                }
                >.el-tree-node__content{
                    border-left: 1px solid #E5E7ED;
                    border-right: 1px solid #E5E7ED;
                }
            }
            }
        }
        .el-tree-node__children {
            display: flex;
            flex-direction: column;
            .el-tree-node {
                display: flex;
                flex: 1;
                padding: 0px !important;
                .el-tree-node__content {
                    border-bottom: none;
                    .custom-tree-node {
                    height: 24px;
                    display: flex;
                    align-items: center;
                    .tree-btn {
                        margin-left: 10px;
                        display: none;
                    }
                    .el-button {
                        padding: 0px !important;
                        border-radius: 4px;
                        background: #363554;
                        color: #ffffff;
                    }
                    }
                }
                .el-tree-node__children {
                    .el-tree-node {
                    &:not(:first-child) {
                        .el-tree-node__content {
                        //border-left: none;
                        }
                    }
                    }
                }
            }
        }
    }
}
</style>
