package com.cool.modules.dingtalk.controller.admin;

import cn.hutool.json.JSONObject;
import com.cool.core.annotation.CoolRestController;
import com.cool.core.base.BaseController;
import com.cool.core.request.R;
import com.cool.modules.dingtalk.entity.DingtalkDepartmentEntity;
import com.cool.modules.dingtalk.mapper.DingtalkDepartmentMapper;
import com.cool.modules.dingtalk.service.DingtalkDepartmentService;
import com.cool.modules.user.entity.UserInfoEntity;
import com.cool.modules.user.mapper.UserInfoMapper;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cool.modules.dingtalk.entity.table.DingtalkDepartmentEntityTableDef.DINGTALK_DEPARTMENT_ENTITY;
import static com.cool.modules.user.entity.table.UserInfoEntityTableDef.USER_INFO_ENTITY;

/**
 * 钉钉部门管理Controller
 */
@Slf4j
@Tag(name = "钉钉部门", description = "钉钉部门管理")
@CoolRestController(api = {"page", "list"})
@RequiredArgsConstructor
public class AdminDingtalkDepartmentController extends BaseController<DingtalkDepartmentService, DingtalkDepartmentEntity> {

    private final DingtalkDepartmentMapper departmentMapper;
    private final UserInfoMapper userInfoMapper;

    @Override
    protected void init(HttpServletRequest request, JSONObject requestParams) {
        setPageOption(createOp()
                .keyWordLikeFields(DINGTALK_DEPARTMENT_ENTITY.NAME)
                .queryWrapper(QueryWrapper.create().orderBy(DINGTALK_DEPARTMENT_ENTITY.DEPT_ORDER, true))
        );
    }

    @Operation(summary = "获取部门树", description = "获取部门树结构")
    @GetMapping("/tree")
    public R getDepartmentTree() {
        log.info("【钉钉部门Controller】获取部门树");

        try {
            // 获取所有部门
            List<DingtalkDepartmentEntity> allDepts = departmentMapper.selectAll();

            // 构建树结构
            List<Map<String, Object>> tree = buildTree(allDepts, 1L);

            log.info("【钉钉部门Controller】部门树获取成功, 根节点数量: {}", tree.size());
            return R.ok(tree);

        } catch (Exception e) {
            log.error("【钉钉部门Controller】获取部门树失败", e);
            return R.error("获取部门树失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取部门员工", description = "根据钉钉部门ID获取该部门的员工列表")
    @GetMapping("/users")
    public R getDepartmentUsers(@RequestParam Long deptId) {
        log.info("【钉钉部门Controller】获取部门员工, deptId: {}", deptId);

        try {
            // 查询该部门下的所有员工
            QueryWrapper qw = QueryWrapper.create()
                    .where(USER_INFO_ENTITY.DINGTALK_DEPT_ID.eq(deptId))
                    .orderBy(USER_INFO_ENTITY.CREATE_TIME, false);

            List<UserInfoEntity> users = userInfoMapper.selectListByQuery(qw);

            log.info("【钉钉部门Controller】部门员工获取成功, 数量: {}", users.size());
            return R.ok(users);

        } catch (Exception e) {
            log.error("【钉钉部门Controller】获取部门员工失败", e);
            return R.error("获取部门员工失败: " + e.getMessage());
        }
    }

    /**
     * 构建部门树
     *
     * @param allDepts 所有部门
     * @param parentId 父部门ID
     * @return 部门树
     */
    private List<Map<String, Object>> buildTree(List<DingtalkDepartmentEntity> allDepts, Long parentId) {
        List<Map<String, Object>> tree = new ArrayList<>();

        for (DingtalkDepartmentEntity dept : allDepts) {
            if (dept.getParentId().equals(parentId)) {
                Map<String, Object> node = new HashMap<>();
                node.put("id", dept.getId());
                node.put("deptId", dept.getDeptId());
                node.put("name", dept.getName());
                node.put("parentId", dept.getParentId());
                node.put("deptOrder", dept.getDeptOrder());
                node.put("createTime", dept.getCreateTime());
                node.put("updateTime", dept.getUpdateTime());

                // 递归获取子部门
                List<Map<String, Object>> children = buildTree(allDepts, dept.getDeptId());
                if (!children.isEmpty()) {
                    node.put("children", children);
                }

                tree.add(node);
            }
        }

        return tree;
    }
}
