package com.sundot.airport.system.service.approval.impl;

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

import com.sundot.airport.common.enums.RoleTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.core.domain.entity.SysRole;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.system.mapper.SysUserMapper;
import com.sundot.airport.system.mapper.SysDeptMapper;
import com.sundot.airport.system.mapper.SysRoleMapper;
import com.sundot.airport.system.mapper.approval.ApprovalTaskMapper;
import com.sundot.airport.system.mapper.approval.ApprovalInstanceMapper;
import com.sundot.airport.system.domain.approval.ApprovalTask;
import com.sundot.airport.system.domain.approval.ApprovalInstance;
import com.sundot.airport.system.service.approval.IApprovalUserService;

/**
 * 审批流程用户服务实现
 *
 * @author simon lin
 * @date 2025-09-06
 */
@Service
public class ApprovalUserServiceImpl implements IApprovalUserService {
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ApprovalTaskMapper taskMapper;

    @Autowired
    private ApprovalInstanceMapper instanceMapper;

    /**
     * 根据审批人类型获取审批人ID列表
     */
    @Override
    public List<Long> getApproverIds(String approverType, String approverValue, Object businessData) {
        switch (approverType) {
            case "USER":
                // 指定用户，approverValue为用户ID，多个用逗号分隔
                if (approverValue != null) {
                    List<Long> userIds = new ArrayList<>();
                    String[] userIdStrs = approverValue.split(",");
                    for (String userIdStr : userIdStrs) {
                        try {
                            userIds.add(Long.valueOf(userIdStr.trim()));
                        } catch (NumberFormatException e) {
                            // 忽略格式错误的ID
                        }
                    }
                    return userIds;
                }
                break;

            case "ROLE":
                // 角色，approverValue为角色标识
                return getUserIdsByRoleKey(approverValue);

            case "DEPT":
                // 部门，approverValue为部门ID
                if (approverValue != null) {
                    try {
                        Long deptId = Long.valueOf(approverValue);
                        return getUserIdsByDeptId(deptId);
                    } catch (NumberFormatException e) {
                        // 忽略格式错误的部门ID
                    }
                }
                break;

            case "GROUP_LEADER":
                // 班组长，根据业务数据动态获取
                return getGroupLeaderIdsByBusinessData(businessData);

            case "SECTION_LEADER":
                // 科长，根据业务数据动态获取
                return getSectionLeaderIdsByBusinessData(businessData);

            case "ORIGINAL_OPERATOR":
                // 原始操作者，根据业务数据中的taskId获取
                return getOriginalOperatorIdsByBusinessData(businessData);

            case "DEPT_SECTION_LEADER":
                // 指定部门的科长，根据业务数据中的deptId获取
                return getDeptSectionLeaderIdsByBusinessData(businessData);

            default:
                break;
        }

        return new ArrayList<>();
    }

    /**
     * 根据部门ID获取部门负责人（科长）
     * 如果传入的是班组ID，会自动查找其父部门的科长
     */
    @Override
    public List<Long> getDeptLeaderIds(Long deptId) {
        List<Long> leaderIds = new ArrayList<>();

        if (deptId == null) {
            return leaderIds;
        }

        // 获取传入的部门信息
        SysDept dept = deptMapper.selectDeptById(deptId);
        if (dept == null) {
            return leaderIds;
        }

        // 确定要查找科长的科室ID
        Long sectionDeptId = deptId;

        // 如果当前部门有父部门，说明这是班组，需要找父部门（科室）的科长
        if (dept.getParentId() != null && dept.getParentId() != 100) {
            sectionDeptId = dept.getParentId();
            // 重新获取科室部门信息
            dept = deptMapper.selectDeptById(sectionDeptId);
        }

        if (dept != null) {
            // 方法1: 根据部门负责人姓名查找用户
            if (dept.getLeader() != null && !dept.getLeader().isEmpty()) {
                SysUser leader = userMapper.selectUserByUserName(dept.getLeader());
                if (leader != null) {
                    leaderIds.add(leader.getUserId());
                }
            }

            // 方法2: 根据角色查找科长（在该科室下的科长）
            List<Long> sectionLeaderIds = getUserIdsByRoleKey("kezhang");
            List<SysUser> sectionUsers = userMapper.selectUsersByDeptId(sectionDeptId);

            for (SysUser user : sectionUsers) {
                if (sectionLeaderIds.contains(user.getUserId())) {
                    if (!leaderIds.contains(user.getUserId())) {
                        leaderIds.add(user.getUserId());
                    }
                }
            }
        }

        return leaderIds;
    }

    /**
     * 根据用户ID获取所属部门的科长
     */
    @Override
    public List<Long> getSectionLeaderIdsByUserId(Long userId) {
        SysUser user = userMapper.selectUserById(userId);
        if (user != null && user.getDeptId() != null) {
            return getDeptLeaderIds(user.getDeptId());
        }
        return new ArrayList<>();
    }

    /**
     * 根据用户ID获取所属班组的班组长
     */
    @Override
    public List<Long> getGroupLeaderIdsByUserId(Long userId) {
        List<Long> groupLeaderIds = new ArrayList<>();

        SysUser user = userMapper.selectUserById(userId);
        if (user != null && user.getDeptId() != null) {
            // 获取班组长角色的用户
            List<Long> groupLeaderRoleIds = getUserIdsByRoleKey("banzuzhang");

            // 获取同部门的班组长
            List<SysUser> deptUsers = userMapper.selectUsersByDeptId(user.getDeptId());
            for (SysUser deptUser : deptUsers) {
                if (groupLeaderRoleIds.contains(deptUser.getUserId())) {
                    groupLeaderIds.add(deptUser.getUserId());
                }
            }
        }

        return groupLeaderIds;
    }

    /**
     * 根据角色标识获取用户ID列表
     */
    @Override
    public List<Long> getUserIdsByRoleKey(String roleKey) {
        if (roleKey == null) {
            return new ArrayList<>();
        }

        List<SysUser> users = userMapper.selectUsersByRoleKey(roleKey);
        return users.stream()
                .map(SysUser::getUserId)
                .collect(Collectors.toList());
    }

    /**
     * 根据部门ID获取部门下所有用户ID列表
     */
    @Override
    public List<Long> getUserIdsByDeptId(Long deptId) {
        if (deptId == null) {
            return new ArrayList<>();
        }

        List<SysUser> users = userMapper.selectUsersByDeptId(deptId);
        return users.stream()
                .filter(user -> "0".equals(user.getStatus()) && "0".equals(user.getDelFlag()))
                .map(SysUser::getUserId)
                .collect(Collectors.toList());
    }

    /**
     * 判断用户是否为班组长角色
     */
    @Override
    public boolean isGroupLeader(Long userId) {
        if (userId == null) {
            return false;
        }

        List<Long> groupLeaderIds = getUserIdsByRoleKey("banzuzhang");
        return groupLeaderIds.contains(userId);
    }

    /**
     * 判断用户是否为科长角色
     */
    @Override
    public boolean isSectionLeader(Long userId) {
        if (userId == null) {
            return false;
        }

        List<Long> sectionLeaderIds = getUserIdsByRoleKey("kezhang");
        return sectionLeaderIds.contains(userId);
    }

    /**
     * 根据业务数据动态获取整改班组
     */
    @Override
    public Long getTargetGroupIdFromBusinessData(Object businessData) {
        if (businessData instanceof String) {
            try {
                String businessDataStr = (String) businessData;
                // 简单的JSON解析，查找targetGroupId
                if (businessDataStr.contains("\"targetGroupId\"")) {
                    // 使用正则表达式提取targetGroupId的值
                    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"targetGroupId\"\\s*:\\s*(\\d+)");
                    java.util.regex.Matcher matcher = pattern.matcher(businessDataStr);
                    if (matcher.find()) {
                        return Long.valueOf(matcher.group(1));
                    }
                }
            } catch (Exception e) {
                // 解析失败，返回null
                return null;
            }
        }

        return null;
    }

    /**
     * 根据业务数据获取班组长ID列表
     */
    private List<Long> getGroupLeaderIdsByBusinessData(Object businessData) {
        // 优先检查是否有直接指定的groupLeaderId
        Long groupLeaderId = getGroupLeaderIdFromBusinessData(businessData);
        if (groupLeaderId != null) {
            List<Long> result = new ArrayList<>();
            result.add(groupLeaderId);
            return result;
        }

        Long targetId = null;

        // 尝试从业务数据中获取targetGroupId或targetDeptId
        targetId = getTargetGroupIdFromBusinessData(businessData);
        if (targetId == null) {
            targetId = getTargetDeptIdFromBusinessData(businessData);
        }

        if (targetId != null) {
            // 获取班组长角色的用户
            List<Long> groupLeaderRoleIds = getUserIdsByRoleKey("banzuzhang");

            // 获取目标部门/班组的所有用户
            List<SysUser> groupUsers = userMapper.selectUsersByDeptId(targetId);

            // 找到交集：既在目标部门/班组，又是班组长角色的用户
            List<Long> groupLeaderIds = new ArrayList<>();
            for (SysUser user : groupUsers) {
                if (groupLeaderRoleIds.contains(user.getUserId())) {
                    groupLeaderIds.add(user.getUserId());
                }
            }

            return groupLeaderIds;
        }

        // 如果无法从业务数据中获取，返回空列表
        return new ArrayList<>();
    }

    /**
     * 根据业务数据获取科长ID列表
     */
    private List<Long> getSectionLeaderIdsByBusinessData(Object businessData) {
        // 优先检查是否有直接指定的sectionLeaderId
        Long sectionLeaderId = getSectionLeaderIdFromBusinessData(businessData);
        if (sectionLeaderId != null) {
            List<Long> result = new ArrayList<>();
            result.add(sectionLeaderId);
            return result;
        }

        // 如果没有直接指定的sectionLeaderId，则根据业务数据获取目标部门ID
        Long targetDeptId = getTargetDeptIdFromBusinessData(businessData);

        if (targetDeptId != null) {
            return getDeptLeaderIds(targetDeptId);
        }

        // 如果无法从业务数据中获取，返回空列表
        return new ArrayList<>();
    }

    /**
     * 根据业务数据获取直接指定的班组长ID
     */
    private Long getGroupLeaderIdFromBusinessData(Object businessData) {
        if (businessData instanceof String) {
            try {
                String businessDataStr = (String) businessData;
                // 查找groupLeaderId
                if (businessDataStr.contains("\"groupLeaderId\"")) {
                    // 使用正则表达式提取groupLeaderId的值
                    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"groupLeaderId\"\\s*:\\s*(\\d+)");
                    java.util.regex.Matcher matcher = pattern.matcher(businessDataStr);
                    if (matcher.find()) {
                        return Long.valueOf(matcher.group(1));
                    }
                }
            } catch (Exception e) {
                // 忽略解析错误
            }
        }
        return null;
    }

    /**
     * 根据业务数据获取直接指定的科长ID
     */
    private Long getSectionLeaderIdFromBusinessData(Object businessData) {
        if (businessData instanceof String) {
            try {
                String businessDataStr = (String) businessData;
                // 查找sectionLeaderId
                if (businessDataStr.contains("\"sectionLeaderId\"")) {
                    // 使用正则表达式提取sectionLeaderId的值
                    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"sectionLeaderId\"\\s*:\\s*(\\d+)");
                    java.util.regex.Matcher matcher = pattern.matcher(businessDataStr);
                    if (matcher.find()) {
                        return Long.valueOf(matcher.group(1));
                    }
                }
            } catch (Exception e) {
                // 忽略解析错误
            }
        }
        return null;
    }

    /**
     * 根据业务数据获取目标部门ID
     */
    private Long getTargetDeptIdFromBusinessData(Object businessData) {
        if (businessData instanceof String) {
            try {
                String businessDataStr = (String) businessData;
                // 简单的JSON解析，查找targetDeptId
                if (businessDataStr.contains("\"targetDeptId\"")) {
                    // 使用正则表达式提取targetDeptId的值
                    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"targetDeptId\"\\s*:\\s*(\\d+)");
                    java.util.regex.Matcher matcher = pattern.matcher(businessDataStr);
                    if (matcher.find()) {
                        return Long.valueOf(matcher.group(1));
                    }
                }
            } catch (Exception e) {
                // 解析失败，返回null
                return null;
            }
        }

        return null;
    }

    /**
     * 根据业务数据获取原始操作者ID列表（用于班组长整改完成后回流）
     */
    private List<Long> getOriginalOperatorIdsByBusinessData(Object businessData) {
        List<Long> operatorIds = new ArrayList<>();

        if (businessData instanceof String) {
            try {
                String businessDataStr = (String) businessData;
                // 解析业务数据中的taskId或其他标识
                if (businessDataStr.contains("\"taskId\"")) {
                    // 使用正则表达式提取taskId的值
                    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"taskId\"\\s*:\\s*(\\d+)");
                    java.util.regex.Matcher matcher = pattern.matcher(businessDataStr);
                    if (matcher.find()) {
                        Long taskId = Long.valueOf(matcher.group(1));
                        Long operatorId = getOriginalOperatorByTaskId(taskId);
                        if (operatorId != null) {
                            operatorIds.add(operatorId);
                        }
                    }
                }
            } catch (Exception e) {
                // 解析失败，返回空列表
            }
        }

        return operatorIds;
    }

    /**
     * 根据业务数据获取指定部门的科长ID列表
     */
    private List<Long> getDeptSectionLeaderIdsByBusinessData(Object businessData) {
        List<Long> sectionLeaderIds = new ArrayList<>();

        if (businessData instanceof String) {
            try {
                String businessDataStr = (String) businessData;
                // 解析业务数据中的deptId（如质检科ID：289）
                if (businessDataStr.contains("\"deptId\"")) {
                    // 使用正则表达式提取deptId的值
                    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"deptId\"\\s*:\\s*(\\d+)");
                    java.util.regex.Matcher matcher = pattern.matcher(businessDataStr);
                    if (matcher.find()) {
                        Long deptId = Long.valueOf(matcher.group(1));

                        // 获取指定部门下具有科长角色的用户
                        List<Long> kezhangRoleIds = getUserIdsByRoleKey("kezhang");
                        List<SysUser> deptUsers = userMapper.selectUsersByDeptId(deptId);

                        // 找到交集：既在指定部门，又是科长角色的用户
                        for (SysUser user : deptUsers) {
                            if (kezhangRoleIds.contains(user.getUserId())) {
                                sectionLeaderIds.add(user.getUserId());
                            }
                        }
                    }
                }
            } catch (Exception e) {
                // 解析失败，返回空列表
            }
        }

        return sectionLeaderIds;
    }

    /**
     * 根据任务ID获取原始操作者（创建者或更新者）的用户ID
     */
    @Override
    public Long getOriginalOperatorByTaskId(Long taskId) {
        if (taskId == null) {
            return null;
        }

        // 查找当前任务
        ApprovalTask currentTask = taskMapper.selectApprovalTaskById(taskId);
        if (currentTask == null) {
            return null;
        }

        // 获取同一实例的所有历史任务，按创建时间排序
        List<ApprovalTask> instanceTasks = taskMapper.selectApprovalTaskByInstanceId(currentTask.getInstanceId());

        // 查找最早的科长审批任务（SECTION_LEADER节点）
        for (ApprovalTask task : instanceTasks) {
            if (task.getCreateBy() != null) {
                // 根据create_by字段（用户名）查找用户ID
                SysUser user = userMapper.selectUserByUserName(task.getCreateBy());
                if (user != null && isSectionLeader(user.getUserId())) {
                    return user.getUserId();
                }
            }
        }

        // 如果找不到科长任务，查找实例的提交者（通常提交后会有科长审批）
        if (currentTask.getInstanceId() != null) {
            ApprovalInstance instance = instanceMapper.selectApprovalInstanceById(currentTask.getInstanceId());
            if (instance != null && instance.getSubmitterId() != null) {
                // 查找提交者所属部门的科长
                return getSectionLeaderIdsByUserId(instance.getSubmitterId()).stream().findFirst().orElse(null);
            }
        }

        return null;
    }

    /**
     * 根据任务ID获取任务的创建者或更新者用户ID（用于驳回回流）
     */
    @Override
    public Long getTaskCreatorOrUpdaterByTaskId(Long taskId) {
        if (taskId == null) {
            return null;
        }

        // 查找当前任务
        ApprovalTask currentTask = taskMapper.selectApprovalTaskById(taskId);
        if (currentTask == null) {
            return null;
        }

        // 如果没有更新者，查找create_by（创建者）
        if (currentTask.getCreateBy() != null && !currentTask.getCreateBy().isEmpty()) {
            SysUser user = userMapper.selectUserByUserName(currentTask.getCreateBy());
            if (user != null) {
                return user.getUserId();
            }
        }

        return null;
    }

    /**
     * 根据用户ID查找其直接上级（违禁品审批用）
     * 如果用户是安检员，找其班组长；如果是班组长，找其科长
     */
    @Override
    public List<Long> getDirectSuperiorIds(Long userId) {
        List<Long> superiorIds = new ArrayList<>();

        if (userId == null) {
            return superiorIds;
        }

        // 判断用户角色
        if (isGroupLeader(userId)) {
            // 如果是班组长，找其科长
            List<Long> sectionLeaderIds = getSectionLeaderIdsByUserId(userId);
            superiorIds.addAll(sectionLeaderIds);
        } else {
            // 如果是普通安检员，找其班组长
            List<Long> groupLeaderIds = getGroupLeaderIdsByUserId(userId);
            superiorIds.addAll(groupLeaderIds);
        }

        return superiorIds;
    }

    /**
     * 判断用户是否为安检员角色
     */
    @Override
    public boolean isSecurityCheck(Long userId) {
        if (userId == null) {
            return false;
        }

        List<Long> groupLeaderIds = getUserIdsByRoleKey("SecurityCheck");
        return groupLeaderIds.contains(userId);
    }

    /**
     * 根据用户ID查找其主管（违禁品审批用）
     *
     * @param userId 用户ID
     * @return 主管的用户ID列表
     */
    @Override
    public List<Long> getKeZhangByUserId(Long userId) {
        if (userId == null) {
            return Collections.emptyList();
        }

        if (!isGroupLeader(userId) && !isSecurityCheck(userId)) {
            return Collections.emptyList();
        }

        SysUser user = userMapper.selectUserById(userId);
        List<SysUser> sysUserList = userMapper.selectUserByDeptIdAndRoleKeyList(user.getDept().getParentId(), Collections.singletonList(RoleTypeEnum.kezhang.getCode()));
        return sysUserList.stream().map(SysUser::getUserId).distinct().collect(Collectors.toList());
    }
}