//部门管理 hook
import { ref, reactive } from 'vue'
import http from '@/api/http'
import { departInterence } from '@/api/api.js';
import { ElMessage, ElMessageBox } from 'element-plus'

export function useDepart(){
    //选择的部门
    let defaultDepart = ref('')
    //选择的分组
    let defaultGroup = ref('')
    let groupTeamId = 0
    let tableParams = reactive({
        searchTxt:'',
        pageNo:1,
        pageSize:10,
        total:0
    })

    //部门数据
    let departArr = ref([])
    //获取部门结构
    async function getDepartArr(){
        const res = await departInterence.getDepartList()
        if(res.Ret!==200) return 
        const list = res.Data.List||[]
        //给节点增加unicodeKey
        departArr.value = list.map(depart=>{
            depart.unicodeKey='depart_'+depart.DepartmentId
            depart.parentKey = 0
            if(depart.Child){
                depart.Child = depart.Child.map(group=>{
                    group.unicodeKey = 'group_'+group.DepartmentId
                    group.parentKey = depart.unicodeKey
                    if(group.Child){
                        group.Child = group.Child.map(team=>{
                            team.unicodeKey = 'team_'+team.DepartmentId
                            team.parentKey = group.unicodeKey
                            return team
                        })
                    }
                    return group
                })
            }
            return depart
        })
    }

    let tableData = ref([])
    //获取对应部门/分组下的用户数据
    function getTableUser(){
        const {searchTxt,pageSize,pageNo} = tableParams
        departInterence.getUserList({
            DepartmentId:defaultDepart.value,
            GroupId:defaultGroup.value,
            TeamId:groupTeamId,
            KeyWord:searchTxt,
            PageSize:pageSize,
            CurrentIndex:pageNo
        }).then(res => {
            if(res.Ret === 200) {
                tableData.value = res.Data.List || [];
                tableParams.total = res.Data.Paging.Totals;
            }
        })
    }

    //用户表格事件
    function useDepartTable(){
        let isShowUserdtl = ref(false)
        let userObj = ref(null)
        //打开添加/编辑用户弹窗 (原项目 addUser editUser 合成一个)
        let isModifyUserShow = ref(false)
        let modifyUserType = ref('add')
        let userInfo = ref({})
        function openUserDialog(type,data){
            modifyUserType.value = type
            userInfo.value = data
            isModifyUserShow.value = true
        }
        //打开重置密码弹窗
        let isResetPassShow = ref(false)
        function openResetPassDialog(data){
            userInfo.value = data
            isResetPassShow.value = true
        }
        //打开移动分组弹窗
        let isMoveDepartShow = ref(false)
        function openMoveDepartDialog(data){
            userInfo.value = data
            isMoveDepartShow.value = true
        }
        //添加编辑用户
        function modifyUser(data){
            const {type,userForm} = data
            const {direct} = userForm
            const ResearchGroupIds = direct.length?direct.map(i=>i[i.length-1]):[]
            //将userForm转为接口的形式
            const params = {
                AdminName: userForm.account,
                Password: new http.Base64().encode(userForm.pwd),
                EmployeeId:userForm.employeeNumber.replaceAll(' ',''),
                Authority: userForm.auth,
                DepartmentId: Number(userForm.depart[0]),
                GroupId:userForm.depart[1] ? Number(userForm.depart[1]) : 0,
                TeamId:userForm.depart[2] ? Number(userForm.depart[2]) : 0,
                Mobile: userForm.mobile,
                Position: userForm.post,
                RealName: userForm.name,
                RoleId: Number(userForm.role),
                Enabled:Number(userForm.status),
                ResearchGroupIds:ResearchGroupIds.join(','),
                Province:userForm.province,
                City:userForm.city,
                Email:userForm.email,
                TelAreaCode:userForm.areacode,
            }
            if(type==='edit'){
                params.AdminId = Number(userForm.admin_id)
            }
            const map = {
                'add':addUser,
                'edit':editUser
            }
            map[type]&&map[type](params)
        }
        function addUser(params){
            departInterence.addUser(params).then(res => {
                if(res.Ret === 200) {
                    ElMessage.success('添加成功');
                    getTableUser()
                    isModifyUserShow.value = false
                }
            })
        }
        function editUser(params){
            departInterence.editUser(params).then(res => {
                if(res.Ret === 200) {
                    ElMessage.success('编辑成功');
                    getTableUser()
                    isModifyUserShow.value = false
                }
            })
        }
        //删除用户,前端按钮因产品要求隐藏,函数保留
        function delUser(data){
            ElMessageBox.confirm(`是否确认删除用户【${data.AdminName}】`,'提示',{
                type:'warning'
            }).then(() => {
                departInterence.delUser({
                    AdminId:data.AdminId
                }).then(res => {
                    if(res.Ret === 200) {
                        ElMessage.success('删除成功')
                        getTableUser()
                    }
                })
            }).catch(() => {});
        }
        //重置用户密码
        function resetUserPassWord({user,form}){
            departInterence.resetSysuserPass({
                AdminId:Number(user.AdminId),
                Password:new http.Base64().encode(form.password),
                RePassword:new http.Base64().encode(form.password)
            }).then(res=>{
                if(res.Ret!==200) return 
                ElMessage.success('重置密码成功')
                isResetPassShow.value = false
                getTableUser()
            })
        }
        //移动用户分组
        function moveDepart({user,form}){
            departInterence.moveSysuser({
                AdminId:Number(user.AdminId),
                DepartmentId:Number(form.depart[0]),
                GroupId:Number(form.depart[1]?form.depart[1]:0),
                TeamId:Number(form.depart[2]?form.depart[2]:0),
            }).then(res=>{
                if(res.Ret!==200) return
                ElMessage.success('移动分组成功')
                isMoveDepartShow.value = false
                getTableUser()
            })
        }
        //改变用户启用禁用状态
        async function changeStatus(data){
            const res=await departInterence.statusChange({
                AdminId:Number(data.AdminId),
                Enabled:data.Enabled===1?0:1
            })
            if(res.Ret===200){
                ElMessage.success('设置成功')
                getTableUser()
            }
        }
        //查询用户详情
        async function getUserDetail(data){
            const res = await departInterence.getResearchGroupByAdminId({
                AdminId:data.AdminId
            })
            if(res.Ret!==200) return 
            //用户详情数据直接传入组件中,数据结构转换在组件内部处理
            userObj.value = {
                user:data,
                direct:res.Data||[]
            }
            isShowUserdtl.value = true
        }
        //获取研究方向分组列表
        let researchGroup = ref([])
        function getResearchGroup(){
            departInterence.getTagTree().then(res=>{
                if(res.Ret===200){
                    researchGroup.value = res.Data||[]
                }
            })
        }

        return {
            isShowUserdtl,userObj,
            isModifyUserShow,modifyUserType,userInfo,openUserDialog,
            isResetPassShow,openResetPassDialog,resetUserPassWord,
            isMoveDepartShow,openMoveDepartDialog,moveDepart,
            modifyUser,delUser,
            getUserDetail,changeStatus,
            getResearchGroup,researchGroup
        }
    }

    //树结构事件
    function useTreeEvent(){
        let act_node = ref('')
        //点击树节点
        function clickNode(node,data){
            console.log('node',node)
            console.log('data',data)
            act_node.value = data.unicodeKey
            /* 部门节点 */
            if(data.IsDepartment) {
                defaultDepart.value = data.DepartmentId;
                defaultGroup.value = '';
                groupTeamId = 0
            }else if(data.IsGroup){
                /* 分组节点 */
                defaultGroup.value = data.DepartmentId;
                defaultDepart.value = ''
                groupTeamId = 0
            } else {
                defaultGroup.value = data.GroupId;
                groupTeamId = data.DepartmentId
                defaultDepart.value = ''
            }
            tableParams.pageNo = 1;
            getTableUser();
        }
        //重置部门选中
        function initDepart(){
            defaultDepart.value = ''
            defaultGroup.value = ''
            act_node.value = ''
            groupTeamId = 0
            getDepartArr()
            tableParams.pageNo = 1
            getTableUser()
        }

        //打开添加/编辑部门/分组弹窗 (原项目中的addNode editNode addDepart合成一个)
        let modifyNodeType = ref('add')
        let nodeInfo = ref(null)
        let isModifyNodeShow = ref(false)
        /**
         * 
         * @param type  add or edit
         * @param data 树节点数据
         * @param node 树节点 只需要用到level
         */
        function openNodeDialog(type,data,{level}){
            modifyNodeType.value = type
            nodeInfo.value = {data,level}
            isModifyNodeShow.value = true
        }
        //添加编辑部门or分组
        /**
         * @param params
         * @param params.type add or edit 
         * @param params.nodeForm 节点修改的数据 {name,group}
         * @param params.nodeInfo 当前点击的树节点 {data,level}
         */
        async function modifyNode({type='add',nodeForm,nodeInfo}){
            const {level=0} = nodeInfo
            //根据level和type确定modify类型
            //level为0 增加部门
            //level为1 编辑部门&增加分组
            //level为2 编辑分组&增加分组
            //level为3 编辑分组
            const modifyMap = [
                {'add':addDepart},
                {'add':addGroup,'edit':editDepart},
                {'add':addGroup,'edit':editGroup},
                {'edit':editGroup}
            ]
            await modifyMap[level][type](nodeForm,nodeInfo)
            getDepartArr()
        }
        async function addDepart(form,{data}){
            await departInterence.addDepart({
                DepartmentName:form.departName
            }).then(res=>{
                if(res.Ret!==200) return 
                ElMessage.success("添加部门成功")
                isModifyNodeShow.value = false
            })
        }
        async function editDepart(form,{data}){
            console.log("编辑部门")
           await  departInterence.editDepart({
                DepartmentId:Number(data.DepartmentId),
                DepartmentName:form.departName
            }).then(res => {
                if(res.Ret!==200) return 
                ElMessage.success("编辑部门成功")
                isModifyNodeShow.value = false
            })
        }
        //部门添加分组 or 分组添加分组
        async function addGroup(form,{data}){
            const groups = form.group.map(i=>i.DepartmentName)
            const params = data.IsGroup
                ?{
                    DepartmentId:Number(data.TopId),
                    GroupId:Number(data.DepartmentId),
                    TeamName:groups.join(',')
                }:{
                    DepartmentId:Number(data.DepartmentId),
                    GroupName:groups.join(',')
                }
            const res = data.IsGroup
                ?await departInterence.addTeamGroup(params)
                :await departInterence.addGroup(params)
            if(res.Ret===200){
                ElMessage.success("添加分组成功")
                isModifyNodeShow.value = false
            }

        }
        async function editGroup(form,{data}){
            const params = data.IsGroup
                ?{
                    GroupId:Number(data.DepartmentId),
                    GroupName:form.groupName,
                }:{
                    TeamId:Number(data.DepartmentId),
                    TeamName:form.groupName
                }
            const res = data.IsGroup
                ?await departInterence.editGroup(params)
                :await departInterence.editTeamGroup(params)
            if(res.Ret===200) {
                ElMessage.success("编辑分组成功")
                isModifyNodeShow.value = false
            }
        }
        //删除节点 
        async function removeNode(data){
            let res = null
            if(data.IsDepartment) {
                res = await departInterence.delDepart({
                    DepartmentId:data.DepartmentId
                })
            }else if(data.IsGroup) {
                /* 删除分组 */
                res = await departInterence.delGroup({
                    GroupId:data.DepartmentId
                })
            }else {
                res = await departInterence.delTeamGroup({
                    TeamId:data.DepartmentId
                })
            }

            if(res&&res.Ret===200){
                ElMessage.success('删除成功')
                initDepart()
            }
        }
        return {
            act_node,
            clickNode,initDepart,removeNode,
            modifyNodeType,nodeInfo,isModifyNodeShow,openNodeDialog,modifyNode,
            
        }

    }
    //树结构移动
    function useTreeMove(){
        //节点是否可拖拽:所有节点均可拖拽
        function checkAllowDrag(){return true}
        //节点是否可放入:仅支持同部门下,同级节点相互排序
        function checkAllowDrop(draggingNode,dropNode,type){
            if(type==='inner'){
                /**
                 * 情况1 
                 * draggingNode.level==2 dropNode.level==1
                 * draggingNode.TopId == dropNode.DepartmentId
                 * 情况2
                 * draggingNode.level==3 dropNode.level==2
                 * draggingNode.GroupId == dropNode.DepartmentId
                 */
                const case_1 = draggingNode.level===2&&dropNode.level===1
                                && draggingNode.data.TopId === dropNode.data.DepartmentId
                const case_2 = draggingNode.level===3&&dropNode.level===2
                                && draggingNode.data.GroupId == dropNode.data.DepartmentId
                return case_1||case_2
            }else if(draggingNode.level===dropNode.level){
                /**
                 * 情况1
                 * draggingNode.level===dropNode.level===1
                 * 情况2
                 * draggingNode.level===dropNode.level
                 * draggingNode.TopId === dropNode.TopId||draggingNode.GroupId===dropNode.GroupId
                 */
                const case_1 = dropNode.level===1
                const case_2 = draggingNode.data.TopId&&dropNode.data.TopId&&draggingNode.data.TopId === dropNode.data.TopId
                        ||draggingNode.data.GroupId&&dropNode.data.GroupId&&draggingNode.data.GroupId===dropNode.data.GroupId
                return case_1||case_2
            }
            return false
        }
        //放入节点
        let departTree = ref(null)
        function handleDropOver(draggingNode,dropNode,type,e){
            //获取当前移动节点的层级和id,parentId
            //获取同层级的ids
            const treeData = departTree.value.data||[]
            const node = departTree.value.getNode(draggingNode.data.parentKey)||{data:{Child:[]}}
            let params = {
                DepartmentIds:[],
                GroupIds:[],
                TeamIds:[]
            }
            if(draggingNode.level===1){
                params.DepartmentIds = treeData.map(i=>i.DepartmentId)
            }else{
                const ids = node.data.Child.map(i=>i.DepartmentId)
                params.GroupIds = draggingNode.level===2?ids:[]
                params.TeamIds =draggingNode.level===3?ids:[]
            }
            departInterence.sortDepart(params).then(res=>{
                if(res.Ret!==200) return 
                ElMessage.success('移动排序成功')
                getDepartArr()
            })
        }
        return {
            departTree,
            checkAllowDrag,
            checkAllowDrop,
            handleDropOver
        }
    }


    return {
        groupTeamId,departArr,
        defaultDepart,defaultGroup,
        tableParams,tableData,
        getTableUser,getDepartArr,
        useTreeMove,
        useTreeEvent,
        useDepartTable
    }
}

