package com.hotwj.platform.securityManagement.vehicleInoutCheck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.config.vehicleThreeInspect.service.IHotVehicleThreeInspectService;
import com.hotwj.platform.noticeManagerment.systemNotification.domain.bo.HotSystemNotificationGroupBo;
import com.hotwj.platform.noticeManagerment.systemNotification.service.IHotSystemNotificationService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.HotCompanySafetyManager;
import com.hotwj.platform.resourceManagement.companySafetyManager.mapper.HotCompanySafetyManagerMapper;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.HotVehicle;
import com.hotwj.platform.resourceManagement.vehicleManagement.mapper.HotVehicleMapper;
import com.hotwj.platform.securityManagement.vehicleEntryExit.domain.bo.HotVehicleEntryExitBo;
import com.hotwj.platform.securityManagement.vehicleEntryExit.service.IHotVehicleEntryExitService;
import com.hotwj.platform.securityManagement.vehicleInoutCheck.domain.HotVehicleInoutCheck;
import com.hotwj.platform.securityManagement.vehicleInoutCheck.domain.bo.HotVehicleInoutCheckBo;
import com.hotwj.platform.securityManagement.vehicleInoutCheck.domain.vo.HotVehicleInoutCheckVo;
import com.hotwj.platform.securityManagement.vehicleInoutCheck.mapper.HotVehicleInoutCheckMapper;
import com.hotwj.platform.securityManagement.vehicleInoutCheck.service.IHotVehicleInoutCheckService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 车辆进出场检查Service业务层处理
 *
 * @author shihongwei
 * @date 2026-01-05
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotVehicleInoutCheckServiceImpl implements IHotVehicleInoutCheckService {

    private final HotVehicleInoutCheckMapper baseMapper;
    private final IHotVehicleEntryExitService vehicleEntryExitService;
    private final HotVehicleMapper vehicleMapper;
    private final HotCompanySafetyManagerMapper safetyManagerMapper;
    private final IHotSystemNotificationService notificationService;
    private final IHotVehicleThreeInspectService hotVehicleThreeInspectService;

    /**
     * 查询车辆进出场检查
     *
     * @param id 主键
     * @return 车辆进出场检查
     */
    @Override
    public HotVehicleInoutCheckVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询车辆进出场检查列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 车辆进出场检查分页列表
     */
    @Override
    public TableDataInfo<HotVehicleInoutCheckVo> queryPageList(HotVehicleInoutCheckBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotVehicleInoutCheck> lqw = buildQueryWrapper(bo);
        Page<HotVehicleInoutCheckVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的车辆进出场检查列表
     *
     * @param bo 查询条件
     * @return 车辆进出场检查列表
     */
    @Override
    public List<HotVehicleInoutCheckVo> queryList(HotVehicleInoutCheckBo bo) {
        LambdaQueryWrapper<HotVehicleInoutCheck> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotVehicleInoutCheck> buildQueryWrapper(HotVehicleInoutCheckBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotVehicleInoutCheck> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(HotVehicleInoutCheck::getCheckDate);
        lqw.eq(bo.getRecordId() != null, HotVehicleInoutCheck::getRecordId, bo.getRecordId());
        lqw.eq(bo.getCompanyId() != null, HotVehicleInoutCheck::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getVehicleId() != null, HotVehicleInoutCheck::getVehicleId, bo.getVehicleId());
        lqw.eq(StringUtils.isNotBlank(bo.getPlateNumber()), HotVehicleInoutCheck::getPlateNumber, bo.getPlateNumber());
        lqw.eq(bo.getInspectorId() != null, HotVehicleInoutCheck::getInspectorId, bo.getInspectorId());
        lqw.like(StringUtils.isNotBlank(bo.getInspectorName()), HotVehicleInoutCheck::getInspectorName, bo.getInspectorName());
        lqw.eq(bo.getDrivingLicenseStatus() != null, HotVehicleInoutCheck::getDrivingLicenseStatus, bo.getDrivingLicenseStatus());
        lqw.eq(bo.getDriverLicenseStatus() != null, HotVehicleInoutCheck::getDriverLicenseStatus, bo.getDriverLicenseStatus());
        lqw.eq(bo.getRoadTransportCertStatus() != null, HotVehicleInoutCheck::getRoadTransportCertStatus, bo.getRoadTransportCertStatus());
        lqw.eq(bo.getQualificationCertStatus() != null, HotVehicleInoutCheck::getQualificationCertStatus, bo.getQualificationCertStatus());
        lqw.eq(bo.getCheckDate() != null, HotVehicleInoutCheck::getCheckDate, bo.getCheckDate());
        lqw.eq(bo.getDepartureTime() != null, HotVehicleInoutCheck::getDepartureTime, bo.getDepartureTime());
        lqw.eq(bo.getReturnTime() != null, HotVehicleInoutCheck::getReturnTime, bo.getReturnTime());
        lqw.eq(StringUtils.isNotBlank(bo.getRoute()), HotVehicleInoutCheck::getRoute, bo.getRoute());
        lqw.eq(StringUtils.isNotBlank(bo.getConclusion()), HotVehicleInoutCheck::getConclusion, bo.getConclusion());
        lqw.like(StringUtils.isNotBlank(bo.getReturnRemark()), HotVehicleInoutCheck::getReturnRemark, bo.getReturnRemark());
        lqw.eq(bo.getIsDeleted() != null, HotVehicleInoutCheck::getIsDeleted, bo.getIsDeleted());
        lqw.like(StringUtils.isNotBlank(bo.getCreateByName()), HotVehicleInoutCheck::getCreateByName, bo.getCreateByName());
        lqw.like(StringUtils.isNotBlank(bo.getUpdateByName()), HotVehicleInoutCheck::getUpdateByName, bo.getUpdateByName());
        return lqw;
    }

    /**
     * 新增车辆进出场检查
     *
     * @param bo 车辆进出场检查
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotVehicleInoutCheckBo bo) {
        if (bo.getCheckDate() == null) {
            bo.setCheckDate(new Date());
        }

        hotVehicleThreeInspectService.validateNoUnfinishedProcess(String.valueOf(bo.getVehicleId()),
                "当前车辆三检流程未完成，不能新增出车检查");

        // 填充冗余字段（车牌号、检查人员姓名）
        fillRedundantFields(bo);

        // 只有在新增未完成的出场记录时（returnTime == null），才校验是否已存在未回场记录
        // 如果是补录已完成的历史记录（returnTime != null），则不受此限制
        if (bo.getVehicleId() != null && bo.getReturnTime() == null) {
            LambdaQueryWrapper<HotVehicleInoutCheck> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(HotVehicleInoutCheck::getVehicleId, bo.getVehicleId());
            queryWrapper.isNotNull(HotVehicleInoutCheck::getDepartureTime);
            queryWrapper.isNull(HotVehicleInoutCheck::getReturnTime);
            // 严谨逻辑：查询该车是否存在任意一条“已出场但未回场”的记录，防止历史脏数据导致的状态错误
            if (baseMapper.selectCount(queryWrapper) > 0) {
                throw new ServiceException("该车尚有未回场的记录，请先处理");
            }
        }
        // 如果存在检查日期存在，则不创建新表，复用之前查到的HotVehicleInoutCheck
        if (bo.getRecordId() == null) {
            com.hotwj.platform.securityManagement.vehicleEntryExit.domain.vo.HotVehicleEntryExitVo entryExitVo = vehicleEntryExitService.selectByCheckDate(bo.getCompanyId(), bo.getCheckDate());
            if (entryExitVo != null) {
                bo.setRecordId(entryExitVo.getId());
            } else {
                HotVehicleEntryExitBo entryExitBo = new HotVehicleEntryExitBo();
                entryExitBo.setCompanyId(bo.getCompanyId());
                entryExitBo.setCheckTime(bo.getCheckDate());
                vehicleEntryExitService.insertByBo(entryExitBo);
                bo.setRecordId(entryExitBo.getId());
            }
        }
        HotVehicleInoutCheck add = MapstructUtils.convert(bo, HotVehicleInoutCheck.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            boolean abnormal = isAbnormal(add);
            if (abnormal && add.getCompanyId() != null) {
                List<HotCompanySafetyManager> managers = safetyManagerMapper.selectList(
                        Wrappers.<HotCompanySafetyManager>lambdaQuery()
                                .eq(HotCompanySafetyManager::getCompanyId, add.getCompanyId())
                                .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                                .eq(HotCompanySafetyManager::getIsResigned, 0L)
                                .eq(HotCompanySafetyManager::getStatus, 1L)
                );
                if (managers != null && !managers.isEmpty()) {
                    List<String> receiverIds = managers.stream().map(m -> String.valueOf(m.getId())).toList();
                    String plate = StringUtils.blankToDefault(add.getPlateNumber(), "未知车牌");
                    String dateStr = add.getCheckDate() != null ? DateUtils.formatDate(add.getCheckDate()) : "未知日期";
                    String content = "车辆【" + plate + "】在【" + dateStr + "】进出场检查发现异常。";
                    HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
                    bos.setLevel("普通");
                    bos.setContent(content);
                    bos.setSourceType("车辆管理");
                    bos.setSenderType("SYSTEM");
                    bos.setReceiverType("管理员");
                    bos.setReceiverIds(receiverIds);
                    bos.setIsDeleted(0L);
                    try {
                        notificationService.insertByBo(bos);
                    } catch (Exception e) {
                        log.warn("发送进出场异常通知失败 companyId={} vehicleId={}", add.getCompanyId(), add.getVehicleId(), e);
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 修改车辆进出场检查
     *
     * @param bo 车辆进出场检查
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotVehicleInoutCheckBo bo) {
        // 填充冗余字段（车牌号、检查人员姓名）
        fillRedundantFields(bo);
        
        HotVehicleInoutCheck update = MapstructUtils.convert(bo, HotVehicleInoutCheck.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 填充冗余字段：车牌号、检查人员姓名
     */
    private void fillRedundantFields(HotVehicleInoutCheckBo bo) {
        // 填充车牌号
        if (StringUtils.isBlank(bo.getPlateNumber()) && bo.getVehicleId() != null) {
            // HotVehicle 主键 ID 定义为 String，需转换
            HotVehicle vehicle = vehicleMapper.selectById(String.valueOf(bo.getVehicleId()));
            if (vehicle != null) {
                bo.setPlateNumber(vehicle.getPlateNumber());
            }
        }
        // 填充检查人员姓名（安全管理人员）
        if (StringUtils.isBlank(bo.getInspectorName()) && bo.getInspectorId() != null) {
            HotCompanySafetyManager safetyManager = safetyManagerMapper.selectById(bo.getInspectorId());
            if (safetyManager != null) {
                bo.setInspectorName(safetyManager.getName());
            }
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotVehicleInoutCheck entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除车辆进出场检查信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    private boolean isAbnormal(HotVehicleInoutCheck entity) {
        return (entity.getDrivingLicenseStatus() != null && Long.valueOf(0L).equals(entity.getDrivingLicenseStatus()))
                || (entity.getDriverLicenseStatus() != null && Long.valueOf(0L).equals(entity.getDriverLicenseStatus()))
                || (entity.getRoadTransportCertStatus() != null && Long.valueOf(0L).equals(entity.getRoadTransportCertStatus()))
                || (entity.getQualificationCertStatus() != null && Long.valueOf(0L).equals(entity.getQualificationCertStatus()));
    }
}
