package com.hotwj.platform.resourceManagement.vehicleClaim.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.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.vehicleClaim.domain.HotVehicleClaim;
import com.hotwj.platform.resourceManagement.vehicleClaim.domain.bo.HotVehicleClaimBo;
import com.hotwj.platform.resourceManagement.vehicleClaim.domain.vo.HotVehicleClaimVo;
import com.hotwj.platform.resourceManagement.vehicleClaim.mapper.HotVehicleClaimMapper;
import com.hotwj.platform.resourceManagement.vehicleClaim.service.IHotVehicleClaimService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.List;
import java.util.Map;

/**
 * 车辆出险记录Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotVehicleClaimServiceImpl implements IHotVehicleClaimService {

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

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

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

    /**
     * 查询符合条件的车辆出险记录列表
     *
     * @param bo 查询条件
     * @return 车辆出险记录列表
     */
    @Override
    public List<HotVehicleClaimVo> queryList(HotVehicleClaimBo bo) {
        LambdaQueryWrapper<HotVehicleClaim> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotVehicleClaim> buildQueryWrapper(HotVehicleClaimBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotVehicleClaim> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotVehicleClaim::getId);
        lqw.eq(bo.getCompanyId() != null, HotVehicleClaim::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getVehicleId() != null, HotVehicleClaim::getVehicleId, bo.getVehicleId());
        lqw.eq(bo.getVehicleInsuranceId() != null, HotVehicleClaim::getVehicleInsuranceId, bo.getVehicleInsuranceId());
        lqw.like(StringUtils.isNotBlank(bo.getPlateNumber()), HotVehicleClaim::getPlateNumber, bo.getPlateNumber());
        lqw.like(StringUtils.isNotBlank(bo.getAccidentLocation()), HotVehicleClaim::getAccidentLocation, bo.getAccidentLocation());
        lqw.like(StringUtils.isNotBlank(bo.getInsuranceType()), HotVehicleClaim::getInsuranceType, bo.getInsuranceType());
        lqw.like(StringUtils.isNotBlank(bo.getInsurerName()), HotVehicleClaim::getInsurerName, bo.getInsurerName());
        lqw.eq(bo.getIncidentTime() != null, HotVehicleClaim::getIncidentTime, bo.getIncidentTime());
        lqw.eq(bo.getAssessDate() != null, HotVehicleClaim::getAssessDate, bo.getAssessDate());
        lqw.eq(bo.getInsuranceExpireDate() != null, HotVehicleClaim::getInsuranceExpireDate, bo.getInsuranceExpireDate());
        lqw.eq(StringUtils.isNotBlank(bo.getClaimItems()), HotVehicleClaim::getClaimItems, bo.getClaimItems());
        lqw.eq(StringUtils.isNotBlank(bo.getImageUrls()), HotVehicleClaim::getImageUrls, bo.getImageUrls());
        lqw.eq(bo.getIsDeleted() != null, HotVehicleClaim::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增车辆出险记录
     *
     * @param bo 车辆出险记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotVehicleClaimBo bo) {
        HotVehicleClaim add = MapstructUtils.convert(bo, HotVehicleClaim.class);
        add.setIsDeleted(0L);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            if (add.getCompanyId() != null) {
                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 insuranceLabel = StringUtils.blankToDefault(add.getInsuranceType(), "车辆保险");
                    String dateStr = add.getIncidentTime() != null ? DateUtils.formatDate(add.getIncidentTime()) : "未知日期";
                    String content = "车辆【" + plate + "】的【" + insuranceLabel + "】由【" + 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(HotVehicleClaimBo bo) {
        HotVehicleClaim before = null;
        if (bo.getId() != null) {
            before = baseMapper.selectById(bo.getId());
        }
        HotVehicleClaim update = MapstructUtils.convert(bo, HotVehicleClaim.class);
        validEntityBeforeSave(update);
        boolean ok = baseMapper.updateById(update) > 0;
        if (ok) {
            Long companyId = update.getCompanyId() != null ? update.getCompanyId() : (before != null ? before.getCompanyId() : null);
            if (companyId != null) {
                List<HotCompanySafetyManager> managers = managerMapper.selectList(
                        Wrappers.<HotCompanySafetyManager>lambdaQuery()
                                .eq(HotCompanySafetyManager::getCompanyId, companyId)
                                .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 = org.dromara.common.core.utils.StringUtils.blankToDefault(update.getPlateNumber() != null ? update.getPlateNumber() : (before != null ? before.getPlateNumber() : null), "未知车牌");
                    String insuranceLabel = org.dromara.common.core.utils.StringUtils.blankToDefault(update.getInsuranceType() != null ? update.getInsuranceType() : (before != null ? before.getInsuranceType() : null), "车辆保险");
                    String dateStr = update.getIncidentTime() != null ? org.dromara.common.core.utils.DateUtils.formatDate(update.getIncidentTime()) : (before != null && before.getIncidentTime() != null ? org.dromara.common.core.utils.DateUtils.formatDate(before.getIncidentTime()) : "未知日期");
                    String content = "车辆【" + plate + "】的【" + insuranceLabel + "】在【" + 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={}", companyId, update.getVehicleId(), e);
                    }
                }
            }
        }
        return ok;
    }

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

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

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