package org.dromara.zjk.learning_world.service.impl;

import cn.hutool.core.collection.CollectionUtil;
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.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zjk.domain.vo.ZjkExpertVo;
import org.dromara.zjk.enums.PublishStatusEnum;
import org.dromara.zjk.learning_world.domain.vo.ZjkLearningInformationVo;
import org.dromara.zjk.learning_world.mapper.ZjkLearningInformationMapper;
import org.dromara.zjk.mapper.ZjkExpertMapper;
import org.springframework.stereotype.Service;
import org.dromara.zjk.learning_world.domain.bo.ZjkLearningInformationBo;
import org.dromara.zjk.learning_world.domain.entity.ZjkLearningInformation;
import org.dromara.zjk.learning_world.service.IZjkLearningInformationService;

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

/**
 * 资讯Service业务层处理
 *
 * @author ygh
 * @date 2024-11-11
 */
@RequiredArgsConstructor
@Service
public class ZjkLearningInformationServiceImpl implements IZjkLearningInformationService {

    private final ZjkLearningInformationMapper baseMapper;

    private final ZjkExpertMapper expertMapper;


    /**
     * 查询资讯
     *
     * @param id 主键
     * @return 资讯
     */
    @Override
    public ZjkLearningInformationVo queryById(Long id){
        ZjkLearningInformationVo detail = baseMapper.getDetail(id);
        if(detail == null){
            throw new ServiceException("无效帖子id");
        }
        List<ZjkExpertVo> zjkExpertVos = expertMapper.selectByUserIds(Arrays.asList(detail.getUserId()));
        if(CollectionUtil.isEmpty(zjkExpertVos)){
            return detail;
        }
        Map<Long, ZjkExpertVo> userMap = zjkExpertVos.stream().collect(Collectors.toMap(ZjkExpertVo::getUserId, v->v));
            if(userMap.containsKey(detail.getUserId())){
                ZjkExpertVo zjkExpertVo = userMap.get(detail.getUserId());
                detail.setUserName(zjkExpertVo.getUserName());
                detail.setDeptName(zjkExpertVo.getDeptName());
                detail.setPhotograph(zjkExpertVo.getAvatar());
            }
        return detail;
    }

    /**
     * 分页查询资讯列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 资讯分页列表
     */
    @Override
    public TableDataInfo<ZjkLearningInformationVo> queryPageList(ZjkLearningInformationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZjkLearningInformation> lqw = buildQueryWrapper(bo);
        Page<ZjkLearningInformationVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<ZjkLearningInformationVo> records = result.getRecords();
        if(CollectionUtil.isEmpty(records)){
            return TableDataInfo.build(result);
        }
        Set<Long> collect = records.stream().map(ZjkLearningInformationVo::getUserId).collect(Collectors.toSet());
        List<ZjkExpertVo> zjkExpertVos = expertMapper.selectByUserIds(collect);
        if(CollectionUtil.isEmpty(zjkExpertVos)){
            return TableDataInfo.build(result);
        }
        Map<Long, ZjkExpertVo> userMap = zjkExpertVos.stream().collect(Collectors.toMap(ZjkExpertVo::getUserId, v->v));
        for (ZjkLearningInformationVo record : records) {
            if(userMap.containsKey(record.getUserId())){
                ZjkExpertVo zjkExpertVo = userMap.get(record.getUserId());
                record.setUserName(zjkExpertVo.getUserName());
                record.setDeptName(zjkExpertVo.getDeptName());
                record.setPhotograph(zjkExpertVo.getAvatar());
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的资讯列表
     *
     * @param bo 查询条件
     * @return 资讯列表
     */
    @Override
    public List<ZjkLearningInformationVo> queryList(ZjkLearningInformationBo bo) {
        LambdaQueryWrapper<ZjkLearningInformation> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZjkLearningInformation> buildQueryWrapper(ZjkLearningInformationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZjkLearningInformation> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getInformationClassifyId()), ZjkLearningInformation::getInformationClassifyId, bo.getInformationClassifyId());
        lqw.eq(StringUtils.isNotBlank(bo.getInformationImage()), ZjkLearningInformation::getInformationImage, bo.getInformationImage());
        lqw.like(StringUtils.isNotBlank(bo.getInformationTitle()), ZjkLearningInformation::getInformationTitle, bo.getInformationTitle());
        lqw.like(StringUtils.isNotBlank(bo.getInformationDetail()), ZjkLearningInformation::getInformationDetail, bo.getInformationDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ZjkLearningInformation::getStatus, bo.getStatus());
        lqw.eq(bo.getUserId() != null, ZjkLearningInformation::getUserId, bo.getUserId());
        lqw.ge(bo.getStartTime()!=null, ZjkLearningInformation::getCreateTime,bo.getStartTime());
        lqw.le(bo.getEndTime()!=null, ZjkLearningInformation::getCreateTime,bo.getEndTime());
        return lqw;
    }

    /**
     * 新增资讯
     *
     * @param bo 资讯
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ZjkLearningInformationBo bo) {
        ZjkLearningInformation add = MapstructUtils.convert(bo, ZjkLearningInformation.class);
        validEntityBeforeSave(add);
        add.setUserId(LoginHelper.getUserId());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改资讯
     *
     * @param bo 资讯
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ZjkLearningInformationBo bo) {
        ZjkLearningInformation update = MapstructUtils.convert(bo, ZjkLearningInformation.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZjkLearningInformation 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 int updateStatus(ZjkLearningInformationBo bo) {
        Long id = bo.getId();
        ZjkLearningInformation zjkLearningInformation = baseMapper.selectById(id);
        if(zjkLearningInformation==null){
            throw new ServiceException("无效id");
        }
        zjkLearningInformation.setStatus(bo.getStatus());
        zjkLearningInformation.setTakedownTime(new Date());
        return baseMapper.updateById(zjkLearningInformation);
    }

    @Override
    public Long getCount() {
        LambdaQueryWrapper<ZjkLearningInformation> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ZjkLearningInformation::getStatus, PublishStatusEnum.ON.getCode());
        return baseMapper.selectCount(queryWrapper);
    }
}
