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.DisEventReport;
import com.zksy.dispatch.domain.DisEventVerify;
import com.zksy.dispatch.dto.EventReportPageInDTO;
import com.zksy.dispatch.mapper.DisEventReportMapper;
import com.zksy.dispatch.mapper.DisEventVerifyMapper;
import com.zksy.dispatch.service.DisEventReportService;
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.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class DisEventReportServiceImpl extends ServiceImpl<DisEventReportMapper, DisEventReport>
        implements DisEventReportService {

    @Autowired
    private DisEventVerifyMapper verifyMapper;

    @Override
    public boolean save(DisEventReport entity) {
        if (StrUtil.isBlank(entity.getEventNo())) {
            String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            long count = this.count() + 1;
            entity.setEventNo("JB" + today + String.format("%03d", count));
        }
        if (entity.getStatus() == null) entity.setStatus("待受理");
        if (entity.getCreateTime() == null) entity.setCreateTime(LocalDateTime.now());
        return super.save(entity);
    }

    @Override
    public Page<DisEventReport> findByPage(EventReportPageInDTO dto) {
        Page<DisEventReport> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<DisEventReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(dto.getSource()), DisEventReport::getSource, dto.getSource());
        wrapper.eq(StrUtil.isNotBlank(dto.getStatus()), DisEventReport::getStatus, dto.getStatus());
        wrapper.eq(StrUtil.isNotBlank(dto.getLocation()), DisEventReport::getLocation, dto.getLocation());
        if (StrUtil.isNotBlank(dto.getKeyword())) {
            wrapper.and(w -> w.like(DisEventReport::getEventNo, dto.getKeyword())
                    .or().like(DisEventReport::getDescription, dto.getKeyword())
                    .or().like(DisEventReport::getReporter, dto.getKeyword()));
        }
        if (StrUtil.isNotBlank(dto.getBeginTime()) && StrUtil.isNotBlank(dto.getEndTime())) {
            wrapper.between(DisEventReport::getCreateTime,
                    LocalDateTime.parse(dto.getBeginTime()),
                    LocalDateTime.parse(dto.getEndTime()));
        }
        wrapper.orderByDesc(DisEventReport::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean accept(Long id) {
        DisEventReport entity = this.getById(id);
        if (entity == null) {
            log.warn("接报记录不存在: id={}", id);
            return false;
        }
        entity.setStatus("已受理");
        entity.setUpdateTime(LocalDateTime.now());
        this.updateById(entity);

        // 自动创建初判核实记录（如已存在则跳过，避免重复受理报错）
        LambdaQueryWrapper<DisEventVerify> existWrapper = new LambdaQueryWrapper<>();
        existWrapper.eq(DisEventVerify::getEventNo, entity.getEventNo());
        if (verifyMapper.selectCount(existWrapper) == 0) {
            DisEventVerify verify = new DisEventVerify();
            verify.setReportId(entity.getId());
            verify.setEventNo(entity.getEventNo());
            verify.setLocation(entity.getLocation());
            verify.setDescription(entity.getDescription());
            verify.setStatus("待核实");
            verify.setJudgeTime(LocalDateTime.now());
            verify.setCreateTime(LocalDateTime.now());
            verifyMapper.insert(verify);
        }
        return true;
    }

    @Override
    public boolean reject(Long id, String remark) {
        DisEventReport entity = this.getById(id);
        if (entity == null) {
            log.warn("接报记录不存在: id={}", id);
            return false;
        }
        entity.setStatus("已驳回");
        entity.setRemark(remark);
        entity.setUpdateTime(LocalDateTime.now());
        return this.updateById(entity);
    }
}
