package com.aegis.emergency.alert.service.impl;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aegis.common.exception.ServiceException;
import com.aegis.common.utils.SecurityUtils;
import com.aegis.common.utils.StringUtils;
import com.aegis.emergency.alert.constant.AlertLogAction;
import com.aegis.emergency.alert.constant.AlertStatus;
import com.aegis.emergency.alert.constant.AlertTransferStatus;
import com.aegis.emergency.alert.domain.DutyAlert;
import com.aegis.emergency.alert.domain.DutyAlertTransfer;
import com.aegis.emergency.alert.mapper.DutyAlertTransferMapper;
import com.aegis.emergency.alert.service.DutyAlertLogService;
import com.aegis.emergency.alert.service.DutyAlertService;
import com.aegis.emergency.alert.service.DutyAlertTransferService;

/**
 * 转警记录 Service 实现
 *
 * 负责处理转警申请、审核、反馈以及状态流转等业务逻辑。
 *
 * @author aegis
 */
@Service
public class DutyAlertTransferServiceImpl extends ServiceImpl<DutyAlertTransferMapper, DutyAlertTransfer> implements DutyAlertTransferService {

    @Autowired
    private DutyAlertService dutyAlertService;

    @Autowired
    private DutyAlertLogService alertLogService;

    /**
     * 根据条件查询转警记录列表
     */
    @Override
    public List<DutyAlertTransfer> listByCondition(DutyAlertTransfer condition) {
        LambdaQueryWrapper<DutyAlertTransfer> wrapper = new LambdaQueryWrapper<>();
        if (condition != null) {
            if (condition.getAlertId() != null) {
                wrapper.eq(DutyAlertTransfer::getAlertId, condition.getAlertId());
            }
            if (StringUtils.isNotEmpty(condition.getStatus())) {
                wrapper.eq(DutyAlertTransfer::getStatus, condition.getStatus());
            }
            if (StringUtils.isNotEmpty(condition.getTargetOrg())) {
                wrapper.like(DutyAlertTransfer::getTargetOrg, condition.getTargetOrg());
            }
            if (condition.getTransferTime() != null) {
                wrapper.ge(DutyAlertTransfer::getTransferTime, condition.getTransferTime());
            }
        }
        wrapper.orderByDesc(DutyAlertTransfer::getTransferTime);
        return list(wrapper);
    }

    /**
     * 根据警情ID获取转警记录（最新一条）
     */
    @Override
    public DutyAlertTransfer getByAlertId(Long alertId) {
        if (alertId == null) {
            throw new ServiceException("警情ID不能为空");
        }
        LambdaQueryWrapper<DutyAlertTransfer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DutyAlertTransfer::getAlertId, alertId)
                .orderByDesc(DutyAlertTransfer::getTransferTime)
                .last("LIMIT 1");
        return getOne(wrapper);
    }

    /**
     * 批量查询转警记录（根据警情ID列表，返回每个警情的最新一条记录）
     */
    @Override
    public Map<Long, DutyAlertTransfer> getLatestByAlertIds(List<Long> alertIds) {
        if (alertIds == null || alertIds.isEmpty()) {
            return Collections.emptyMap();
        }
        
        // 使用 IN 查询，一次性获取所有转警记录
        LambdaQueryWrapper<DutyAlertTransfer> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DutyAlertTransfer::getAlertId, alertIds)
               .orderByDesc(DutyAlertTransfer::getTransferTime);
        
        List<DutyAlertTransfer> allTransfers = list(wrapper);
        
        // 在内存中筛选每个警情的最新一条记录
        Map<Long, DutyAlertTransfer> result = new HashMap<>();
        for (DutyAlertTransfer transfer : allTransfers) {
            Long alertId = transfer.getAlertId();
            // 如果该警情还没有记录，或者当前记录更新，则更新
            if (!result.containsKey(alertId) || 
                (transfer.getTransferTime() != null && 
                 result.get(alertId).getTransferTime() != null &&
                 transfer.getTransferTime().after(result.get(alertId).getTransferTime()))) {
                result.put(alertId, transfer);
            }
        }
        
        return result;
    }

    /**
     * 提交转警申请
     */
    @Override
    @Transactional
    public boolean applyTransfer(DutyAlertTransfer transfer) {
        if (transfer == null) {
            throw new ServiceException("转警信息不能为空");
        }
        if (transfer.getAlertId() == null) {
            throw new ServiceException("警情ID不能为空");
        }
        if (StringUtils.isBlank(transfer.getTargetOrg())) {
            throw new ServiceException("目标单位不能为空");
        }
        if (StringUtils.isBlank(transfer.getContact())) {
            throw new ServiceException("联系人不能为空");
        }
        if (StringUtils.isBlank(transfer.getMobile())) {
            throw new ServiceException("联系电话不能为空");
        }

        // 验证警情是否存在
        DutyAlert alert = dutyAlertService.getById(transfer.getAlertId());
        if (alert == null) {
            throw new ServiceException("警情不存在或已删除");
        }

        // 检查是否已经存在该警情的转警记录
        DutyAlertTransfer existingTransfer = getByAlertId(transfer.getAlertId());
        if (existingTransfer != null) {
            AlertTransferStatus existingStatus = AlertTransferStatus.fromCode(existingTransfer.getStatus());
            // 如果已存在且状态不是 rejected，不允许重复申请
            if (existingStatus != null && existingStatus != AlertTransferStatus.REJECTED) {
                throw new ServiceException("该警情已存在转警申请，无法重复提交");
            }
            // 如果已存在且状态是 rejected，更新现有记录
            if (existingStatus != null && existingStatus == AlertTransferStatus.REJECTED) {
                String operator = SecurityUtils.getUsername();
                
                // 更新现有记录
                existingTransfer.setTargetOrg(transfer.getTargetOrg());
                existingTransfer.setContact(transfer.getContact());
                existingTransfer.setMobile(transfer.getMobile());
                existingTransfer.setTransferDesc(transfer.getTransferDesc());
                existingTransfer.setTransferTime(transfer.getTransferTime() != null ? transfer.getTransferTime() : new Date());
                existingTransfer.setStatus(AlertTransferStatus.PENDING_REVIEW.getCode());
                existingTransfer.setUpdateBy(operator);
                existingTransfer.setUpdateTime(new Date());
                
                if (!super.updateById(existingTransfer)) {
                    return false;
                }
                
                alertLogService.recordLog(transfer.getAlertId(), AlertLogAction.TRANSFER_APPLY, existingTransfer);
                
                // 更新警情状态 -> 已转警
                alert.setStatus(AlertStatus.TRANSFERRED.getCode());
                alert.setUpdateBy(operator);
                alert.setUpdateTime(new Date());
                boolean updated = dutyAlertService.updateById(alert);
                if (updated) {
                    alertLogService.recordLog(transfer.getAlertId(), AlertLogAction.ALERT_TRANSFERRED, alert);
                }
                
                return true;
            }
        }

        // 初始化默认字段
        String operator = SecurityUtils.getUsername();
        transfer.setCreateBy(operator);
        transfer.setCreateTime(new Date());
        transfer.setUpdateBy(operator);
        transfer.setUpdateTime(new Date());
        if (transfer.getTransferTime() == null) {
            transfer.setTransferTime(new Date());
        }
        transfer.setStatus(AlertTransferStatus.PENDING_REVIEW.getCode());

        if (!super.save(transfer)) {
            return false;
        }

        alertLogService.recordLog(transfer.getAlertId(), AlertLogAction.TRANSFER_APPLY, transfer);

        // 更新警情状态 -> 已转警
        alert.setStatus(AlertStatus.TRANSFERRED.getCode());
        alert.setUpdateBy(operator);
        alert.setUpdateTime(new Date());
        boolean updated = dutyAlertService.updateById(alert);
        
        // 记录状态变更日志
        if (updated) {
            alertLogService.recordLog(transfer.getAlertId(), AlertLogAction.ALERT_TRANSFERRED, alert);
        }

        return true;
    }

    /**
     * 审批通过转警申请
     */
    @Override
    @Transactional
    public boolean approveTransfer(Long transferId, String reviewComment) {
        DutyAlertTransfer transfer = validateTransferForReview(transferId);

        String operator = SecurityUtils.getUsername();
        transfer.setStatus(AlertTransferStatus.PENDING_FEEDBACK.getCode());
        transfer.setRemark(reviewComment);
        transfer.setUpdateBy(operator);
        transfer.setUpdateTime(new Date());
        // 审批通过时间视作实际转警时间
        transfer.setTransferTime(new Date());
        // TODO integrate with external notification/dispatch systems after approval

        boolean updated = super.updateById(transfer);
        if (updated) {
            alertLogService.recordLog(transfer.getAlertId(), AlertLogAction.TRANSFER_APPROVE, transfer);
        }
        return updated;
    }

    /**
     * 审批驳回转警申请
     */
    @Override
    @Transactional
    public boolean rejectTransfer(Long transferId, String reviewComment) {
        DutyAlertTransfer transfer = validateTransferForReview(transferId);

        String operator = SecurityUtils.getUsername();
        transfer.setStatus(AlertTransferStatus.REJECTED.getCode());
        transfer.setRemark(reviewComment);
        transfer.setUpdateBy(operator);
        transfer.setUpdateTime(new Date());

        boolean updated = super.updateById(transfer);
        if (updated) {
            alertLogService.recordLog(transfer.getAlertId(), AlertLogAction.TRANSFER_REJECT, transfer);
            
            // 审核驳回后，回退警情状态为 received（如果当前状态是 transferred）
            DutyAlert alert = dutyAlertService.getById(transfer.getAlertId());
            if (alert != null && AlertStatus.TRANSFERRED.getCode().equals(alert.getStatus())) {
                alert.setStatus(AlertStatus.RECEIVED.getCode());
                alert.setUpdateBy(operator);
                alert.setUpdateTime(new Date());
                dutyAlertService.updateById(alert);
            }
        }
        return updated;
    }

    /**
     * 记录外部单位反馈（支持多次反馈）
     */
    @Override
    @Transactional
    public boolean recordFeedback(Long transferId, String feedback, Date feedbackTime) {
        DutyAlertTransfer transfer = validateTransferExists(transferId);
        AlertTransferStatus status = AlertTransferStatus.fromCode(transfer.getStatus());
        if (status == null || status == AlertTransferStatus.REJECTED) {
            throw new ServiceException("当前状态不允许登记反馈");
        }
        if (status == AlertTransferStatus.PENDING_REVIEW) {
            throw new ServiceException("转警尚未审核，不能登记反馈");
        }
        // 移除对 FEEDBACK_RECEIVED 和 PROCESSED 状态的限制，允许多次反馈
        // 但 PROCESSED 状态通常表示流程已结束，可以考虑是否允许反馈
        if (status == AlertTransferStatus.PROCESSED) {
            throw new ServiceException("转警已处理完成，无需继续反馈");
        }

        String operator = SecurityUtils.getUsername();
        Date newFeedbackTime = feedbackTime != null ? feedbackTime : new Date();
        
        // 如果已有反馈内容，追加新反馈（带时间戳）
        if (StringUtils.isNotBlank(transfer.getFeedback())) {
            String existingFeedback = transfer.getFeedback();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timestamp = sdf.format(newFeedbackTime);
            transfer.setFeedback(existingFeedback + "\n\n--- " + timestamp + " ---\n" + feedback);
        } else {
        transfer.setFeedback(feedback);
        }
        
        transfer.setFeedbackTime(newFeedbackTime);
        // 如果当前状态是 pending_feedback，更新为 feedback_received
        // 如果已经是 feedback_received，保持状态不变
        if (status == AlertTransferStatus.PENDING_FEEDBACK) {
        transfer.setStatus(AlertTransferStatus.FEEDBACK_RECEIVED.getCode());
        }
        transfer.setUpdateBy(operator);
        transfer.setUpdateTime(new Date());

        boolean updated = super.updateById(transfer);
        if (updated) {
            alertLogService.recordLog(transfer.getAlertId(), AlertLogAction.TRANSFER_FEEDBACK, transfer);
        }
        return updated;
    }

    /**
     * 将转警记录标记为已处理
     */
    @Override
    @Transactional
    public boolean markProcessed(Long transferId, String remark) {
        DutyAlertTransfer transfer = validateTransferExists(transferId);
        AlertTransferStatus status = AlertTransferStatus.fromCode(transfer.getStatus());
        if (status == null || status == AlertTransferStatus.REJECTED) {
            throw new ServiceException("当前状态不允许标记处理完成");
        }
        if (status == AlertTransferStatus.PENDING_REVIEW) {
            throw new ServiceException("转警尚未审核，不能标记处理完成");
        }

        String operator = SecurityUtils.getUsername();
        transfer.setStatus(AlertTransferStatus.PROCESSED.getCode());
        if (StringUtils.isNotBlank(remark)) {
            transfer.setRemark(remark);
        }
        transfer.setUpdateBy(operator);
        transfer.setUpdateTime(new Date());

        boolean updated = super.updateById(transfer);
        if (updated) {
            alertLogService.recordLog(transfer.getAlertId(), AlertLogAction.TRANSFER_PROCESSED, transfer);
        }
        return updated;
    }

    /**
     * 校验转警记录是否存在
     */
    private DutyAlertTransfer validateTransferExists(Long transferId) {
        if (transferId == null) {
            throw new ServiceException("转警记录ID不能为空");
        }
        DutyAlertTransfer transfer = super.getById(transferId);
        if (transfer == null) {
            throw new ServiceException("转警记录不存在");
        }
        return transfer;
    }

    /**
     * 校验转警记录并确保处于可审核状态
     */
    private DutyAlertTransfer validateTransferForReview(Long transferId) {
        DutyAlertTransfer transfer = validateTransferExists(transferId);
        if (!AlertTransferStatus.PENDING_REVIEW.getCode().equals(transfer.getStatus())) {
            throw new ServiceException("该转警记录已处理，无法重复审核");
        }
        return transfer;
    }
}