package com.hotwj.platform.driverManagement.driverRewardPunishment.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.driverManagement.driverRewardPunishment.domain.HotDriverRewardPunishment;
import com.hotwj.platform.driverManagement.driverRewardPunishment.domain.bo.HotDriverRewardPunishmentBo;
import com.hotwj.platform.driverManagement.driverRewardPunishment.domain.vo.HotDriverRewardPunishmentVo;
import com.hotwj.platform.driverManagement.driverRewardPunishment.mapper.HotDriverRewardPunishmentMapper;
import com.hotwj.platform.driverManagement.driverRewardPunishment.service.IHotDriverRewardPunishmentService;
import com.hotwj.platform.noticeManagerment.systemNotification.domain.bo.HotSystemNotificationGroupBo;
import com.hotwj.platform.noticeManagerment.systemNotification.service.IHotSystemNotificationService;
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-16
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotDriverRewardPunishmentServiceImpl implements IHotDriverRewardPunishmentService {

    private final HotDriverRewardPunishmentMapper baseMapper;
    private final IHotSystemNotificationService notificationService;
    /**
     * 查询驾驶员奖惩记录
     *
     * @param id 主键
     * @return 驾驶员奖惩记录
     */
    @Override
    public HotDriverRewardPunishmentVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询驾驶员奖惩记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 驾驶员奖惩记录分页列表
     */
    @Override
    public TableDataInfo<HotDriverRewardPunishmentVo> queryPageList(HotDriverRewardPunishmentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotDriverRewardPunishment> lqw = buildQueryWrapper(bo);
        Page<HotDriverRewardPunishmentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的驾驶员奖惩记录列表
     *
     * @param bo 查询条件
     * @return 驾驶员奖惩记录列表
     */
    @Override
    public List<HotDriverRewardPunishmentVo> queryList(HotDriverRewardPunishmentBo bo) {
        LambdaQueryWrapper<HotDriverRewardPunishment> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotDriverRewardPunishment> buildQueryWrapper(HotDriverRewardPunishmentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotDriverRewardPunishment> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotDriverRewardPunishment::getId);
        lqw.eq(bo.getCompanyId() != null, HotDriverRewardPunishment::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getDriverName()), HotDriverRewardPunishment::getDriverName, bo.getDriverName());
        lqw.eq(bo.getDriverId() != null, HotDriverRewardPunishment::getDriverId, bo.getDriverId());
        lqw.eq(bo.getRecordType() != null, HotDriverRewardPunishment::getRecordType, bo.getRecordType());
        lqw.eq(bo.getEventDate() != null, HotDriverRewardPunishment::getEventDate, bo.getEventDate());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), HotDriverRewardPunishment::getCategory, bo.getCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getReason()), HotDriverRewardPunishment::getReason, bo.getReason());
        lqw.eq(StringUtils.isNotBlank(bo.getDecision()), HotDriverRewardPunishment::getDecision, bo.getDecision());
        lqw.eq(StringUtils.isNotBlank(bo.getAttachmentUrl()), HotDriverRewardPunishment::getAttachmentUrl, bo.getAttachmentUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), HotDriverRewardPunishment::getContent, bo.getContent());
        lqw.eq(bo.getRecorderId() != null, HotDriverRewardPunishment::getRecorderId, bo.getRecorderId());
        lqw.eq(bo.getIsDeleted() != null, HotDriverRewardPunishment::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增驾驶员奖惩记录
     *
     * @param bo 驾驶员奖惩记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotDriverRewardPunishmentBo bo) {
        HotDriverRewardPunishment add = MapstructUtils.convert(bo, HotDriverRewardPunishment.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            if (StringUtils.isNotBlank(add.getDriverId())) {
                HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
                bos.setLevel("普通");
                String content;
                String rewardPunishmentContent = StringUtils.isNotBlank(add.getContent()) ? add.getContent() : "请查看详情。";
                if (add.getRecordType() != null && Long.valueOf(1L).equals(add.getRecordType())) {
                    content = "您有一条来自企业的奖励信息：" + rewardPunishmentContent;
                } else if (add.getRecordType() != null && Long.valueOf(2L).equals(add.getRecordType())) {
                    content = "您有一条来自企业的处分信息：" + rewardPunishmentContent;
                } else {
                    content = "您有一条来自企业的奖励/惩罚信息：" + rewardPunishmentContent;
                }
                bos.setContent(content);
                bos.setSourceType("驾驶员管理");
                bos.setSenderType("SYSTEM");
                bos.setReceiverType("驾驶员");
                bos.setReceiverIds(java.util.Collections.singletonList(add.getDriverId()));
                bos.setIsDeleted(0L);
                try {
                    notificationService.insertByBo(bos);
                } catch (Exception e) {
                    log.warn("发送驾驶员奖惩新增通知失败 driverId={} companyId={}", add.getDriverId(), add.getCompanyId(), e);
                }
            }
        }
        return flag;
    }

    /**
     * 修改驾驶员奖惩记录
     *
     * @param bo 驾驶员奖惩记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotDriverRewardPunishmentBo bo) {
        HotDriverRewardPunishment before = null;
        if (bo.getId() != null) {
            before = baseMapper.selectById(bo.getId());
        }
        HotDriverRewardPunishment update = MapstructUtils.convert(bo, HotDriverRewardPunishment.class);
        validEntityBeforeSave(update);
        boolean ok = baseMapper.updateById(update) > 0;
        if (ok) {
            String driverId = org.dromara.common.core.utils.StringUtils.isNotBlank(update.getDriverId()) ? update.getDriverId()
                    : (before != null ? before.getDriverId() : null);
            if (org.dromara.common.core.utils.StringUtils.isNotBlank(driverId)) {
                HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
                bos.setLevel("普通");
                String content;
                Long type = update.getRecordType() != null ? update.getRecordType() : (before != null ? before.getRecordType() : null);
                if (type != null && Long.valueOf(1L).equals(type)) {
                    content = "您有一条来自企业的奖励信息已更新，请查看。";
                } else if (type != null && Long.valueOf(2L).equals(type)) {
                    content = "您有一条来自企业的处分信息已更新，请查看。";
                } else {
                    content = "您有一条来自企业的奖励/惩罚信息已更新，请查看。";
                }
                bos.setContent(content);
                bos.setSourceType("驾驶员管理");
                bos.setSenderType("SYSTEM");
                bos.setReceiverType("驾驶员");
                bos.setReceiverIds(java.util.Collections.singletonList(driverId));
                bos.setIsDeleted(0L);
                try {
                    notificationService.insertByBo(bos);
                } catch (Exception e) {
                    log.warn("发送驾驶员奖惩修改通知失败 driverId={} companyId={}", driverId, update.getCompanyId(), e);
                }
            }
        }
        return ok;
    }

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

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