package com.mortals.xhx.module.news.service.impl;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.module.favorites.model.FavoritesNewsEntity;
import com.mortals.xhx.module.favorites.model.FavoritesNewsQuery;
import com.mortals.xhx.module.favorites.service.FavoritesNewsService;
import com.mortals.xhx.module.news.model.*;
import com.mortals.xhx.module.news.service.NewsRecordService;
import com.mortals.xhx.module.news.service.NewsShareService;
import com.mortals.xhx.module.news.service.NewsUpService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.news.dao.NewsDao;
import com.mortals.xhx.module.news.service.NewsService;
import lombok.extern.slf4j.Slf4j;

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

/**
* NewsService
* 新闻 service实现
*
* @author zxfei
* @date 2023-09-18
*/
@Service("newsService")
@Slf4j
public class NewsServiceImpl extends AbstractCRUDServiceImpl<NewsDao, NewsEntity, Long> implements NewsService {

    @Autowired
    private NewsShareService newsShareService;
    @Autowired
    private NewsRecordService newsRecordService;
    @Autowired
    private NewsUpService newsUpService;
    @Autowired
    private UserService userService;
    @Autowired
    private FavoritesNewsService favoritesNewsService;

    @Value("${domain.name:https://oa.xinhx.co}")
    private String domain;

    @Override
    protected void findAfter(NewsEntity params, PageInfo pageInfo, Context context, List<NewsEntity> list) throws AppException {
        if(CollectionUtils.isNotEmpty(list)){
            String regex = "src=\"file";
            String replacement;
            if(domain.endsWith("/")){
                replacement = "src=\"" + domain + "file";
            }else {
                replacement = "src=\"" + domain + "/file";
            }

            List<Long> userIdList = list.stream().map(NewsEntity::getCreateUserId).collect(Collectors.toList());
            List<UserEntity> userList = userService.find(new UserQuery().idList(userIdList));
            Map<Long,UserEntity> userMap = userList.parallelStream().collect(Collectors.toMap(x -> x.getId(), z -> z, (o, n) -> n));
            if(context!=null && context.getUser()!=null){
                List<Long> newsIdList = list.stream().map(NewsEntity::getId).collect(Collectors.toList());
                List<NewsUpEntity> upList = newsUpService.find(new NewsUpQuery().newsIdList(newsIdList).upId(context.getUser().getId()));
                Map<Long,NewsUpEntity> upMap = new HashMap<>();
                if(CollectionUtils.isNotEmpty(upList)){
                    upMap = upList.parallelStream().collect(Collectors.toMap(x -> x.getNewsId(), z -> z, (o, n) -> n));
                }
                List<NewsShareEntity> shareList = newsShareService.find(new NewsShareQuery().newsIdList(newsIdList).createUserId(context.getUser().getId()));
                Map<Long,NewsShareEntity> shareMap = new HashMap<>();
                if(CollectionUtils.isNotEmpty(shareList)) {
                    shareMap = shareList.parallelStream().collect(Collectors.toMap(x -> x.getId(), z -> z, (o, n) -> n));
                }
                for(NewsEntity item:list){
                    if(upMap.containsKey(item.getId())){
                        item.setUpStatus(1);
                    }else {
                        item.setUpStatus(0);
                    }
                    if(shareMap.containsKey(item.getId())){
                        item.setShareStatus(1);
                    }else {
                        item.setShareStatus(0);
                    }
                    UserEntity userEntity = userMap.get(item.getCreateUserId());
                    if(userEntity!=null) {
                        item.setPhotoPath(userEntity.getPhotoPath());
                    }
                    if(StringUtils.isNotEmpty(item.getContent())) {
                        item.setContent(item.getContent().replaceAll(regex, replacement));
                    }
                }
            }else {
                for(NewsEntity item:list){
                    if(StringUtils.isNotEmpty(item.getContent())) {
                        item.setContent(item.getContent().replaceAll(regex, replacement));
                    }
                }
            }
        }
    }

    @Override
    public NewsEntity get(Long key, Context context) throws AppException {
        NewsEntity entity = this.dao.get(key);
        if(entity!=null){
            String regex = "src=\"file";
            String replacement;
            if(domain.endsWith("/")){
                replacement = "src=\"" + domain + "file";
            }else {
                replacement = "src=\"" + domain + "/file";
            }
            if(StringUtils.isNotEmpty(entity.getContent())) {
                entity.setContent(entity.getContent().replaceAll(regex, replacement));
            }
            if(context!=null && context.getUser()!=null){
                UserEntity userEntity = userService.get(context.getUser().getId());
                if(userEntity!=null){
                    NewsShareEntity newsShareEntity = newsShareService.selectOne(new NewsShareQuery().newsId(key).createUserId(userEntity.getId()));
                    NewsUpEntity newsUpEntity = newsUpService.selectOne(new NewsUpQuery().newsId(key).upId(userEntity.getId()));
                    if(newsShareEntity!=null){
                        entity.setShareStatus(1);
                    }else {
                        entity.setShareStatus(0);
                    }
                    if(newsUpEntity!=null){
                        entity.setUpStatus(1);
                    }else {
                        entity.setUpStatus(0);
                    }
                    FavoritesNewsEntity favoritesNewsEntity = favoritesNewsService.selectOne(new FavoritesNewsQuery().newsId(key).userId(userEntity.getId()));
                    if(favoritesNewsEntity!=null){
                        entity.setFavoriteStatus(1);
                    }else {
                        entity.setFavoriteStatus(0);
                    }
                }else {
                    entity.setShareStatus(0);
                    entity.setUpStatus(0);
                }
            }
        }
        return entity;
    }

    @Override
    public NewsEntity upNews(Long id, Context context, int increment) throws AppException {
        NewsEntity news = this.get(id);
        if(news==null){
            throw new AppException("新闻不存在");
        }
        if(context!=null && context.getUser()!=null) {
            NewsUpEntity newsUpEntity = newsUpService.selectOne(new NewsUpQuery().newsId(id).upId(context.getUser().getId()));
            if(newsUpEntity!=null){
                if(increment < 0){
                    newsUpService.remove(newsUpEntity.getId(),context);
                }else {
                    NewsUpQuery updateUp = new NewsUpQuery();
                    updateUp.setId(newsUpEntity.getId());
                    updateUp.setSumUpIncrement(increment);
                    updateUp.setUpTime(new Date());
                    updateUp.setUpdateTime(new Date());
                    updateUp.setUpdateUserId(context.getUser().getId());
                    newsUpService.update(updateUp);
                }
            }else {
                if(increment > 0) {
                    newsUpEntity = new NewsUpEntity();
                    newsUpEntity.initAttrValue();
                    newsUpEntity.setNewsId(id);
                    newsUpEntity.setUpId(context.getUser().getId());
                    newsUpEntity.setUpName(context.getUser().getRealName());
                    newsUpEntity.setUpTime(new Date());
                    newsUpEntity.setCreateTime(new Date());
                    newsUpEntity.setCreateUserId(context.getUser().getId());
                    newsUpEntity.setSumUp(increment);
                    newsUpService.save(newsUpEntity);
                }
            }
        }
        NewsQuery update = new NewsQuery();
        update.setId(id);
        if(news.getUpNums()==0 && increment<0){
            update.setUpNumsIncrement(0);
        }else {
            update.setUpNumsIncrement(increment);
        }
        return this.update(update);
    }

    @Override
    public NewsEntity viewNews(Long id, Context context) throws AppException {
        NewsEntity news = this.get(id);
        if(news==null){
            throw new AppException("新闻不存在");
        }
        if(context!=null && context.getUser()!=null) {
            NewsRecordEntity newsRecordEntity = newsRecordService.selectOne(new NewsRecordQuery().newsId(id).viewId(context.getUser().getId()));
            if(newsRecordEntity!=null){
                NewsRecordQuery updateRecord = new NewsRecordQuery();
                updateRecord.setId(newsRecordEntity.getId());
                updateRecord.setSumViewsIncrement(1);
                updateRecord.setViewTime(new Date());
                updateRecord.setUpdateTime(new Date());
                updateRecord.setUpdateUserId(context.getUser().getId());
                newsRecordService.update(updateRecord);
            }else {
                newsRecordEntity = new NewsRecordEntity();
                newsRecordEntity.initAttrValue();
                newsRecordEntity.setNewsId(id);
                newsRecordEntity.setViewId(context.getUser().getId());
                newsRecordEntity.setViewName(context.getUser().getRealName());
                newsRecordEntity.setCreateTime(new Date());
                newsRecordEntity.setCreateUserId(context.getUser().getId());
                newsRecordEntity.setSumViews(1);
                newsRecordService.save(newsRecordEntity);
            }
        }
        NewsQuery update = new NewsQuery();
        update.setId(id);
        update.setViewNumsIncrement(1);
        return this.update(update);
    }

    @Override
    public NewsEntity shareNews(Long id, Context context) throws AppException {
        NewsEntity news = this.get(id);
        if(news==null){
            throw new AppException("新闻不存在");
        }
        if(context!=null && context.getUser()!=null) {
            NewsShareEntity newsShareEntity = newsShareService.selectOne(new NewsShareQuery().newsId(id).createUserId(context.getUser().getId()));
            if(newsShareEntity!=null){
                NewsShareQuery updateShare = new NewsShareQuery();
                updateShare.setId(id);
                updateShare.setSumSharesIncrement(1);
                updateShare.setUpdateTime(new Date());
                updateShare.setUpdateUserId(context.getUser().getId());
                newsShareService.update(updateShare);
            }else {
                newsShareEntity = new NewsShareEntity();
                newsShareEntity.initAttrValue();
                newsShareEntity.setNewsId(id);
                newsShareEntity.setSumShares(1);
                newsShareEntity.setShareName(context.getUser().getRealName());
                newsShareEntity.setCreateTime(new Date());
                newsShareEntity.setCreateUserId(context.getUser().getId());
                newsShareService.save(newsShareEntity);
            }
        }
        NewsQuery update = new NewsQuery();
        update.setId(id);
        update.setShareNumsIncrement(1);
        return this.update(update);
    }

}