package com.hotwj.platform.noticeManagerment.noticeReply.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.adminNotice.domain.HotAdminNotice;
import com.hotwj.platform.noticeManagerment.adminNotice.mapper.HotAdminNoticeMapper;
import com.hotwj.platform.noticeManagerment.noticeReply.domain.HotNoticeReply;
import com.hotwj.platform.noticeManagerment.noticeReply.domain.bo.HotNoticeReplyBo;
import com.hotwj.platform.noticeManagerment.noticeReply.domain.vo.HotNoticeReplyVo;
import com.hotwj.platform.noticeManagerment.noticeReply.mapper.HotNoticeReplyMapper;
import com.hotwj.platform.noticeManagerment.noticeReply.service.IHotNoticeReplyService;
import com.hotwj.platform.noticeManagerment.notificationIssue.domain.HotNotificationIssue;
import com.hotwj.platform.noticeManagerment.notificationIssue.mapper.HotNotificationIssueMapper;
import com.hotwj.platform.noticeManagerment.systemNotification.domain.bo.HotSystemNotificationGroupBo;
import com.hotwj.platform.noticeManagerment.systemNotification.service.IHotSystemNotificationService;
import com.hotwj.platform.resourceManagement.company.domain.SysCompany;
import com.hotwj.platform.resourceManagement.company.mapper.SysCompanyMapper;
import com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.HotCompanySafetyManager;
import com.hotwj.platform.resourceManagement.companySafetyManager.mapper.HotCompanySafetyManagerMapper;
import com.hotwj.platform.resourceManagement.govEnterpriseUnit.domain.HotGovEnterpriseUnit;
import com.hotwj.platform.resourceManagement.govEnterpriseUnit.mapper.HotGovEnterpriseUnitMapper;
import com.hotwj.platform.resourceManagement.personnelConfig.mapper.HotPersonnelConfigMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.model.LoginUser;
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.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 通知整改回复记录Service业务层处理
 *
 * @author shihongwei
 * @date 2026-02-05
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotNoticeReplyServiceImpl implements IHotNoticeReplyService {

    private final HotNoticeReplyMapper baseMapper;
    private final HotAdminNoticeMapper hotAdminNoticeMapper;
    private final HotNotificationIssueMapper hotNotificationIssueMapper;
    private final HotGovEnterpriseUnitMapper hotGovEnterpriseUnitMapper;
    private final HotPersonnelConfigMapper hotPersonnelConfigMapper;
    private final SysCompanyMapper sysCompanyMapper;
    private final HotCompanySafetyManagerMapper hotCompanySafetyManagerMapper;
    private final IHotSystemNotificationService hotSystemNotificationService;

    /**
     * 查询通知整改回复记录
     *
     * @param id 主键
     * @return 通知整改回复记录
     */
    @Override
    public HotNoticeReplyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询通知整改回复记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 通知整改回复记录分页列表
     */
    @Override
    public TableDataInfo<HotNoticeReplyVo> queryPageList(HotNoticeReplyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotNoticeReply> lqw = buildQueryWrapper(bo);
        Page<HotNoticeReplyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的通知整改回复记录列表
     *
     * @param bo 查询条件
     * @return 通知整改回复记录列表
     */
    @Override
    public List<HotNoticeReplyVo> queryList(HotNoticeReplyBo bo) {
        LambdaQueryWrapper<HotNoticeReply> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotNoticeReply> buildQueryWrapper(HotNoticeReplyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotNoticeReply> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotNoticeReply::getId);
        lqw.eq(bo.getRelationId() != null, HotNoticeReply::getRelationId, bo.getRelationId());
        lqw.eq(StringUtils.isNotBlank(bo.getReplyContent()), HotNoticeReply::getReplyContent, bo.getReplyContent());
        lqw.eq(StringUtils.isNotBlank(bo.getReplyFiles()), HotNoticeReply::getReplyFiles, bo.getReplyFiles());
        lqw.eq(bo.getReplyTime() != null, HotNoticeReply::getReplyTime, bo.getReplyTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAuditRemark()), HotNoticeReply::getAuditRemark, bo.getAuditRemark());
        lqw.eq(bo.getAuditTime() != null, HotNoticeReply::getAuditTime, bo.getAuditTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAuditBy()), HotNoticeReply::getAuditBy, bo.getAuditBy());
        lqw.eq(bo.getAuditStatus() != null, HotNoticeReply::getAuditStatus, bo.getAuditStatus());
        return lqw;
    }

    /**
     * 新增通知整改回复记录
     *
     * @param bo 通知整改回复记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotNoticeReplyBo bo) {
        HotNoticeReply add = MapstructUtils.convert(bo, HotNoticeReply.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改通知整改回复记录
     *
     * @param bo 通知整改回复记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotNoticeReplyBo bo) {
        HotNoticeReply update = MapstructUtils.convert(bo, HotNoticeReply.class);
        validEntityBeforeUpdate(update);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 修改前的数据校验
     */
    private void validEntityBeforeUpdate(HotNoticeReply entity) {
        //TODO 做一些数据校验,如唯一约束
    }

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

    @Override
    public Boolean submitReply(HotNoticeReplyBo bo) {
        // 1. 校验通知是否存在
        HotAdminNotice notice = hotAdminNoticeMapper.selectById(bo.getRelationId());
        if (notice == null) {
            throw new RuntimeException("关联的通知记录不存在");
        }

        // 2. 新增回复记录
        HotNoticeReply reply = MapstructUtils.convert(bo, HotNoticeReply.class);
        reply.setReplyTime(new Date());
        reply.setAuditStatus(0); // 待审核
        boolean flag = baseMapper.insert(reply) > 0;

        if (flag) {
            bo.setId(reply.getId());
            notice.setStatus(0); // 待审核
            notice.setIsReceived(1L); // 已收到
            if (notice.getReceiveTime() == null) {
                notice.setReceiveTime(new Date());
            }
            notice.setReplyAttachmentUrl(bo.getReplyFiles());
            hotAdminNoticeMapper.updateById(notice);
            pushGovernmentReplyNotification(notice);
        }
        return flag;
    }

    private void pushGovernmentReplyNotification(HotAdminNotice notice) {
        HotNotificationIssue issue = hotNotificationIssueMapper.selectById(notice.getNoticeId());
        if (issue == null) {
            return;
        }
        List<String> receiverIds = listGovernmentReceiverIds(issue.getDistrictCode());
        if (receiverIds.isEmpty()) {
            return;
        }
        HotSystemNotificationGroupBo notificationBo = new HotSystemNotificationGroupBo();
        notificationBo.setLevel("普通");
        notificationBo.setSourceType("通知下发");
        notificationBo.setSenderType("COMPANY");
        notificationBo.setReceiverType("企业回复");
        notificationBo.setReceiverIds(receiverIds);
        notificationBo.setIsDeleted(0L);

        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser != null) {
            if (StringUtils.isNotBlank(loginUser.getBusinessUserId())) {
                try {
                    notificationBo.setSenderId(Long.valueOf(loginUser.getBusinessUserId()));
                } catch (NumberFormatException ignored) {
                }
            }
            notificationBo.setSenderName(loginUser.getUsername());
        }

        SysCompany company = notice.getCompanyId() == null ? null : sysCompanyMapper.selectById(notice.getCompanyId());
        String companyName = company == null ? "" : StringUtils.blankToDefault(company.getCompanyName(), "");
        if (StringUtils.isBlank(notificationBo.getSenderName())) {
            notificationBo.setSenderName(companyName);
        }
        String noticeTitle = StringUtils.blankToDefault(notice.getFileName(), "通知");
        notificationBo.setContent("企业【" + StringUtils.blankToDefault(companyName, "未知企业") + "】已提交通知《" + noticeTitle + "》的整改回复");
        hotSystemNotificationService.insertByBo(notificationBo);
    }

    private List<String> listGovernmentReceiverIds(String districtCode) {
        LinkedHashSet<String> receiverIds = new LinkedHashSet<>();
        receiverIds.add("1");
        if (StringUtils.isBlank(districtCode)) {
            return new ArrayList<>(receiverIds);
        }
        List<HotGovEnterpriseUnit> govUnits = hotGovEnterpriseUnitMapper.selectList(
                Wrappers.<HotGovEnterpriseUnit>lambdaQuery()
                        .eq(HotGovEnterpriseUnit::getUnitType, 1L)
                        .eq(HotGovEnterpriseUnit::getDistrictCode, districtCode)
        );
        if (govUnits == null || govUnits.isEmpty()) {
            return new ArrayList<>(receiverIds);
        }
        receiverIds.addAll(govUnits.stream()
                .map(HotGovEnterpriseUnit::getId)
                .filter(id -> id != null)
                .map(String::valueOf)
                .collect(Collectors.toList()));
        return new ArrayList<>(receiverIds);
    }

    @Override
    public Boolean auditReply(HotNoticeReplyBo bo) {
        // 1. 获取回复记录
        HotNoticeReply reply = baseMapper.selectById(bo.getId());
        if (reply == null) {
            throw new RuntimeException("回复记录不存在");
        }

        // 2. 更新回复记录
        reply.setAuditStatus(bo.getAuditStatus());
        reply.setAuditRemark(bo.getAuditRemark());
        reply.setAuditTime(new Date());
        try {
            reply.setAuditBy(LoginHelper.getLoginUser().getUsername());
        } catch (Exception e) {
            reply.setAuditBy("system");
        }
        boolean flag = baseMapper.updateById(reply) > 0;

        if (flag) {
            HotAdminNotice notice = hotAdminNoticeMapper.selectById(reply.getRelationId());
            if (notice != null) {
                notice.setStatus(bo.getAuditStatus());
                hotAdminNoticeMapper.updateById(notice);
                pushCompanyAuditResultNotification(notice, bo.getAuditStatus(), bo.getAuditRemark());
            }
        }
        return flag;
    }

    private void pushCompanyAuditResultNotification(HotAdminNotice notice, Integer auditStatus, String auditRemark) {
        String receiverId = findCompanyHeadReceiverId(notice.getCompanyId());
        if (StringUtils.isBlank(receiverId)) {
            return;
        }
        HotSystemNotificationGroupBo notificationBo = new HotSystemNotificationGroupBo();
        notificationBo.setLevel("普通");
        notificationBo.setSourceType("行管通知审核");
        notificationBo.setReceiverType("管理员");
        notificationBo.setReceiverId(receiverId);
        notificationBo.setIsDeleted(0L);

        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser != null) {
            String loginPort = loginUser.getLoginPort();
            if (StringUtils.equals(loginPort, ISysUserLoginPortService.GOVERNMENT_PORT)) {
                notificationBo.setSenderType("GOVERNMENT");
            } else {
                notificationBo.setSenderType("SYSTEM");
            }
            notificationBo.setSenderName(loginUser.getUsername());
            if (StringUtils.isNotBlank(loginUser.getBusinessUserId())) {
                try {
                    notificationBo.setSenderId(Long.valueOf(loginUser.getBusinessUserId()));
                } catch (NumberFormatException ignored) {
                }
            }
        } else {
            notificationBo.setSenderType("SYSTEM");
            notificationBo.setSenderName("系统");
        }

        String noticeTitle = StringUtils.blankToDefault(notice.getFileName(), "通知");
        if (auditStatus != null && auditStatus == 1) {
            notificationBo.setContent("您提交的行管通知《" + noticeTitle + "》整改回复已审核通过。");
        } else if (auditStatus != null && auditStatus == 2) {
            String reason = StringUtils.isBlank(auditRemark) ? "无" : auditRemark;
            notificationBo.setContent("您提交的行管通知《" + noticeTitle + "》整改回复已驳回，原因：" + reason);
        } else {
            notificationBo.setContent("您提交的行管通知《" + noticeTitle + "》整改回复审核状态已更新。");
        }
        hotSystemNotificationService.insertByBo(notificationBo);

        HotSystemNotificationGroupBo notificationBo2 = new HotSystemNotificationGroupBo();
        notificationBo2.setLevel("普通");
        notificationBo2.setSourceType("行管通知审核");
        notificationBo2.setReceiverType("政府审核通过");

        notificationBo2.setReceiverIds(List.of("1"));
        notificationBo2.setIsDeleted(0L);

        notificationBo2.setSenderType("GOVERNMENT");

        if (auditStatus != null && auditStatus == 1) {
            notificationBo2.setContent("行管通知《" + noticeTitle + "》整改回复已审核通过。");
        } else if (auditStatus != null && auditStatus == 2) {
            String reason = StringUtils.isBlank(auditRemark) ? "无" : auditRemark;
            notificationBo2.setContent("行管通知《" + noticeTitle + "》整改回复已驳回，原因：" + reason);
        } else {
            notificationBo2.setContent("行管通知《" + noticeTitle + "》整改回复审核状态已更新。");
        }
        hotSystemNotificationService.insertByBo(notificationBo2);
    }

    private String findCompanyHeadReceiverId(Long companyId) {
        if (companyId == null) {
            return null;
        }
        List<HotCompanySafetyManager> heads = hotCompanySafetyManagerMapper.selectList(
                Wrappers.<HotCompanySafetyManager>lambdaQuery()
                        .eq(HotCompanySafetyManager::getCompanyId, companyId)
                        .eq(HotCompanySafetyManager::getCompanyHead, 1L)
                        .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                        .eq(HotCompanySafetyManager::getIsResigned, 0L)
                        .eq(HotCompanySafetyManager::getStatus, 1L)
                        .orderByDesc(HotCompanySafetyManager::getCreateTime)
        );
        if (heads != null && !heads.isEmpty()) {
            return String.valueOf(heads.get(0).getId());
        }
        List<HotCompanySafetyManager> managers = hotCompanySafetyManagerMapper.selectList(
                Wrappers.<HotCompanySafetyManager>lambdaQuery()
                        .eq(HotCompanySafetyManager::getCompanyId, companyId)
                        .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                        .eq(HotCompanySafetyManager::getIsResigned, 0L)
                        .eq(HotCompanySafetyManager::getStatus, 1L)
                        .orderByDesc(HotCompanySafetyManager::getCreateTime)
        );
        if (managers == null || managers.isEmpty()) {
            return null;
        }
        return String.valueOf(managers.get(0).getId());
    }
}
