package com.maintain.system.util;

import cn.dev33.satoken.secure.BCrypt;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.maintain.common.core.domain.entity.SysDept;
import com.maintain.common.core.domain.entity.SysUser;
import com.maintain.common.enums.IsEnableStatus;
import com.maintain.common.enums.UserStatus;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class ExternalDataDispose {

    // 定义部门类，对应JSON中的字段
    @Data
    public static class Department {
        private String deptName;
        private String upperDeptName;
        private String upperDeptCode;
        private String deptType;
        private String deptCode;
        private String deptFullName;
        private String status;
    }

    // 定义用户类，对应JSON中的字段
    @Data
    public static class user {
        private String filaNo;
        private String groupName;
        private String lineNo;
        private String empName;
        private String statusName;
        private String lineName;
        private String empNo;
        private String groupNo;
        private String subStatusName;
        private String filaName;
        private String subStatus;
        private String status;
    }

    /**
     * 处理部门数据，返回 SysDept 列表
     */
    public static List<SysDept> deptExtracted() {
        List<SysDept> sysDeptList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<Department> departments = objectMapper.readValue(
                new File("C:\\Users\\admin\\Desktop\\维修管理系统\\组织信息.json"),
                new TypeReference<List<Department>>() {}
            );

            log.info("共解析出 {} 条部门信息", departments.size());

            // 构建部门代码（原始 deptCode，包含字母）到部门的映射
            Map<String, Department> deptMap = departments.stream()
                .filter(dept -> dept.getDeptCode() != null && !dept.getDeptCode().isEmpty())
                .collect(Collectors.toMap(
                    Department::getDeptCode,
                    dept -> dept,
                    (existing, replacement) -> existing
                ));

            for (Department dept : departments) {
                SysDept sysDept = new SysDept();
                sysDept.setDeptName(dept.getDeptName());
                sysDept.setDeptId(parseDeptId(dept.getDeptCode())); // 提取数字ID
                sysDept.setParentId(parseDeptId(dept.getUpperDeptCode())); // 提取上级数字ID

                // 状态转换（注意：原逻辑可能反向，需确认业务需求）
                sysDept.setStatus(
                    dept.getStatus().equals("已启用")
                        ? String.valueOf(IsEnableStatus.YES.getCode()) // 已启用对应YES？
                        : String.valueOf(IsEnableStatus.NO.getCode())
                );

                // 构建 ancestors（使用原始 upperDeptCode 中的数字部分）
                String ancestors = buildAncestors(dept, deptMap);
                sysDept.setAncestors(ancestors);

                sysDeptList.add(sysDept);
            }
            return sysDeptList;
        } catch (IOException e) {
            log.error("读取部门 JSON 文件失败", e);
            return sysDeptList;
        }
    }

    /**
     * 从 deptCode 提取数字部分（如 "D50018" -> 50018）
     */
    private static long parseDeptId(String deptCode) {
        if (deptCode == null || deptCode.isEmpty()) {
            return 0L;
        }
        String numericPart = deptCode.replaceAll("[^0-9]", "");
        return numericPart.isEmpty() ? 0L : Long.parseLong(numericPart);
    }

    /**
     * 递归构建 ancestors 路径（格式：0,父部门数字ID,祖父部门数字ID,...）
     * 示例：对于 D50018（上级5009，上级的上级500），路径为 0,500,5009（不包含当前部门ID）
     */
    private static String buildAncestors(Department dept, Map<String, Department> deptMap) {
        if (dept == null) {
            return "0"; // 根节点默认祖先为0
        }

        String upperDeptCode = dept.getUpperDeptCode();
        if (upperDeptCode == null || upperDeptCode.equals("0")) {
            return "0"; // 顶级部门的祖先只有根节点0
        }

        // 获取上级部门（通过原始 upperDeptCode 查找，可能包含字母）
        Department parentDept = deptMap.get(upperDeptCode);
        if (parentDept == null) {
            log.warn("未找到上级部门：{}", upperDeptCode);
            return "0"; // 找不到上级时默认挂根节点
        }

        // 递归获取上级祖先路径，并拼接上级部门的数字ID（不包含当前部门ID）
        String parentAncestors = buildAncestors(parentDept, deptMap);
        long parentDeptId = parseDeptId(parentDept.getDeptCode()); // 上级部门的数字ID
        return parentAncestors.equals("0")
            ? "0," + parentDeptId // 根节点后直接拼接一级部门
            : parentAncestors + "," + parentDeptId; // 多级部门拼接
    }

    /**
     * 处理用户数据
     */
    public static List<SysUser> userExtracted() {
        List<SysUser> sysUserList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 从文件读取JSON数据
            List<user> users = objectMapper.readValue(
                new File("C:\\Users\\admin\\Desktop\\维修管理系统\\人员信息.json"),
                new TypeReference<List<user>>(){}
            );
            // 打印解析结果
            System.out.println("共解析出 " + users.size() + " 条人员信息");
            System.out.println("----------------------------------");

            for (user user : users) {
                SysUser sysUser = new SysUser();
                sysUser.setDeptId(Long.valueOf(user.getGroupNo()));
                sysUser.setUserName(user.getEmpNo());
                sysUser.setNickName(user.getEmpName());
                sysUser.setStatus(user.getStatusName().equals("在职") ? UserStatus.OK.getCode() : UserStatus.DISABLE.getCode());
                sysUser.setPassword(BCrypt.hashpw(user.getEmpNo()));
                sysUserList.add(sysUser);
            }
            return sysUserList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sysUserList;
    }
}
