package cn.stylefeng.team.portal.modular.management.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.entity.BaseEntity;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.file.api.FileBusinessApi;
import cn.stylefeng.roses.kernel.file.api.pojo.response.SysFileInfoResponse;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.stat.api.ClickCountCalcApi;
import cn.stylefeng.roses.kernel.stat.api.ClickStatusCalcApi;
import cn.stylefeng.team.portal.api.enums.NewsTypeEnum;
import cn.stylefeng.team.portal.modular.management.entity.PortalNews;
import cn.stylefeng.team.portal.modular.management.enums.PortalNewsExceptionEnum;
import cn.stylefeng.team.portal.modular.management.factory.NewsFactory;
import cn.stylefeng.team.portal.modular.management.mapper.PortalNewsMapper;
import cn.stylefeng.team.portal.modular.management.pojo.request.PortalNewsRequest;
import cn.stylefeng.team.portal.modular.management.service.PortalNewsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.stylefeng.team.portal.api.constants.PortalConstants.FILE_BUSINESS_NEWS_CODE;

@Service
public class PortalNewsServiceImpl extends ServiceImpl<PortalNewsMapper, PortalNews> implements PortalNewsService {

    @Resource
    private FileBusinessApi fileBusinessApi;

    @Resource
    private ClickCountCalcApi clickCountCalcApi;

    @Resource
    private ClickStatusCalcApi clickStatusCalcApi;

    @Override
    public void add(PortalNewsRequest portalNewsRequest) {

        this.validateParam(portalNewsRequest, false);

        PortalNews portalNews = new PortalNews();
        portalNews.setNewsId(IdWorker.getId());
        NewsFactory.commonFillParam(portalNewsRequest, portalNews);

        if (ObjectUtil.isNotEmpty(portalNewsRequest.getFileIdList())) {
            fileBusinessApi.addFileBusinessBind(FILE_BUSINESS_NEWS_CODE, portalNews.getNewsId(), portalNewsRequest.getFileIdList());
        }

        this.save(portalNews);
    }

    @Override
    public void del(PortalNewsRequest portalNewsRequest) {
        PortalNews portalNews = this.queryPortalNews(portalNewsRequest);
        this.removeById(portalNews.getNewsId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(PortalNewsRequest portalNewsRequest) {
        this.removeByIds(portalNewsRequest.getBatchDeleteIdList());
    }

    @Override
    public void edit(PortalNewsRequest portalNewsRequest) {

        this.validateParam(portalNewsRequest, true);

        PortalNews oldNews = this.queryPortalNews(portalNewsRequest);
        NewsFactory.commonFillParam(portalNewsRequest, oldNews);

        fileBusinessApi.removeBusinessIdFileList(FILE_BUSINESS_NEWS_CODE, oldNews.getNewsId());
        if (ObjectUtil.isNotEmpty(portalNewsRequest.getFileIdList())) {
            fileBusinessApi.addFileBusinessBind(FILE_BUSINESS_NEWS_CODE, oldNews.getNewsId(), portalNewsRequest.getFileIdList());
        }

        this.updateById(oldNews);
    }

    @Override
    public PortalNews detail(PortalNewsRequest portalNewsRequest) {

        PortalNews portalNews = this.queryPortalNews(portalNewsRequest);

        List<SysFileInfoResponse> businessFileInfoList = fileBusinessApi.getBusinessFileInfoList(portalNews.getBusinessId());
        portalNews.setBusinessFileInfoList(businessFileInfoList);

        Long clickCount = clickCountCalcApi.addOneClickCount(portalNews);
        clickStatusCalcApi.addClickStatus(portalNews);

        portalNews.setClickCount(clickCount);

        return portalNews;
    }

    @Override
    public PageResult<PortalNews> findPage(PortalNewsRequest portalNewsRequest) {

        LambdaQueryWrapper<PortalNews> wrapper = createWrapper(portalNewsRequest);

        wrapper.select(PortalNews::getNewsId, PortalNews::getNewsTitle, PortalNews::getNewsStatus,
                PortalNews::getShowPublishTime, PortalNews::getShowPublishUser,
                PortalNews::getNewsTopFlag, PortalNews::getNewsSort, BaseEntity::getCreateTime);

        Page<PortalNews> pageList = this.page(PageFactory.defaultPage(), wrapper);
        List<PortalNews> records = pageList.getRecords();
        if(ObjectUtil.isEmpty(records)){
            return PageResultFactory.createPageResult(pageList);
        }

        clickStatusCalcApi.calcClickStatus(records);

        return PageResultFactory.createPageResult(pageList);
    }

    @Override
    public Map<Long, String> getNewsNameMap(List<Long> newsIdList) {

        if (ObjectUtil.isEmpty(newsIdList)) {
            return new HashMap<>();
        }

        LambdaQueryWrapper<PortalNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PortalNews::getNewsId, newsIdList);
        queryWrapper.select(PortalNews::getNewsId, PortalNews::getNewsTitle);
        List<PortalNews> portalNews = this.list(queryWrapper);

        return portalNews.stream().collect(Collectors.toMap(PortalNews::getNewsId, PortalNews::getNewsTitle));
    }

    @Override
    public List<PortalNews> getSelect(PortalNewsRequest portalNewsRequest) {
        LambdaQueryWrapper<PortalNews> wrapper = createWrapper(portalNewsRequest);

        wrapper.select(PortalNews::getNewsId, PortalNews::getNewsTitle, PortalNews::getNewsStatus,
                PortalNews::getShowPublishTime, PortalNews::getShowPublishUser,
                PortalNews::getNewsTopFlag, PortalNews::getNewsSort, BaseEntity::getCreateTime);

        return this.list(wrapper);
    }

    private PortalNews queryPortalNews(PortalNewsRequest portalNewsRequest) {
        PortalNews portalNews = this.getById(portalNewsRequest.getNewsId());
        if (ObjectUtil.isEmpty(portalNews)) {
            throw new ServiceException(PortalNewsExceptionEnum.PORTAL_NEWS_NOT_EXISTED);
        }
        return portalNews;
    }

    private LambdaQueryWrapper<PortalNews> createWrapper(PortalNewsRequest portalNewsRequest) {
        LambdaQueryWrapper<PortalNews> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(PortalNews::getDesignId, portalNewsRequest.getDesignId());

        String searchText = portalNewsRequest.getSearchText();
        if (StrUtil.isNotBlank(searchText)) {
            queryWrapper.like(PortalNews::getNewsTitle, searchText);
        }

        Long newsCategoryId = portalNewsRequest.getNewsCategoryId();
        if (ObjectUtil.isNotEmpty(newsCategoryId)) {
            queryWrapper.eq(PortalNews::getNewsCategoryId, newsCategoryId);
        }

        Integer newsStatus = portalNewsRequest.getNewsStatus();
        if (ObjectUtil.isNotEmpty(newsStatus)) {
            queryWrapper.eq(PortalNews::getNewsStatus, newsStatus);
        }

        queryWrapper.orderByDesc(PortalNews::getNewsTopFlag);
        queryWrapper.orderByAsc(PortalNews::getNewsSort);
        queryWrapper.orderByDesc(BaseEntity::getCreateTime);

        return queryWrapper;
    }

    private void validateParam(PortalNewsRequest portalNewsRequest, boolean isEdit) {

        if (NewsTypeEnum.ITEM_20.getCode().equals(portalNewsRequest.getNewsType())) {
            if (ObjectUtil.isEmpty(portalNewsRequest.getLinkUrl())) {
                throw new ServiceException(PortalNewsExceptionEnum.LINK_URL_IS_EMPTY);
            }
        }

        if (NewsTypeEnum.ITEM_10.getCode().equals(portalNewsRequest.getNewsType())) {
            if (ObjectUtil.isEmpty(portalNewsRequest.getNewsContent())) {
                throw new ServiceException(PortalNewsExceptionEnum.NEWS_CONTENT_IS_EMPTY);
            }
        }

        LambdaQueryWrapper<PortalNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PortalNews::getNewsTitle, portalNewsRequest.getNewsTitle());
        if (isEdit) {
            wrapper.ne(PortalNews::getNewsId, portalNewsRequest.getNewsId());
        }
        if (this.count(wrapper) > 0) {
            throw new ServiceException(PortalNewsExceptionEnum.PORTAL_NEWS_NAME_REPEAT);
        }
    }

}
