package com.hotwj.platform.noticeManagerment.companyNotice.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.companyNotice.domain.HotCompanyNotice;
import com.hotwj.platform.noticeManagerment.companyNotice.domain.HotCompanyNoticeRead;
import com.hotwj.platform.noticeManagerment.companyNotice.domain.bo.HotCompanyNoticeBo;
import com.hotwj.platform.noticeManagerment.companyNotice.domain.vo.HotCompanyNoticeVo;
import com.hotwj.platform.noticeManagerment.companyNotice.mapper.HotCompanyNoticeMapper;
import com.hotwj.platform.noticeManagerment.companyNotice.mapper.HotCompanyNoticeReadMapper;
import com.hotwj.platform.noticeManagerment.companyNotice.service.IHotCompanyNoticeService;
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.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 公司公告Service业务层处理
 *
 * @author shihongwei
 * @date 2026-01-07
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotCompanyNoticeServiceImpl implements IHotCompanyNoticeService {

    private final HotCompanyNoticeMapper baseMapper;
    private final HotCompanyNoticeReadMapper hotCompanyNoticeReadMapper;

    /**
     * 查询公司公告
     *
     * @param id 主键
     * @return 公司公告
     */
    @Override
    public HotCompanyNoticeVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询公司公告列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 公司公告分页列表
     */
    @Override
    public TableDataInfo<HotCompanyNoticeVo> queryPageList(HotCompanyNoticeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotCompanyNotice> lqw = buildQueryWrapper(bo);
        Page<HotCompanyNoticeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的公司公告列表
     *
     * @param bo 查询条件
     * @return 公司公告列表
     */
    @Override
    public List<HotCompanyNoticeVo> queryList(HotCompanyNoticeBo bo) {
        LambdaQueryWrapper<HotCompanyNotice> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public HotCompanyNoticeVo queryLatestUnread() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null || loginUser.getCompanyId() == null) {
            return null;
        }
        String readerId = getReaderId(loginUser);
        if (StringUtils.isBlank(readerId)) {
            return null;
        }
        LambdaQueryWrapper<HotCompanyNotice> lqw = Wrappers.lambdaQuery();
        lqw.eq(HotCompanyNotice::getCompanyId, loginUser.getCompanyId());
        lqw.eq(HotCompanyNotice::getIsPublished, 1L);
        lqw.apply("NOT EXISTS (SELECT 1 FROM hot_company_notice_read r WHERE r.notice_id = hot_company_notice.id AND r.reader_id = {0} AND r.is_deleted = 0)", readerId);
        lqw.orderByDesc(HotCompanyNotice::getIsTop);
        lqw.orderByDesc(HotCompanyNotice::getCreateTime);
        lqw.orderByDesc(HotCompanyNotice::getId);
        lqw.last("limit 1");
        HotCompanyNotice notice = baseMapper.selectOne(lqw);
        if (notice == null) {
            return null;
        }
        return baseMapper.selectVoById(notice.getId());
    }

    private LambdaQueryWrapper<HotCompanyNotice> buildQueryWrapper(HotCompanyNoticeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotCompanyNotice> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(HotCompanyNotice::getCreateTime);
        Object beginTime = params.get("beginTime");
        Object endTime = params.get("endTime");
        if (beginTime != null && endTime != null) {
            lqw.between(HotCompanyNotice::getCreateTime, beginTime, endTime);
        } else if (beginTime != null) {
            lqw.ge(HotCompanyNotice::getCreateTime, beginTime);
        } else if (endTime != null) {
            lqw.le(HotCompanyNotice::getCreateTime, endTime);
        }
        lqw.eq(bo.getCompanyId() != null, HotCompanyNotice::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), HotCompanyNotice::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getAuthor()), HotCompanyNotice::getAuthor, bo.getAuthor());
        lqw.eq(StringUtils.isNotBlank(bo.getCoverImage()), HotCompanyNotice::getCoverImage, bo.getCoverImage());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), HotCompanyNotice::getContent, bo.getContent());
        lqw.eq(bo.getSortNo() != null, HotCompanyNotice::getSortNo, bo.getSortNo());
        lqw.eq(bo.getIsTop() != null, HotCompanyNotice::getIsTop, bo.getIsTop());
        lqw.eq(bo.getIsPublished() != null, HotCompanyNotice::getIsPublished, bo.getIsPublished());
        lqw.eq(bo.getIsDeleted() != null, HotCompanyNotice::getIsDeleted, bo.getIsDeleted());
        lqw.eq(bo.getNoticeType() != null, HotCompanyNotice::getNoticeType, bo.getNoticeType());
        return lqw;
    }

    /**
     * 新增公司公告
     *
     * @param bo 公司公告
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotCompanyNoticeBo bo) {
        HotCompanyNotice add = MapstructUtils.convert(bo, HotCompanyNotice.class);
        // 获取当前公司最大的排序号
        HotCompanyNotice maxSortNotice = baseMapper.selectOne(new LambdaQueryWrapper<HotCompanyNotice>()
            .select(HotCompanyNotice::getSortNo)
            .eq(HotCompanyNotice::getCompanyId, bo.getCompanyId())
            .orderByDesc(HotCompanyNotice::getSortNo)
            .last("limit 1"));
        long maxSort = (maxSortNotice != null && maxSortNotice.getSortNo() != null) ? maxSortNotice.getSortNo() : 0L;
        add.setSortNo(maxSort + 1);

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

    /**
     * 修改公司公告
     *
     * @param bo 公司公告
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotCompanyNoticeBo bo) {
        HotCompanyNotice update = MapstructUtils.convert(bo, HotCompanyNotice.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean markRead(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null || loginUser.getCompanyId() == null) {
            return false;
        }
        String readerId = getReaderId(loginUser);
        if (StringUtils.isBlank(readerId)) {
            return false;
        }
        HotCompanyNotice notice = baseMapper.selectOne(Wrappers.lambdaQuery(HotCompanyNotice.class)
                .eq(HotCompanyNotice::getId, id)
                .eq(HotCompanyNotice::getCompanyId, loginUser.getCompanyId())
                .eq(HotCompanyNotice::getIsPublished, 1L));
        if (notice == null) {
            return false;
        }
        Long existCount = hotCompanyNoticeReadMapper.selectCount(Wrappers.lambdaQuery(HotCompanyNoticeRead.class)
                .eq(HotCompanyNoticeRead::getNoticeId, id)
                .eq(HotCompanyNoticeRead::getReaderId, readerId));
        if (existCount != null && existCount > 0) {
            return true;
        }
        HotCompanyNoticeRead read = new HotCompanyNoticeRead();
        read.setNoticeId(id);
        read.setCompanyId(loginUser.getCompanyId());
        read.setReaderId(readerId);
        read.setReadTime(new Date());
        return hotCompanyNoticeReadMapper.insert(read) > 0;
    }

    private String getReaderId(LoginUser loginUser) {
        return loginUser.getUserId() == null ? null : String.valueOf(loginUser.getUserId());
    }

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

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