package com.hotwj.platform.config.companyBasicConfig.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.companyBasicConfig.domain.HotCompanyBasicConfig;
import com.hotwj.platform.config.companyBasicConfig.domain.bo.HotCompanyBasicConfigBo;
import com.hotwj.platform.config.companyBasicConfig.domain.vo.HotCompanyBasicConfigVo;
import com.hotwj.platform.config.companyBasicConfig.mapper.HotCompanyBasicConfigMapper;
import com.hotwj.platform.config.companyBasicConfig.service.IHotCompanyBasicConfigService;
import com.hotwj.platform.driverManagement.driver.domain.HotDriver;
import com.hotwj.platform.driverManagement.driver.mapper.HotDriverMapper;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
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-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotCompanyBasicConfigServiceImpl implements IHotCompanyBasicConfigService {

    private final HotCompanyBasicConfigMapper baseMapper;
    private final HotCompanySafetyManagerMapper managerMapper;
    private final HotDriverMapper driverMapper;
    private final IHotSystemNotificationService notificationService;

    /**
     * 查询企业基础配置
     *
     * @param id 主键
     * @return 企业基础配置
     */
    @Override
    public HotCompanyBasicConfigVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询企业基础配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 企业基础配置分页列表
     */
    @Override
    public TableDataInfo<HotCompanyBasicConfigVo> queryPageList(HotCompanyBasicConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotCompanyBasicConfig> lqw = buildQueryWrapper(bo);
        Page<HotCompanyBasicConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的企业基础配置列表
     *
     * @param bo 查询条件
     * @return 企业基础配置列表
     */
    @Override
    public List<HotCompanyBasicConfigVo> queryList(HotCompanyBasicConfigBo bo) {
        LambdaQueryWrapper<HotCompanyBasicConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotCompanyBasicConfig> buildQueryWrapper(HotCompanyBasicConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotCompanyBasicConfig> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotCompanyBasicConfig::getId);
        lqw.eq(bo.getCompanyId() != null, HotCompanyBasicConfig::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getMakeUpStudyEnabled() != null, HotCompanyBasicConfig::getMakeUpStudyEnabled, bo.getMakeUpStudyEnabled());
        lqw.eq(bo.getForbidPeriodEnabled() != null, HotCompanyBasicConfig::getForbidPeriodEnabled, bo.getForbidPeriodEnabled());
        lqw.eq(bo.getForbidStartTime() != null, HotCompanyBasicConfig::getForbidStartTime, bo.getForbidStartTime());
        lqw.eq(bo.getForbidEndTime() != null, HotCompanyBasicConfig::getForbidEndTime, bo.getForbidEndTime());
        lqw.eq(bo.getStudySmsEnabled() != null, HotCompanyBasicConfig::getStudySmsEnabled, bo.getStudySmsEnabled());
        lqw.eq(bo.getRemainingSmsCount() != null, HotCompanyBasicConfig::getRemainingSmsCount, bo.getRemainingSmsCount());
        lqw.eq(bo.getIsDeleted() != null, HotCompanyBasicConfig::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增企业基础配置
     *
     * @param bo 企业基础配置
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotCompanyBasicConfigBo bo) {
        HotCompanyBasicConfig add = MapstructUtils.convert(bo, HotCompanyBasicConfig.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            if (add.getCompanyId() != null
                    && add.getForbidPeriodEnabled() != null && Long.valueOf(1L).equals(add.getForbidPeriodEnabled())
                    && add.getForbidStartTime() != null && add.getForbidEndTime() != null) {
                notifyForbidPeriod(add.getCompanyId(), add.getForbidStartTime(), add.getForbidEndTime());
            }
        }
        return flag;
    }

    /**
     * 修改企业基础配置
     *
     * @param bo 企业基础配置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotCompanyBasicConfigBo bo) {
        HotCompanyBasicConfig update = MapstructUtils.convert(bo, HotCompanyBasicConfig.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            HotCompanyBasicConfig cfg = baseMapper.selectById(update.getId());
            if (cfg != null
                    && cfg.getCompanyId() != null
                    && cfg.getForbidPeriodEnabled() != null && Long.valueOf(1L).equals(cfg.getForbidPeriodEnabled())
                    && cfg.getForbidStartTime() != null && cfg.getForbidEndTime() != null) {
                notifyForbidPeriod(cfg.getCompanyId(), bo.getForbidStartTime(), bo.getForbidEndTime());
            }
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotCompanyBasicConfig 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 void notifyForbidPeriod(Long companyId, String startTime, String endTime) {
        List<HotCompanySafetyManager> managers = managerMapper.selectList(
                Wrappers.<HotCompanySafetyManager>lambdaQuery()
                        .eq(HotCompanySafetyManager::getCompanyId, companyId)
                        .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                        .eq(HotCompanySafetyManager::getIsResigned, 0L)
                        .eq(HotCompanySafetyManager::getStatus, 1L)
        );
        List<HotDriver> drivers = driverMapper.selectList(
                Wrappers.<HotDriver>lambdaQuery()
                        .eq(HotDriver::getCompanyId, companyId)
                        .eq(HotDriver::getIsDeleted, 0L)
                        .eq(HotDriver::getStatus, 1L)
        );
        String content = "企业已配置禁学期间：" + startTime + " 至 " + endTime + "，期间禁止学习。";

        if (managers != null && !managers.isEmpty()) {
            List<String> receiverIds = managers.stream().map(m -> String.valueOf(m.getId())).toList();
            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={} type=manager", companyId, e);
            }
        }
        if (drivers != null && !drivers.isEmpty()) {
            List<String> receiverIds = drivers.stream().map(HotDriver::getId).toList();
            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={} type=driver", companyId, e);
            }
        }
    }
}
