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

import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.system.domain.approval.ApprovalInstance;
import com.sundot.airport.system.domain.approval.ApprovalTask;
import com.sundot.airport.system.domain.approval.ApprovalCc;
import com.sundot.airport.system.domain.approval.ApprovalHistory;
import com.sundot.airport.system.mapper.approval.ApprovalTaskMapper;
import com.sundot.airport.system.mapper.approval.ApprovalCcMapper;
import com.sundot.airport.system.mapper.approval.ApprovalHistoryMapper;
import com.sundot.airport.system.mapper.approval.ApprovalInstanceMapper;
import com.sundot.airport.system.service.approval.IApprovalEngineService;
import com.sundot.airport.system.service.approval.ICheckApprovalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 审批检查服务实现类
 *
 * @author Simon Lin
 */
@Service
public class CheckApprovalServiceImpl implements ICheckApprovalService {

    private static final Logger logger = LoggerFactory.getLogger(CheckApprovalServiceImpl.class);

    @Autowired
    private IApprovalEngineService approvalEngineService;

    @Autowired
    private ApprovalTaskMapper approvalTaskMapper;

    @Autowired
    private ApprovalCcMapper approvalCcMapper;

    @Autowired
    private ApprovalHistoryMapper approvalHistoryMapper;

    @Autowired
    private ApprovalInstanceMapper approvalInstanceMapper;

    @Override
    public ApprovalInstance submitPersonalCheck(Map<String, Object> requestData, Long userId, String username, String remark) throws Exception {
        // 提取系统控制参数
        String checkType = (String) requestData.get("checkType");
        String location = (String) requestData.get("location");

        // 新的参数：问题人ID和审批科长ID
        Object problemUserIdObj = requestData.get("problemUserId");
        Object sectionLeaderIdObj = requestData.get("sectionLeaderId");
        Object businessIdObj = requestData.get("businessId");

        if (businessIdObj == null) {
            throw new Exception("businessId参数不能为空");
        }
        if (problemUserIdObj == null) {
            throw new Exception("problemUserId参数不能为空");
        }
        if (sectionLeaderIdObj == null) {
            throw new Exception("sectionLeaderId参数不能为空");
        }

        // 转换参数类型
        Long businessId = null;
        if (businessIdObj instanceof Number) {
            businessId = ((Number) businessIdObj).longValue();
        } else if (businessIdObj instanceof String) {
            businessId = Long.parseLong((String) businessIdObj);
        }

        Long problemUserId = null;
        if (problemUserIdObj instanceof Number) {
            problemUserId = ((Number) problemUserIdObj).longValue();
        } else if (problemUserIdObj instanceof String) {
            problemUserId = Long.parseLong((String) problemUserIdObj);
        }

        Long sectionLeaderId = null;
        if (sectionLeaderIdObj instanceof Number) {
            sectionLeaderId = ((Number) sectionLeaderIdObj).longValue();
        } else if (sectionLeaderIdObj instanceof String) {
            sectionLeaderId = Long.parseLong((String) sectionLeaderIdObj);
        }

        // 提取用户表单数据
        Map<String, Object> userFormData = (Map<String, Object>) requestData.get("formData");
        if (userFormData == null) {
            userFormData = new HashMap<>();
        }

        Map<String, Object> params = new HashMap<>();
        params.put("businessType", "PERSONAL_CHECK");
        params.put("businessId", businessId);
        params.put("title", "个人级别检查");
        params.put("checkType", checkType);
        params.put("location", location);
        params.put("problemUserId", problemUserId);
        params.put("sectionLeaderId", sectionLeaderId);

        // 组装最终的表单数据（保留用户填写的所有字段）
        Map<String, Object> formData = new HashMap<>(userFormData);
        params.put("formData", formData);

        // 业务数据（用于系统控制）
        Map<String, Object> businessData = new HashMap<>();
        businessData.put("checkType", checkType);
        businessData.put("location", location);
        businessData.put("problemUserId", problemUserId);
        businessData.put("sectionLeaderId", sectionLeaderId);
        businessData.put("initiatorId", userId); // 发起人ID，用于最后的审批环节
        params.put("businessData", businessData);

        return approvalEngineService.startPersonalLevelProcess(
                (String) params.get("businessType"),
                (Long) params.get("businessId"),
                (String) params.get("title"),
                userId,
                username,
                sectionLeaderId, // 第一个审批节点分配给科长
                formData,
                businessData
        );
    }

    @Override
    public ApprovalInstance submitSectionCheck(Map<String, Object> requestData, Long userId, String username, String remark) throws Exception {
        // 提取系统控制参数
        String checkType = (String) requestData.get("checkType");
        String severity = (String) requestData.get("severity");
        Object targetDeptIdObj = requestData.get("targetDeptId");
        Object sectionLeaderIdObj = requestData.get("sectionLeaderId");
        Object businessIdObj = requestData.get("businessId");

        if (businessIdObj == null) {
            throw new Exception("businessId参数不能为空");
        }

        Long businessId = null;
        if (businessIdObj instanceof Number) {
            businessId = ((Number) businessIdObj).longValue();
        } else if (businessIdObj instanceof String) {
            businessId = Long.parseLong((String) businessIdObj);
        }

        // 提取用户表单数据
        Map<String, Object> userFormData = (Map<String, Object>) requestData.get("formData");
        if (userFormData == null) {
            userFormData = new HashMap<>();
        }

        Long targetDeptId = null;
        if (targetDeptIdObj != null) {
            if (targetDeptIdObj instanceof Number) {
                targetDeptId = ((Number) targetDeptIdObj).longValue();
            } else if (targetDeptIdObj instanceof String) {
                targetDeptId = Long.parseLong((String) targetDeptIdObj);
            }
        }

        Long sectionLeaderId = null;
        if (sectionLeaderIdObj != null) {
            if (sectionLeaderIdObj instanceof Number) {
                sectionLeaderId = ((Number) sectionLeaderIdObj).longValue();
            } else if (sectionLeaderIdObj instanceof String) {
                sectionLeaderId = Long.parseLong((String) sectionLeaderIdObj);
            }
        }

        if (sectionLeaderId == null) {
            throw new Exception("sectionLeaderId参数不能为空");
        }

        // 生成业务ID
        //Long businessId = System.currentTimeMillis();

        Map<String, Object> params = new HashMap<>();
        params.put("businessType", "DEPARTMENT_CHECK");
        params.put("businessId", businessId);
        params.put("title", "被检查级别为主管级检查");
        params.put("checkType", checkType);
        params.put("severity", severity);
        params.put("targetDeptId", targetDeptId);

        // 组装最终的表单数据
        Map<String, Object> formData = new HashMap<>(userFormData);
        params.put("formData", formData);

        // 业务数据
        Map<String, Object> businessData = new HashMap<>();
        businessData.put("checkType", checkType);
        businessData.put("severity", severity);
        businessData.put("targetDeptId", targetDeptId);
        businessData.put("sectionLeaderId", sectionLeaderId);
        params.put("businessData", businessData);

        return approvalEngineService.startSectionLevelProcess(
                (String) params.get("businessType"),
                (Long) params.get("businessId"),
                (String) params.get("title"),
                userId,
                username,
                sectionLeaderId,
                formData,
                businessData
        );
    }

    @Override
    public ApprovalInstance submitBrigadeCheck(Map<String, Object> requestData, Long userId, String username, String remark) throws Exception {
        // 提取系统控制参数
        String checkType = (String) requestData.get("checkType");
        String severity = (String) requestData.get("severity");
        Object targetDeptIdObj = requestData.get("targetDeptId");
        Object sectionLeaderIdObj = requestData.get("sectionLeaderId");
        Object businessIdObj = requestData.get("businessId");
        Map<String, Object> userFormData = (Map<String, Object>) requestData.get("formData");

        if (businessIdObj == null) {
            throw new ServiceException("businessId参数不能为空");
        }

        if (targetDeptIdObj == null) {
            throw new ServiceException("targetDeptId参数不能为空");
        }

        if (sectionLeaderIdObj == null) {
            throw new ServiceException("sectionLeaderId参数不能为空");
        }

        if (userFormData == null) {
            throw new ServiceException("formData参数不能为空");
        }

        Long businessId = null;
        if (businessIdObj instanceof Number) {
            businessId = ((Number) businessIdObj).longValue();
        } else if (businessIdObj instanceof String) {
            businessId = Long.parseLong((String) businessIdObj);
        }

        Long targetDeptId = null;
        if (targetDeptIdObj instanceof Number) {
            targetDeptId = ((Number) targetDeptIdObj).longValue();
        } else if (targetDeptIdObj instanceof String) {
            targetDeptId = Long.parseLong((String) targetDeptIdObj);
        }

        Long sectionLeaderId = null;
        if (sectionLeaderIdObj instanceof Number) {
            sectionLeaderId = ((Number) sectionLeaderIdObj).longValue();
        } else if (sectionLeaderIdObj instanceof String) {
            sectionLeaderId = Long.parseLong((String) sectionLeaderIdObj);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("businessType", "BRIGADE_CHECK");
        params.put("businessId", businessId);
        params.put("title", "被检查级别为大队级检查");
        params.put("checkType", checkType);
        params.put("severity", severity);
        params.put("targetDeptId", targetDeptId);
        params.put("sectionLeaderId", sectionLeaderId);

        // 组装最终的表单数据
        Map<String, Object> formData = new HashMap<>(userFormData);
        params.put("formData", formData);

        // 业务数据
        Map<String, Object> businessData = new HashMap<>();
        businessData.put("checkType", checkType);
        businessData.put("severity", severity);
        businessData.put("targetDeptId", targetDeptId);
        businessData.put("sectionLeaderId", sectionLeaderId);
        businessData.put("initiatorId", userId);
        params.put("businessData", businessData);

        return approvalEngineService.startBrigadeLevelProcess(
                (String) params.get("businessType"),
                (Long) params.get("businessId"),
                (String) params.get("title"),
                userId,
                username,
                sectionLeaderId,
                formData,
                businessData
        );
    }

    @Override
    public ApprovalInstance submitGroupCheck(Map<String, Object> requestData, Long userId, String username, String remark) throws Exception {
        // 提取系统控制参数
        String checkType = (String) requestData.get("checkType");
        String severity = (String) requestData.get("severity");
        Object groupLeaderIdObj = requestData.get("groupLeaderId");
        Object businessIdObj = requestData.get("businessId");

        if (businessIdObj == null) {
            throw new Exception("businessId参数不能为空");
        }

        Long businessId = null;
        if (businessIdObj instanceof Number) {
            businessId = ((Number) businessIdObj).longValue();
        } else if (businessIdObj instanceof String) {
            businessId = Long.parseLong((String) businessIdObj);
        }

        // 提取用户表单数据
        Map<String, Object> userFormData = (Map<String, Object>) requestData.get("formData");
        if (userFormData == null) {
            userFormData = new HashMap<>();
        }

        Long groupLeaderId = null;
        if (groupLeaderIdObj != null) {
            if (groupLeaderIdObj instanceof Number) {
                groupLeaderId = ((Number) groupLeaderIdObj).longValue();
            } else if (groupLeaderIdObj instanceof String) {
                groupLeaderId = Long.parseLong((String) groupLeaderIdObj);
            }
        }

        if (groupLeaderId == null) {
            throw new Exception("groupLeaderId参数不能为空");
        }

        // 生成业务ID
        //Long businessId = System.currentTimeMillis();

        Map<String, Object> params = new HashMap<>();
        params.put("businessType", "GROUP_CHECK");
        params.put("businessId", businessId);
        params.put("title", "班组级检查");
        params.put("checkType", checkType);
        params.put("severity", severity);
        params.put("groupLeaderId", groupLeaderId);

        // 组装表单数据
        Map<String, Object> formData = new HashMap<>(userFormData);
        params.put("formData", formData);

        // 业务数据
        Map<String, Object> businessData = new HashMap<>();
        businessData.put("checkType", checkType);
        businessData.put("severity", severity);
        businessData.put("groupLeaderId", groupLeaderId);
        params.put("businessData", businessData);

        return approvalEngineService.startGroupLevelProcess(
                (String) params.get("businessType"),
                (Long) params.get("businessId"),
                (String) params.get("title"),
                userId,
                username,
                formData,
                businessData
        );
    }

    @Override
    public ApprovalInstance submitSeizureReport(Map<String, Object> requestData, Long userId, String username, String remark) throws Exception {
        // 提取系统控制参数
        Object seizureTimeObj = requestData.get("seizureTime");
        String passengerInfo = (String) requestData.get("passengerInfo");
        String submitterRole = (String) requestData.get("submitterRole");
        Object businessIdObj = requestData.get("businessId");

        if (businessIdObj == null) {
            throw new Exception("businessId参数不能为空");
        }

        Long businessId = null;
        if (businessIdObj instanceof Number) {
            businessId = ((Number) businessIdObj).longValue();
        } else if (businessIdObj instanceof String) {
            businessId = Long.parseLong((String) businessIdObj);
        }

        // 提取用户表单数据
        Map<String, Object> userFormData = (Map<String, Object>) requestData.get("formData");
        if (userFormData == null) {
            userFormData = new HashMap<>();
        }

        // 处理查获时间
        Date seizureTime = null;
        if (seizureTimeObj != null) {
            if (seizureTimeObj instanceof Date) {
                seizureTime = (Date) seizureTimeObj;
            } else if (seizureTimeObj instanceof String) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    seizureTime = sdf.parse((String) seizureTimeObj);
                } catch (ParseException e) {
                    logger.warn("解析查获时间失败: {}", seizureTimeObj);
                }
            }
        }

        // 生成业务ID
        //Long businessId = System.currentTimeMillis();

        Map<String, Object> params = new HashMap<>();
        params.put("businessType", "SEIZURE_REPORT");
        params.put("businessId", businessId);
        params.put("title", "查获物品上报");
        params.put("submitterRole", submitterRole);

        // 组装表单数据
        Map<String, Object> formData = new HashMap<>(userFormData);
        params.put("formData", formData);

        // 业务数据
        Map<String, Object> businessData = new HashMap<>();
        if (seizureTime != null) {
            businessData.put("seizureTime", seizureTime);
        }
        if (passengerInfo != null) {
            businessData.put("passengerInfo", passengerInfo);
        }
        params.put("businessData", businessData);

        return approvalEngineService.startSeizureReportProcess(
                (String) params.get("businessType"),
                (Long) params.get("businessId"),
                (String) params.get("title"),
                userId,
                username,
                submitterRole,
                formData,
                businessData
        );
    }

    @Override
    public ApprovalTask approveTask(Long taskId, String comment, Map<String, Object> formData, Long userId, String username) throws Exception {
        if (formData == null) {
            formData = new HashMap<>();
        }

        Map<String, Object> params = new HashMap<>();
        params.put("comment", comment);

        boolean success = approvalEngineService.approveTask(taskId, userId, username, comment, formData);
        if (success) {
            // 获取更新后的任务信息
            return approvalTaskMapper.selectApprovalTaskById(taskId);
        } else {
            throw new Exception("审批任务失败");
        }
    }

    @Override
    public ApprovalTask rejectTask(Long taskId, String comment, Long userId, String username) throws Exception {
        boolean success = approvalEngineService.rejectTask(taskId, userId, username, comment);
        if (success) {
            // 获取更新后的任务信息
            return approvalTaskMapper.selectApprovalTaskById(taskId);
        } else {
            throw new Exception("驳回任务失败");
        }
    }

    @Override
    public List<ApprovalTask> getPendingTasks(Long userId) throws Exception {
        return approvalEngineService.getUserPendingTasks(userId);
    }

    @Override
    public List<ApprovalTask> getCompletedTasks(Long userId) throws Exception {
        return approvalEngineService.getUserCompletedTasks(userId);
    }

    @Override
    public List<ApprovalInstance> getSubmittedInstances(Long userId, String status) throws Exception {
        return approvalEngineService.getUserSubmittedInstances(userId, status);
    }

    @Override
    public Long getPendingTaskCount(Long userId) throws Exception {
        List<ApprovalTask> tasks = approvalEngineService.getUserPendingTasks(userId);
        return (long) tasks.size();
    }

    @Override
    public List<com.sundot.airport.system.domain.approval.dto.ApprovalCcDetailDTO> getCcDetailsByUserId(Long userId) throws Exception {
        // 1. 获取用户抄送记录（关联实例信息） - 这个查询会被PageHelper拦截进行分页
        List<ApprovalCc> ccList = approvalCcMapper.selectCcDetailsByUserId(userId);

        // 2. 转换为DTO并获取历史记录
        List<com.sundot.airport.system.domain.approval.dto.ApprovalCcDetailDTO> resultList = new ArrayList<>();

        for (ApprovalCc cc : ccList) {
            com.sundot.airport.system.domain.approval.dto.ApprovalCcDetailDTO dto =
                    new com.sundot.airport.system.domain.approval.dto.ApprovalCcDetailDTO();

            // 设置抄送信息
            dto.setCcId(cc.getId());
            dto.setInstanceId(cc.getInstanceId());
            dto.setCcTime(cc.getCcTime());
            dto.setIsRead(cc.getIsRead());
            dto.setReadTime(cc.getReadTime());

            // 设置实例信息
            if (cc.getInstance() != null) {
                dto.setTitle(cc.getInstance().getTitle());
                dto.setCompletionTime(cc.getInstance().getCompletionTime());
                dto.setBusinessId(cc.getInstance().getBusinessId());
                dto.setBusinessType(cc.getInstance().getBusinessType());
                dto.setFormData(cc.getInstance().getFormData());
            }

            // 获取历史记录
            List<ApprovalHistory> historyList = approvalHistoryMapper.selectApprovalHistoryByInstanceId(cc.getInstanceId());
            List<com.sundot.airport.system.domain.approval.dto.ApprovalCcDetailDTO.ApprovalHistoryDetailDTO> historyDetailList =
                    new ArrayList<>();

            for (ApprovalHistory history : historyList) {
                com.sundot.airport.system.domain.approval.dto.ApprovalCcDetailDTO.ApprovalHistoryDetailDTO historyDto =
                        new com.sundot.airport.system.domain.approval.dto.ApprovalCcDetailDTO.ApprovalHistoryDetailDTO();

                historyDto.setNodeName(history.getNodeName());
                historyDto.setOperatorName(history.getOperatorName());
                historyDto.setOperationTime(history.getOperationTime());
                historyDto.setComment(history.getComment());

                historyDetailList.add(historyDto);
            }

            dto.setHistoryList(historyDetailList);
            resultList.add(dto);
        }

        // 3. 创建一个新的具有分页信息的列表，用于让PageInfo获取正确的分页信息
        // 我们需要将ccList的分页信息传递给resultList
        if (ccList instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<ApprovalCc> pagedCcList = (com.github.pagehelper.Page<ApprovalCc>) ccList;
            com.github.pagehelper.Page<com.sundot.airport.system.domain.approval.dto.ApprovalCcDetailDTO> pagedResultList =
                    new com.github.pagehelper.Page<>(pagedCcList.getPageNum(), pagedCcList.getPageSize());
            pagedResultList.setTotal(pagedCcList.getTotal());
            pagedResultList.addAll(resultList);
            return pagedResultList;
        }

        return resultList;
    }

    @Override
    public List<ApprovalHistory> getApprovalHistoryByInstanceId(Long instanceId) throws Exception {
        try {
            List<ApprovalHistory> historyList = approvalHistoryMapper.selectApprovalHistoryByInstanceId(instanceId);

            // 检查审批实例是否完成
            ApprovalInstance instance = approvalInstanceMapper.selectApprovalInstanceById(instanceId);
            if (instance != null && !"COMPLETED".equals(instance.getStatus()) && !"REJECTED".equals(instance.getStatus()) && !"CANCELLED".equals(instance.getStatus())) {
                // 审批未完成，查找待办任务
                ApprovalTask pendingTask = new ApprovalTask();
                pendingTask.setInstanceId(instanceId);
                pendingTask.setStatus("PENDING");
                List<ApprovalTask> pendingTasks = approvalTaskMapper.selectApprovalTaskList(pendingTask);

                if (!pendingTasks.isEmpty()) {
                    // 将待办任务转换为审批历史记录格式并添加到列表末尾
                    ApprovalTask task = pendingTasks.get(0); // 通常只有一个当前待办任务
                    ApprovalHistory pendingHistory = new ApprovalHistory();
                    pendingHistory.setInstanceId(task.getInstanceId());
                    pendingHistory.setTaskId(task.getId());
                    pendingHistory.setNodeId(task.getNodeId());
                    pendingHistory.setNodeName(task.getTaskName());
                    pendingHistory.setAction("PENDING"); // 标记为待办
                    pendingHistory.setOperatorId(task.getAssigneeId());
                    pendingHistory.setOperatorName(task.getAssigneeName());
                    pendingHistory.setOperationTime(task.getAssignTime());
                    pendingHistory.setComment("待处理");
                    pendingHistory.setFormData(task.getFormData());

                    historyList.add(pendingHistory);
                }
            }

            return historyList;
        } catch (Exception e) {
            throw new Exception("根据实例ID查询审批历史失败：" + e.getMessage(), e);
        }
    }

    @Override
    public List<ApprovalHistory> getApprovalHistoryByTaskId(Long taskId) throws Exception {
        try {
            return approvalHistoryMapper.selectApprovalHistoryByTaskId(taskId);
        } catch (Exception e) {
            throw new Exception("根据任务ID查询审批历史失败：" + e.getMessage(), e);
        }
    }

    @Override
    public List<ApprovalHistory> getUserApprovalHistory(Long userId, String action) throws Exception {
        try {
            return approvalHistoryMapper.selectApprovalHistoryByOperator(userId, action);
        } catch (Exception e) {
            throw new Exception("查询用户审批历史失败：" + e.getMessage(), e);
        }
    }

    @Override
    public int batchUpdateCcReadStatus(List<Long> ids) throws Exception {
        try {
            if (ids == null || ids.isEmpty()) {
                return 0;
            }
            return approvalCcMapper.batchUpdateReadStatus(ids);
        } catch (Exception e) {
            throw new Exception("批量更新抄送已读状态失败：" + e.getMessage(), e);
        }
    }
}