package com.hotwj.platform.resourceManagement.vehicleRepair.service.impl;

import cn.hutool.core.collection.CollUtil;
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.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.vehicleRepair.domain.HotVehicleRepair;
import com.hotwj.platform.resourceManagement.vehicleRepair.domain.bo.HotVehicleRepairBo;
import com.hotwj.platform.resourceManagement.vehicleRepair.domain.vo.HotVehicleRepairVo;
import com.hotwj.platform.resourceManagement.vehicleRepair.mapper.HotVehicleRepairMapper;
import com.hotwj.platform.resourceManagement.vehicleRepair.service.IHotVehicleRepairService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.List;
import java.util.Map;

/**
 * 车辆维修记录Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotVehicleRepairServiceImpl implements IHotVehicleRepairService {

    private final HotVehicleRepairMapper baseMapper;
    private final HotCompanySafetyManagerMapper managerMapper;
    private final IHotSystemNotificationService notificationService;

    /**
     * 查询车辆维修记录
     *
     * @param id 主键
     * @return 车辆维修记录
     */
    @Override
    public HotVehicleRepairVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询车辆维修记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 车辆维修记录分页列表
     */
    @Override
    public TableDataInfo<HotVehicleRepairVo> queryPageList(HotVehicleRepairBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotVehicleRepair> lqw = buildQueryWrapper(bo);
        Page<HotVehicleRepairVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的车辆维修记录列表
     *
     * @param bo 查询条件
     * @return 车辆维修记录列表
     */
    @Override
    public List<HotVehicleRepairVo> queryList(HotVehicleRepairBo bo) {
        LambdaQueryWrapper<HotVehicleRepair> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据车辆ID查询最新的一条维修记录
     *
     * @param vehicleId 车辆ID
     * @return 最新维修记录
     */
    @Override
    public HotVehicleRepairVo queryLatestByVehicleId(String vehicleId) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<HotVehicleRepair>()
            .eq(HotVehicleRepair::getVehicleId, vehicleId)
            .orderByDesc(HotVehicleRepair::getFinishDate)
            .last("LIMIT 1"));
    }

    private LambdaQueryWrapper<HotVehicleRepair> buildQueryWrapper(HotVehicleRepairBo bo) {
        Map<String, Object> params = bo.getParams();
        Object beginTime = params.get("beginTime");
        Object endTime = params.get("endTime");
        LambdaQueryWrapper<HotVehicleRepair> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotVehicleRepair::getId);
        lqw.eq(bo.getCompanyId() != null, HotVehicleRepair::getCompanyId, bo.getCompanyId());
        lqw.in(CollUtil.isNotEmpty(bo.getIds()), HotVehicleRepair::getId, bo.getIds());
        lqw.eq(bo.getVehicleId() != null, HotVehicleRepair::getVehicleId, bo.getVehicleId());
        lqw.like(StringUtils.isNotBlank(bo.getPlateNumber()), HotVehicleRepair::getPlateNumber, bo.getPlateNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairCategory()), HotVehicleRepair::getRepairCategory, bo.getRepairCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairReason()), HotVehicleRepair::getRepairReason, bo.getRepairReason());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairUnit()), HotVehicleRepair::getRepairUnit, bo.getRepairUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairUnitPhone()), HotVehicleRepair::getRepairUnitPhone, bo.getRepairUnitPhone());
        lqw.eq(bo.getRepairAmount() != null, HotVehicleRepair::getRepairAmount, bo.getRepairAmount());
        lqw.eq(bo.getIsMajorPartReplaced() != null, HotVehicleRepair::getIsMajorPartReplaced, bo.getIsMajorPartReplaced());
        lqw.eq(StringUtils.isNotBlank(bo.getRecorder()), HotVehicleRepair::getRecorder, bo.getRecorder());
        lqw.eq(bo.getRepairDate() != null, HotVehicleRepair::getRepairDate, bo.getRepairDate());
        lqw.eq(bo.getFinishDate() != null, HotVehicleRepair::getFinishDate, bo.getFinishDate());
        lqw.eq(StringUtils.isNotBlank(bo.getReplacedParts()), HotVehicleRepair::getReplacedParts, bo.getReplacedParts());
        lqw.eq(StringUtils.isNotBlank(bo.getPartSpec()), HotVehicleRepair::getPartSpec, bo.getPartSpec());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairContent()), HotVehicleRepair::getRepairContent, bo.getRepairContent());
        lqw.eq(StringUtils.isNotBlank(bo.getProofImageUrls()), HotVehicleRepair::getProofImageUrls, bo.getProofImageUrls());
        lqw.eq(bo.getIsDeleted() != null, HotVehicleRepair::getIsDeleted, bo.getIsDeleted());
        lqw.eq(bo.getOperationStatus() != null, HotVehicleRepair::getOperationStatus, bo.getOperationStatus());
        lqw.gt(beginTime != null, HotVehicleRepair::getRepairDate, beginTime);
        lqw.lt(endTime != null, HotVehicleRepair::getFinishDate, endTime);
        return lqw;
    }

    /**
     * 新增车辆维修记录
     *
     * @param bo 车辆维修记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotVehicleRepairBo bo) {
        HotVehicleRepair add = MapstructUtils.convert(bo, HotVehicleRepair.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            if (add.getCompanyId() != null
                    && add.getIsMajorPartReplaced() != null && Long.valueOf(1L).equals(add.getIsMajorPartReplaced())
                    && StringUtils.isNotBlank(add.getReplacedParts())) {
                List<HotCompanySafetyManager> managers = managerMapper.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 content = "车辆【" + plate + "】更换了主要部件（" + add.getReplacedParts() + "）。";
                    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(HotVehicleRepairBo bo) {
        HotVehicleRepair old = baseMapper.selectById(bo.getId());
        HotVehicleRepair update = MapstructUtils.convert(bo, HotVehicleRepair.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            boolean changedToMajor = update.getCompanyId() != null
                    && update.getIsMajorPartReplaced() != null && Long.valueOf(1L).equals(update.getIsMajorPartReplaced())
                    && (old == null || !Long.valueOf(1L).equals(old.getIsMajorPartReplaced()))
                    && StringUtils.isNotBlank(update.getReplacedParts());
            if (changedToMajor) {
                List<HotCompanySafetyManager> managers = managerMapper.selectList(
                        Wrappers.<HotCompanySafetyManager>lambdaQuery()
                                .eq(HotCompanySafetyManager::getCompanyId, update.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(update.getPlateNumber(), "未知车牌");
                    String content = "车辆【" + plate + "】更换了主要部件（" + update.getReplacedParts() + "）。";
                    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={}", update.getCompanyId(), update.getVehicleId(), e);
                    }
                }
            }
        }
        return flag;
    }

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

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