package com.zxdmy.excite.system.service.impl.cloud.account;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxdmy.excite.common.entity.PageList;
import com.zxdmy.excite.common.exception.ServiceException;
import com.zxdmy.excite.system.entity.cloud.account.CloudDepartmentUser;
import com.zxdmy.excite.system.entity.SysUser;
import com.zxdmy.excite.system.entity.cloud.account.CloudCompany;
import com.zxdmy.excite.system.entity.cloud.account.CloudDepartment;
import com.zxdmy.excite.system.entity.dto.DepartmentUserTreeNode;
import com.zxdmy.excite.system.entity.req.account.ReqDepartment;
import com.zxdmy.excite.system.entity.vo.account.DepartmentVo;
import com.zxdmy.excite.system.mapper.SysUserMapper;
import com.zxdmy.excite.system.mapper.cloud.account.CloudCompanyMapper;
import com.zxdmy.excite.system.mapper.cloud.account.CloudDepartmentMapper;
import com.zxdmy.excite.system.mapper.cloud.account.CloudDepartmentUserMapper;
import com.zxdmy.excite.system.service.cloud.account.ICloudDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.xml.transform.Result;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author ss
 * @since 2026-01-24
 */
@Service
@AllArgsConstructor
public class CloudDepartmentServiceImpl extends ServiceImpl<CloudDepartmentMapper, CloudDepartment> implements ICloudDepartmentService {

    private CloudDepartmentMapper cloudDepartmentMapper;
    private CloudCompanyMapper cloudCompanyMapper;
    private SysUserMapper sysUserMapper;
    private CloudDepartmentUserMapper cloudDepartmentUserMapper;
    @Override
    public PageList<DepartmentVo> queryByPage(Integer page, Integer limit, ReqDepartment data) {
        Integer pages = limit * (page - 1);
        ArrayList<DepartmentVo> list = cloudDepartmentMapper.queryByPage(pages, limit,data);
        Integer count = cloudDepartmentMapper.queryByPageCount(data);
        return new PageList<DepartmentVo>(list,page,limit,count);
    }

    @Override
    public DepartmentVo getByData(ReqDepartment data) {
        return cloudDepartmentMapper.getData(data);
    }

    @Override
    public int saveData(ReqDepartment data) {
        LocalDateTime localDateTime = LocalDateTime.now();
        CloudDepartment saveData = new CloudDepartment();


        QueryWrapper<CloudCompany> wrapper = new QueryWrapper<>();
        wrapper.eq("id",data.getId());
        Integer company = cloudCompanyMapper.selectCount(wrapper);
        if(company>0){
            saveData.setDepartmentParentId(Long.valueOf("0"));
            saveData.setCompanyId(Long.valueOf(data.getId()));
        }else{
            saveData.setDepartmentParentId(Long.valueOf(data.getId()));
            saveData.setCompanyId(Long.valueOf(data.getCompanyId()));
        }
        saveData.setDepartmentName(data.getDepartmentName());
        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        saveData.setDepartmentSort(0);
        saveData.setCreatorId(sysUser.getId());
        saveData.setCreatorName(sysUser.getUsername());
        saveData.setCreateTime(localDateTime);
        if(cloudDepartmentMapper.insert(saveData)==1){
            return 1;
        }
        return 0;
    }

    @Override
    public int updateData(ReqDepartment data) {
        CloudDepartment updateData = new CloudDepartment();
        updateData.setId(Long.valueOf(data.getId()));
        updateData.setDepartmentName(data.getDepartmentName());
        if(cloudDepartmentMapper.updateById(updateData)==1){
            return 1;
        }
        return 0;
    }

    @Override
    public int deleteById(String id) {
        if (null == id) {
            throw new ServiceException("删除的ID不能为空！");
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        CloudDepartment data = cloudDepartmentMapper.selectById(id);
        if(null!=data){
            data.setDeleteId(sysUser.getId());
            data.setDeleteName(sysUser.getUsername());
            data.setDeleteTime(localDateTime);
            return cloudDepartmentMapper.updateById(data);
        }else{
            return 0;
        }
    }

    @Override
    public int changeDepartment(String userId, String departmentId) {
        QueryWrapper<CloudDepartmentUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<CloudDepartmentUser> list = cloudDepartmentUserMapper.selectList(queryWrapper);
        if (list.size()>0) {
            CloudDepartmentUser cloudDepartmentUser = cloudDepartmentUserMapper.selectById(list.get(0).getId());
            cloudDepartmentUser.setDepartmentId(Long.valueOf(departmentId));
            return cloudDepartmentUserMapper.updateById(cloudDepartmentUser);
        }
        return 0;
    }
    @Override
    public List<CloudDepartment> getList(Long id) {
        return cloudDepartmentMapper.getList(id);
    }


    public List<DepartmentUserTreeNode> buildDepartmentUserTree(Long companyId) {
        // 1. 查询所有部门
        List<CloudDepartment> departments = cloudDepartmentMapper.selectByCompanyId(companyId);

        // 2. 查询所有部门-用户关系
        List<CloudDepartmentUser> departmentUsers = cloudDepartmentUserMapper.selectByCompanyId(companyId);

        // 3. 按部门分组用户关系
        Map<Long, List<CloudDepartmentUser>> deptUserMap = departmentUsers.stream()
                .collect(Collectors.groupingBy(CloudDepartmentUser::getDepartmentId));

        // 4. 查询所有用户信息
        List<Integer> userIds = departmentUsers.stream()
                .map(CloudDepartmentUser::getUserId)
                .distinct()
                .collect(Collectors.toList());

        Map<Integer, SysUser> userMap = new HashMap<>();
        if (!userIds.isEmpty()) {
            List<SysUser> users = sysUserMapper.selectByIds(userIds);
            users.forEach(user -> userMap.put(user.getId(), user));
        }

        // 5. 构建部门树节点映射
        Map<Long, DepartmentUserTreeNode> deptNodeMap = new HashMap<>();
        for (CloudDepartment dept : departments) {
            DepartmentUserTreeNode node = new DepartmentUserTreeNode(dept);
            deptNodeMap.put(dept.getId(), node);
        }

        // 6. 将用户添加到部门节点
        for (Map.Entry<Long, List<CloudDepartmentUser>> entry : deptUserMap.entrySet()) {
            Long deptId = entry.getKey();
            DepartmentUserTreeNode deptNode = deptNodeMap.get(deptId);
            if (deptNode != null) {
                for (CloudDepartmentUser du : entry.getValue()) {
                    SysUser user = userMap.get(du.getUserId());
                    if (user != null) {
                        DepartmentUserTreeNode userNode = new DepartmentUserTreeNode(user, deptId);
                        deptNode.getChildren().add(userNode);
                    }
                }
            }
        }

        // 7. 构建树形结构
        List<DepartmentUserTreeNode> tree = new ArrayList<>();
        for (DepartmentUserTreeNode node : deptNodeMap.values()) {
            if (node.getParentId() == 0) {
                // 根节点
                tree.add(node);
                buildTreeRecursive(node, deptNodeMap);
            }
        }

        // 8. 排序
        sortTreeNodes(tree);

        return tree;
    }

    private void buildTreeRecursive(DepartmentUserTreeNode parentNode,
                                    Map<Long, DepartmentUserTreeNode> deptNodeMap) {
        // 添加子部门
        List<DepartmentUserTreeNode> children = new ArrayList<>();
        for (DepartmentUserTreeNode node : deptNodeMap.values()) {
            if (node.getType().equals("department") &&
                    parentNode.getId().equals(node.getParentId())) {
                children.add(node);
                buildTreeRecursive(node, deptNodeMap);
            }
        }

        // 合并已有的用户节点
        if (!parentNode.getChildren().isEmpty()) {
            // 只保留用户节点，部门节点在children中添加
            List<DepartmentUserTreeNode> userNodes = parentNode.getChildren().stream()
                    .filter(n -> n.getType().equals("user"))
                    .collect(Collectors.toList());
            children.addAll(userNodes);
        }

        parentNode.setChildren(children);
    }

    /**
     * 排序：部门按sort排序，用户按name排序
     */
    private void sortTreeNodes(List<DepartmentUserTreeNode> nodes) {
        if (nodes == null || nodes.isEmpty()) {
            return;
        }

        nodes.sort((n1, n2) -> {
            if (n1.getType().equals("department") && n2.getType().equals("department")) {
                return Integer.compare(n1.getSort(), n2.getSort());
            } else if (n1.getType().equals("user") && n2.getType().equals("user")) {
                return n1.getTitle().compareTo(n2.getTitle());
            } else {
                // 部门在前，用户在后
                return n1.getType().equals("department") ? -1 : 1;
            }
        });

        for (DepartmentUserTreeNode node : nodes) {
            if (node.getType().equals("department") && !node.getChildren().isEmpty()) {
                sortTreeNodes(node.getChildren());
            }
        }
    }
}
