package com.zksy.dispatch.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.collection.CollUtil;
import com.zksy.dispatch.domain.DisEventTransfer;
import com.zksy.dispatch.domain.DisEventTransferLog;
import com.zksy.dispatch.domain.DisEventVerify;
import com.zksy.dispatch.dto.EventReportDTO;
import com.zksy.dispatch.dto.EventTransferPageInDTO;
import com.zksy.dispatch.mapper.DisEventTransferLogMapper;
import com.zksy.dispatch.mapper.DisEventTransferMapper;
import com.zksy.dispatch.mapper.DisEventVerifyMapper;
import com.zksy.dispatch.service.DisEventTransferService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class DisEventTransferServiceImpl extends ServiceImpl<DisEventTransferMapper, DisEventTransfer>
        implements DisEventTransferService {

    @Autowired
    private DisEventTransferLogMapper transferLogMapper;

    @Autowired
    private DisEventVerifyMapper verifyMapper;

    @Override
    public Page<DisEventTransfer> findByPage(EventTransferPageInDTO dto) {
        Page<DisEventTransfer> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<DisEventTransfer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(dto.getEventNo()), DisEventTransfer::getEventNo, dto.getEventNo());
        wrapper.eq(StrUtil.isNotBlank(dto.getCategory()), DisEventTransfer::getCategory, dto.getCategory());
        wrapper.eq(StrUtil.isNotBlank(dto.getLevel()), DisEventTransfer::getLevel, dto.getLevel());
        wrapper.eq(StrUtil.isNotBlank(dto.getStatus()), DisEventTransfer::getStatus, dto.getStatus());
        wrapper.eq(StrUtil.isNotBlank(dto.getTransferDept()), DisEventTransfer::getTransferDept, dto.getTransferDept());
        if (StrUtil.isNotBlank(dto.getBeginTime()) && StrUtil.isNotBlank(dto.getEndTime())) {
            wrapper.between(DisEventTransfer::getCreateTime,
                    LocalDateTime.parse(dto.getBeginTime()),
                    LocalDateTime.parse(dto.getEndTime()));
        }
        wrapper.orderByDesc(DisEventTransfer::getCreateTime);
        Page<DisEventTransfer> result = this.page(page, wrapper);

        // 批量查询关联的核实记录，回填接报编号（原JB事件编号）
        if (CollUtil.isNotEmpty(result.getRecords())) {
            List<Long> verifyIds = result.getRecords().stream()
                    .map(DisEventTransfer::getVerifyId)
                    .filter(id -> id != null)
                    .distinct()
                    .collect(java.util.stream.Collectors.toList());
            if (!verifyIds.isEmpty()) {
                List<DisEventVerify> verifies = verifyMapper.selectBatchIds(verifyIds);
                java.util.Map<Long, String> verifyEventNoMap = verifies.stream()
                        .collect(java.util.stream.Collectors.toMap(DisEventVerify::getId, DisEventVerify::getEventNo, (a, b) -> a));
                for (DisEventTransfer t : result.getRecords()) {
                    if (t.getVerifyId() != null) {
                        t.setReportEventNo(verifyEventNoMap.get(t.getVerifyId()));
                    }
                }
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean doTransfer(DisEventTransfer entity) {
        if (entity.getId() == null) {
            log.warn("转接记录ID为空");
            return false;
        }
        DisEventTransfer existing = this.getById(entity.getId());
        if (existing == null) {
            log.warn("转接记录不存在: id={}", entity.getId());
            return false;
        }
        existing.setTransferDept(entity.getTransferDept());
        existing.setTransferRemark(entity.getTransferRemark());
        existing.setTransferTime(LocalDateTime.now());
        existing.setStatus("已转接");
        existing.setOperator(entity.getOperator());
        existing.setUpdateTime(LocalDateTime.now());
        this.updateById(existing);

        DisEventTransferLog logEntity = new DisEventTransferLog();
        logEntity.setTransferId(existing.getId());
        logEntity.setEventNo(existing.getEventNo());
        logEntity.setActionType("转接");
        logEntity.setActionTarget(entity.getTransferDept());
        logEntity.setContent("转接至: " + entity.getTransferDept());
        logEntity.setType("warning");
        logEntity.setActionTime(LocalDateTime.now());
        logEntity.setCreateTime(LocalDateTime.now());
        transferLogMapper.insert(logEntity);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean doReport(EventReportDTO dto) {
        DisEventTransfer existing = this.getById(dto.getId());
        if (existing == null) {
            log.warn("转接记录不存在: id={}", dto.getId());
            return false;
        }
        String reportTargets = dto.getReportTargets() != null
                ? String.join("、", dto.getReportTargets()) : "";
        existing.setReportTargets(reportTargets);
        existing.setStatus("已报送");
        existing.setUpdateTime(LocalDateTime.now());

        if (CollUtil.isNotEmpty(dto.getAttachments())) {
            String paths = dto.getAttachments().stream()
                    .map(a -> a.getFileName() + "|" + a.getUrl())
                    .reduce((a, b) -> a + "," + b).orElse("");
            existing.setAttachPaths(paths);
        }

        this.updateById(existing);

        DisEventTransferLog logEntity = new DisEventTransferLog();
        logEntity.setTransferId(existing.getId());
        logEntity.setEventNo(existing.getEventNo());
        logEntity.setActionType("报送");
        logEntity.setActionTarget(reportTargets);
        logEntity.setContent("报送至: " + reportTargets);
        logEntity.setType("danger");
        logEntity.setActionTime(LocalDateTime.now());
        logEntity.setCreateTime(LocalDateTime.now());
        transferLogMapper.insert(logEntity);
        return true;
    }

    @Override
    public List<DisEventTransferLog> getTransferLogs(Long transferId) {
        LambdaQueryWrapper<DisEventTransferLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DisEventTransferLog::getTransferId, transferId);
        wrapper.orderByDesc(DisEventTransferLog::getActionTime);
        return transferLogMapper.selectList(wrapper);
    }
}
