package com.hotwj.platform.noticeManagerment.notificationIssue.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.notificationIssue.domain.HotNotificationIssue;
import com.hotwj.platform.noticeManagerment.notificationIssue.domain.bo.HotNotificationIssueBo;
import com.hotwj.platform.noticeManagerment.notificationIssue.domain.vo.HotNotificationIssueVo;
import com.hotwj.platform.noticeManagerment.notificationIssue.mapper.HotNotificationIssueMapper;
import com.hotwj.platform.noticeManagerment.notificationIssue.service.IHotNotificationIssueService;
import com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService;
import com.hotwj.platform.resourceManagement.govEnterpriseUnit.domain.vo.HotGovEnterpriseUnitVo;
import com.hotwj.platform.resourceManagement.govEnterpriseUnit.service.IHotGovEnterpriseUnitService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
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.Collection;
import java.util.List;
import java.util.Map;

/**
 * 通知下发Service业务层处理
 *
 * @author shihongwei
 * @date 2026-01-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotNotificationIssueServiceImpl implements IHotNotificationIssueService {

    private final HotNotificationIssueMapper baseMapper;
    private final IHotGovEnterpriseUnitService hotGovEnterpriseUnitService;

    /**
     * 查询通知下发
     *
     * @param id 主键
     * @return 通知下发
     */
    @Override
    public HotNotificationIssueVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询通知下发列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 通知下发分页列表
     */
    @Override
    public TableDataInfo<HotNotificationIssueVo> queryPageList(HotNotificationIssueBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotNotificationIssue> lqw = buildQueryWrapper(bo);
        Page<HotNotificationIssueVo> result = baseMapper.selectPageList(pageQuery.build(), lqw);
        for (HotNotificationIssueVo vo : result.getRecords()) {
            long read = vo.getReadCount() == null ? 0L : vo.getReadCount();
            long total = vo.getTotalCount() == null ? 0L : vo.getTotalCount();
            StringBuilder sb = new StringBuilder();
            sb.append("已读: ").append(read).append("/").append(total);
            // 如果有审核通过的数据，或者有截止日期（说明是整改类通知）
            if (StringUtils.isNotBlank(vo.getDeadline()) || (vo.getPassCount() != null && vo.getPassCount() > 0)) {
                sb.append("，审核通过: ").append(vo.getPassCount() == null ? 0L : vo.getPassCount());
            }
            vo.setDistributionStatus(sb.toString());
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的通知下发列表
     *
     * @param bo 查询条件
     * @return 通知下发列表
     */
    @Override
    public List<HotNotificationIssueVo> queryList(HotNotificationIssueBo bo) {
        LambdaQueryWrapper<HotNotificationIssue> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotNotificationIssue> buildQueryWrapper(HotNotificationIssueBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotNotificationIssue> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotNotificationIssue::getId);
        lqw.like(StringUtils.isNotBlank(bo.getFileName()), HotNotificationIssue::getFileName, bo.getFileName());
        lqw.eq(bo.getNotifyType() != null, HotNotificationIssue::getNotifyType, bo.getNotifyType());
        lqw.eq(StringUtils.isNotBlank(bo.getAttachmentUrl()), HotNotificationIssue::getAttachmentUrl, bo.getAttachmentUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getProvinceCode()), HotNotificationIssue::getProvinceCode, bo.getProvinceCode());
        lqw.eq(StringUtils.isNotBlank(bo.getCityCode()), HotNotificationIssue::getCityCode, bo.getCityCode());
        lqw.eq(StringUtils.isNotBlank(bo.getDistrictCode()), HotNotificationIssue::getDistrictCode, bo.getDistrictCode());
        lqw.like(StringUtils.isNotBlank(bo.getAreaName()), HotNotificationIssue::getAreaName, bo.getAreaName());
        lqw.eq(bo.getIsDeleted() != null, HotNotificationIssue::getIsDeleted, bo.getIsDeleted());

        // 权限过滤逻辑
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser != null) {
            if (ISysUserLoginPortService.GOVERNMENT_PORT.equals(loginUser.getLoginPort())) {
                // 政府端：只能查看政府下发的，且通过区划代码过滤
                HotGovEnterpriseUnitVo unitVo = hotGovEnterpriseUnitService.queryById(loginUser.getCompanyId());
                if (unitVo != null) {
                    lqw.eq(HotNotificationIssue::getDistrictCode, unitVo.getDistrictCode());
                } else {
                    // 查不到单位信息，什么都不返回
                    lqw.eq(HotNotificationIssue::getId, -1L);
                }
            }
        }

        return lqw;
    }

    /**
     * 新增通知下发
     *
     * @param bo 通知下发
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotNotificationIssueBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("未登录用户无法操作");
        }

        HotNotificationIssue add = MapstructUtils.convert(bo, HotNotificationIssue.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改通知下发
     *
     * @param bo 通知下发
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotNotificationIssueBo bo) {
        HotNotificationIssue update = MapstructUtils.convert(bo, HotNotificationIssue.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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