package com.tuoheng.miniprogram.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import com.tuoheng.miniprogram.dao.DeptMapper;
import com.tuoheng.miniprogram.entity.Dept;
import com.tuoheng.miniprogram.entity.User;
import com.tuoheng.miniprogram.enums.DataPermissionEnum;
import com.tuoheng.miniprogram.enums.MarkEnum;
import com.tuoheng.miniprogram.enums.UserCodeEnum;
import com.tuoheng.miniprogram.service.IDeptService;
import com.tuoheng.miniprogram.utils.CurrentUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author ChengWang
 * @Date 2022/11/21
 */
@Service
public class DeptServiceImpl implements IDeptService {

    @Autowired
    private DeptMapper deptMapper;

    /**
     * 获取部门列表(树形)
     * @return
     */
    @Override
    public JsonResult treeList() {
        List<Dept> list = deptMapper.selectList(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getMark, 1));
        // 获取所有一级节点
        //预设id值为2
        List<Dept> result = list.stream().
                filter(dept -> dept.getPid().equals("1"))
                .peek(dept -> dept.setItemList(getChildren(dept, list))).sorted(Comparator.comparingInt(dept -> (dept.getSort() == null ? 0 : dept.getSort())))
                .collect(Collectors.toList());
        return JsonResult.success(result);
        }

    @Override
    public JsonResult test(String id) {
        List<String> list = deptMapper.selectAllChildListById(id);

        return JsonResult.success(list);
    }

    @Override
    public JsonResult list() {
        User user = CurrentUserUtil.getUserInfo();
        String tenantId = user.getTenantId();
        Integer dataPermission = user.getDataPermission();
        String deptId = user.getDeptId();
        if(StringUtils.isEmpty(deptId)){
            return JsonResult.error("当前用户部门为空");
        }
        List<Dept> deptList = new ArrayList<>();
        if(null == dataPermission){
            return JsonResult.error(DataPermissionEnum.DATA_PERMISSION_IS_NOT_EXIST.getCode(),
                    DataPermissionEnum.DATA_PERMISSION_IS_NOT_EXIST.getDescription());
        }
        if(DataPermissionEnum.ALL.getCode() == dataPermission){
            deptList = deptMapper.selectList(Wrappers.<Dept>lambdaQuery()
                    .eq(Dept::getMark, MarkEnum.VALID.getCode())
                    .eq(Dept::getTenantId, tenantId));
        }
        if(DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == dataPermission){
            //获取当前部门及其子部门
            List<String> deptIdList = deptMapper.selectAllChildListById(deptId);
            if(CollectionUtil.isNotEmpty(deptIdList)){
                for (String id : deptIdList) {
                    Dept dept = deptMapper.selectById(id);
                    deptList.add(dept);
                }
            }
        }
        if(DataPermissionEnum.DEPT.getCode() == dataPermission){
            //查询当前部门
            Dept dept = deptMapper.selectById(deptId);
            deptList.add(dept);
        }

        return JsonResult.success(deptList);
    }


    /**
     * 递归获取部门的子集
     *
     * @author zhu_zishuang
     * @date 3/13/21
     */
    private List<Dept> getChildren(Dept rootDept, List<Dept> list) {
        return list.stream().filter(dept ->
                dept.getPid().equals(rootDept.getId())
        ).peek(dept -> {
            // 设置子集
            dept.setItemList(getChildren(dept, list));
        }).sorted(Comparator.comparingInt(dept -> (dept.getSort() == null ? 0 : dept.getSort()))).collect(Collectors.toList());
    }
}
