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 com.zksy.dispatch.domain.DisEventTransfer;
import com.zksy.dispatch.domain.DisEventTransferLog;
import com.zksy.dispatch.domain.DisEventVerify;
import com.zksy.dispatch.dto.EventVerifyPageInDTO;
import com.zksy.dispatch.mapper.DisEventTransferLogMapper;
import com.zksy.dispatch.mapper.DisEventTransferMapper;
import com.zksy.dispatch.mapper.DisEventVerifyMapper;
import com.zksy.dispatch.service.DisEventVerifyService;
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.time.format.DateTimeFormatter;

@Slf4j
@Service
public class DisEventVerifyServiceImpl extends ServiceImpl<DisEventVerifyMapper, DisEventVerify>
        implements DisEventVerifyService {

    @Autowired
    private DisEventTransferMapper transferMapper;

    @Autowired
    private DisEventTransferLogMapper transferLogMapper;

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean verify(DisEventVerify entity) {
        if (entity.getId() == null) {
            log.warn("核实记录ID为空");
            return false;
        }
        DisEventVerify existing = this.getById(entity.getId());
        if (existing == null) {
            log.warn("核实记录不存在: id={}", entity.getId());
            return false;
        }
        existing.setCategory(entity.getCategory());
        existing.setLevel(entity.getLevel());
        existing.setIsReal(entity.getIsReal());
        existing.setOpinion(entity.getOpinion());
        existing.setJudgeTime(LocalDateTime.now());
        existing.setVerifier(entity.getVerifier());
        existing.setVerifyTime(LocalDateTime.now());

        String eventId = "EVT" + LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        existing.setEventId(eventId);

        if ("真实".equals(entity.getIsReal())) {
            existing.setStatus("已核实");

            // 自动创建转接报送记录（如已存在则跳过）
            LambdaQueryWrapper<DisEventTransfer> existWrapper = new LambdaQueryWrapper<>();
            existWrapper.eq(DisEventTransfer::getVerifyId, existing.getId());
            if (transferMapper.selectCount(existWrapper) == 0) {
                DisEventTransfer transfer = new DisEventTransfer();
                transfer.setVerifyId(existing.getId());
                transfer.setEventNo(eventId);
                transfer.setCategory(entity.getCategory());
                transfer.setLevel(entity.getLevel());
                transfer.setSummary(existing.getDescription());
                transfer.setStatus("待转接");
                transfer.setCreateTime(LocalDateTime.now());
                transferMapper.insert(transfer);

                // 写入流转日志
                DisEventTransferLog transferLog = new DisEventTransferLog();
                transferLog.setTransferId(transfer.getId());
                transferLog.setEventNo(eventId);
                transferLog.setActionType("核实");
                transferLog.setActionTarget("核实通过");
                transferLog.setContent("事件核实通过，待转接部门处理");
                transferLog.setType("success");
                transferLog.setActionTime(LocalDateTime.now());
                transferLog.setCreateTime(LocalDateTime.now());
                transferLogMapper.insert(transferLog);
            }
        } else {
            existing.setStatus("不实事件");
        }
        existing.setUpdateTime(LocalDateTime.now());
        return this.updateById(existing);
    }
}
