package com.fs.qw.service.impl;

import com.fs.common.core.domain.R;
import com.fs.qw.domain.QwDept;
import com.fs.qw.domain.QwDeptTreeSelect;
import com.fs.qw.mapper.QwDeptMapper;
import com.fs.qw.service.IQwDeptService;
import com.fs.qwApi.domain.QwDeptResult;
import com.fs.qwApi.domain.inner.Department;
import com.fs.qwApi.service.QwApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 企业微信部门Service业务层处理
 *
 * @author fs
 * @date 2024-08-27
 */
@Service
public class QwDeptServiceImpl implements IQwDeptService
{
    @Autowired
    private QwDeptMapper qwDeptMapper;

    @Autowired
    private QwApiService qwApiService;

    /**
     * 查询企业微信部门
     *
     * @param id 企业微信部门主键
     * @return 企业微信部门
     */
    @Override
    public QwDept selectQwDeptById(Long id)
    {
        return qwDeptMapper.selectQwDeptById(id);
    }

    /**
     * 查询企业微信部门列表
     *
     * @param qwDept 企业微信部门
     * @return 企业微信部门
     */
    @Override
    public List<QwDept> selectQwDeptList(QwDept qwDept)
    {
        return qwDeptMapper.selectQwDeptList(qwDept);
    }

    /**
     * 新增企业微信部门
     *
     * @param qwDept 企业微信部门
     * @return 结果
     */
    @Override
    public int insertQwDept(QwDept qwDept)
    {
        return qwDeptMapper.insertQwDept(qwDept);
    }


    /**
     * 新增或插入 企业微信部门
     */
    @Override
    public R insertOrUpdateQwDept(String corpId) {

        QwDeptResult departmentList = qwApiService.getDepartmentList(corpId);

        if (departmentList.getErrcode() == 0) {
            List<Department> department = departmentList.getDepartment();
            for (Department dept : department) {
                QwDept qwDept = new QwDept();
                qwDept.setDeptId(Long.valueOf(dept.getId()));
                qwDept.setDeptName(dept.getName());
                qwDept.setCorpId(corpId);
                qwDept.setParentid(Long.valueOf(dept.getParentid()));
                int i = qwDeptMapper.insertOrUpdateQwDept(qwDept);
            }
        }else {
            return R.error("同步失败："+departmentList.getErrmsg());
        }

        return null;
    }

    /**
     * 修改企业微信部门
     *
     * @param qwDept 企业微信部门
     * @return 结果
     */
    @Override
    public int updateQwDept(QwDept qwDept)
    {
        return qwDeptMapper.updateQwDept(qwDept);
    }

    /**
     * 批量删除企业微信部门
     *
     * @param ids 需要删除的企业微信部门主键
     * @return 结果
     */
    @Override
    public int deleteQwDeptByIds(Long[] ids)
    {
        return qwDeptMapper.deleteQwDeptByIds(ids);
    }

    @Override
    public int deleteQwDeptByDeptId(QwDept qwDept) {
        return qwDeptMapper.deleteQwDeptByDeptId(qwDept);
    }

    /**
     * 删除企业微信部门信息
     *
     * @param id 企业微信部门主键
     * @return 结果
     */
    @Override
    public int deleteQwDeptById(Long id)
    {
        return qwDeptMapper.deleteQwDeptById(id);
    }

    /**
     * @Description: 按TreeSelect结构返回部门
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2025/10/30 9:37
     */
    @Override
    /**
     * 将部门列表转换为TreeSelect树形结构
     */
    public List<QwDeptTreeSelect> buildDeptTreeSelect(List<QwDept> deptList) {
        if (deptList == null || deptList.isEmpty()) {
            return new ArrayList<>();
        }

        // 按父部门ID分组
        Map<Long, List<QwDept>> deptMap = deptList.stream()
                .collect(Collectors.groupingBy(QwDept::getParentid));

        // 获取所有根部门（parentId = 0）
        List<QwDept> rootDepts = deptMap.getOrDefault(0L, new ArrayList<>());

        // 构建树形结构
        return rootDepts.stream()
                .map(dept -> buildTreeSelect(dept, deptMap))
                .collect(Collectors.toList());
    }

    /**
     * 递归构建TreeSelect节点
     */
    private QwDeptTreeSelect buildTreeSelect(QwDept dept, Map<Long, List<QwDept>> deptMap) {
        return buildTreeSelect(dept, deptMap, 0);
    }

    /**
     * 递归构建TreeSelect节点，最多5级
     */
    private QwDeptTreeSelect buildTreeSelect(QwDept dept, Map<Long, List<QwDept>> deptMap, int depth) {
        // 限制最多5级，避免死循环
        if (depth > 5) {
            return new QwDeptTreeSelect(dept.getDeptId(), dept.getDeptName());
        }

        QwDeptTreeSelect treeSelect = new QwDeptTreeSelect(dept.getDeptId(), dept.getDeptName());

        // 获取当前部门的子部门
        List<QwDept> children = deptMap.get(dept.getDeptId());
        if (children != null && !children.isEmpty()) {
            // 递归构建子节点
            List<QwDeptTreeSelect> childNodes = children.stream()
                    .map(child -> buildTreeSelect(child, deptMap, depth + 1))
                    .collect(Collectors.toList());
            treeSelect.setChildren(childNodes);
        }

        return treeSelect;
    }




}
