package com.hotwj.platform.resourceManagement.companyPolicy.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.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.companyPolicy.domain.HotCompanyPolicy;
import com.hotwj.platform.resourceManagement.companyPolicy.domain.bo.HotCompanyPolicyBo;
import com.hotwj.platform.resourceManagement.companyPolicy.domain.vo.HotCompanyPolicyVo;
import com.hotwj.platform.resourceManagement.companyPolicy.mapper.HotCompanyPolicyMapper;
import com.hotwj.platform.resourceManagement.companyPolicy.service.IHotCompanyPolicyService;
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.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-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotCompanyPolicyServiceImpl implements IHotCompanyPolicyService {

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

    /**
     * 查询公司制度资料档案
     *
     * @param id 主键
     * @return 公司制度资料档案
     */
    @Override
    public HotCompanyPolicyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询公司制度资料档案列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 公司制度资料档案分页列表
     */
    @Override
    public TableDataInfo<HotCompanyPolicyVo> queryPageList(HotCompanyPolicyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotCompanyPolicy> lqw = buildQueryWrapper(bo);
        Page<HotCompanyPolicyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的公司制度资料档案列表
     *
     * @param bo 查询条件
     * @return 公司制度资料档案列表
     */
    @Override
    public List<HotCompanyPolicyVo> queryList(HotCompanyPolicyBo bo) {
        LambdaQueryWrapper<HotCompanyPolicy> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotCompanyPolicy> buildQueryWrapper(HotCompanyPolicyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotCompanyPolicy> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotCompanyPolicy::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getPolicyType()), HotCompanyPolicy::getPolicyType, bo.getPolicyType());
        lqw.eq(bo.getCompanyId() != null, HotCompanyPolicy::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getPolicyTitle()), HotCompanyPolicy::getPolicyTitle, bo.getPolicyTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getAttachmentUrl()), HotCompanyPolicy::getAttachmentUrl, bo.getAttachmentUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getContentHtml()), HotCompanyPolicy::getContentHtml, bo.getContentHtml());
        lqw.like(bo.getIsPublished() != null, HotCompanyPolicy::getIsPublished, bo.getIsPublished());
        lqw.eq(bo.getIsDeleted() != null, HotCompanyPolicy::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增公司制度资料档案
     *
     * @param bo 公司制度资料档案
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotCompanyPolicyBo bo) {
        HotCompanyPolicy add = MapstructUtils.convert(bo, HotCompanyPolicy.class);
        // 获取当前公司最大的排序号
        HotCompanyPolicy maxOrderPolicy = baseMapper.selectOne(new LambdaQueryWrapper<HotCompanyPolicy>()
                .select(HotCompanyPolicy::getOrderNum)
                .eq(HotCompanyPolicy::getCompanyId, bo.getCompanyId())
                .eq(HotCompanyPolicy::getPolicyType, bo.getPolicyType())
                .orderByDesc(HotCompanyPolicy::getOrderNum)
                .last("limit 1"));
        long maxOrder = (maxOrderPolicy != null && maxOrderPolicy.getOrderNum() != null) ? maxOrderPolicy.getOrderNum() : 0L;
        add.setOrderNum(maxOrder + 1);

        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            if (add.getCompanyId() != null && add.getIsPublished() != null && Long.valueOf(1L).equals(add.getIsPublished())) {
                java.util.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)
                );
                java.util.List<HotDriver> drivers = driverMapper.selectList(
                        Wrappers.<HotDriver>lambdaQuery()
                                .eq(HotDriver::getCompanyId, add.getCompanyId())
                                .eq(HotDriver::getIsDeleted, 0L)
                                .eq(HotDriver::getStatus, 1L)
                );
                String title = StringUtils.blankToDefault(add.getPolicyTitle(), "新制度");
                String content = "公司制度【" + title + "】已发布，请及时查阅。";
                if (managers != null && !managers.isEmpty()) {
                    java.util.List<String> managerIds = managers.stream().map(m -> String.valueOf(m.getId())).toList();
                    HotSystemNotificationGroupBo bosMgr = new HotSystemNotificationGroupBo();
                    bosMgr.setLevel("普通");
                    bosMgr.setContent(content);
                    bosMgr.setSourceType("制度与会议");
                    bosMgr.setSenderType("SYSTEM");
                    bosMgr.setReceiverType("管理员");
                    bosMgr.setReceiverIds(managerIds);
                    bosMgr.setIsDeleted(0L);
                    try {
                        notificationService.insertByBo(bosMgr);
                    } catch (Exception e) {
                        log.warn("发送新增制度通知失败(管理员) companyId={} policyId={}", add.getCompanyId(), add.getId(), e);
                    }
                }
                if (drivers != null && !drivers.isEmpty()) {
                    java.util.List<String> driverIds = drivers.stream().map(d -> String.valueOf(d.getId())).toList();
                    HotSystemNotificationGroupBo bosDrv = new HotSystemNotificationGroupBo();
                    bosDrv.setLevel("普通");
                    bosDrv.setContent(content);
                    bosDrv.setSourceType("制度与会议");
                    bosDrv.setSenderType("SYSTEM");
                    bosDrv.setReceiverType("驾驶员");
                    bosDrv.setReceiverIds(driverIds);
                    bosDrv.setIsDeleted(0L);
                    try {
                        notificationService.insertByBo(bosDrv);
                    } catch (Exception e) {
                        log.warn("发送新增制度通知失败(驾驶员) companyId={} policyId={}", add.getCompanyId(), add.getId(), e);
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 修改公司制度资料档案
     *
     * @param bo 公司制度资料档案
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotCompanyPolicyBo bo) {
        HotCompanyPolicy before = null;
        if (bo.getId() != null) {
            before = baseMapper.selectById(bo.getId());
        }
        HotCompanyPolicy update = MapstructUtils.convert(bo, HotCompanyPolicy.class);
        validEntityBeforeSave(update);
        boolean ok = baseMapper.updateById(update) > 0;
        if (ok) {
            Long companyId = update.getCompanyId() != null ? update.getCompanyId() : (before != null ? before.getCompanyId() : null);
            Long isPublished = update.getIsPublished() != null ? update.getIsPublished() : (before != null ? before.getIsPublished() : null);
            if (companyId != null && isPublished != null && Long.valueOf(1L).equals(isPublished)) {
                java.util.List<HotCompanySafetyManager> managers = managerMapper.selectList(
                        Wrappers.<HotCompanySafetyManager>lambdaQuery()
                                .eq(HotCompanySafetyManager::getCompanyId, companyId)
                                .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                                .eq(HotCompanySafetyManager::getIsResigned, 0L)
                                .eq(HotCompanySafetyManager::getStatus, 1L)
                );
                java.util.List<HotDriver> drivers = driverMapper.selectList(
                        Wrappers.<HotDriver>lambdaQuery()
                                .eq(HotDriver::getCompanyId, companyId)
                                .eq(HotDriver::getIsDeleted, 0L)
                                .eq(HotDriver::getStatus, 1L)
                );
                String title = org.dromara.common.core.utils.StringUtils.blankToDefault(
                        update.getPolicyTitle() != null ? update.getPolicyTitle() : (before != null ? before.getPolicyTitle() : null),
                        "制度"
                );
                String content = "公司制度【" + title + "】已更新，请及时查阅。";
                if (managers != null && !managers.isEmpty()) {
                    java.util.List<String> managerIds = managers.stream().map(m -> String.valueOf(m.getId())).toList();
                    HotSystemNotificationGroupBo bosMgr = new HotSystemNotificationGroupBo();
                    bosMgr.setLevel("普通");
                    bosMgr.setContent(content);
                    bosMgr.setSourceType("制度与会议");
                    bosMgr.setSenderType("SYSTEM");
                    bosMgr.setReceiverType("管理员");
                    bosMgr.setReceiverIds(managerIds);
                    bosMgr.setIsDeleted(0L);
                    try {
                        notificationService.insertByBo(bosMgr);
                    } catch (Exception e) {
                        log.warn("发送更新制度通知失败(管理员) companyId={} policyId={}", companyId, update.getId(), e);
                    }
                }
                if (drivers != null && !drivers.isEmpty()) {
                    java.util.List<String> driverIds = drivers.stream().map(d -> String.valueOf(d.getId())).toList();
                    HotSystemNotificationGroupBo bosDrv = new HotSystemNotificationGroupBo();
                    bosDrv.setLevel("普通");
                    bosDrv.setContent(content);
                    bosDrv.setSourceType("制度与会议");
                    bosDrv.setSenderType("SYSTEM");
                    bosDrv.setReceiverType("驾驶员");
                    bosDrv.setReceiverIds(driverIds);
                    bosDrv.setIsDeleted(0L);
                    try {
                        notificationService.insertByBo(bosDrv);
                    } catch (Exception e) {
                        log.warn("发送更新制度通知失败(驾驶员) companyId={} policyId={}", companyId, update.getId(), e);
                    }
                }
            }
        }
        return ok;
    }

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

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