package com.caimei.www.service.page.impl;

import com.caimei.www.mapper.ArticleDao;
import com.caimei.www.pojo.JsonModel;
import com.caimei.www.pojo.page.Article;
import com.caimei.www.pojo.page.BaseLink;
import com.caimei.www.pojo.page.ImageLink;
import com.caimei.www.service.page.ArticleService;
import com.caimei.www.service.redis.RedisService;
import com.caimei.www.utils.ImageUtil;
import com.caimei.www.utils.PriceUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * Description
 *
 * @author : Charles
 * @date : 2020/8/10
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Value("${caimei.wwwDomain}")
    private String domain;
    @Resource
    private ArticleDao articleDao;
    @Resource
    private RedisService redisService;

    /**
     * 获取文章类型
     */
    @Override
    public List<BaseLink> getArticleTypes() {
        return articleDao.getArticleTypes();
    }

    /**
     * 获取文章热门标签
     */
    @Override
    public JsonModel<List<BaseLink>> getArticleLabels() {
        // 获取最高点击量
        Integer topClickRate = articleDao.getTopClickRate();
        // 获取热门标签
        List<BaseLink> labels = articleDao.getArticleLabels();
        double opacityParam = 0.5f;
        labels.forEach(label -> {
            double opacity = PriceUtil.mul(PriceUtil.div(label.getSort(), topClickRate), (1 - opacityParam)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + opacityParam;
            label.setSort(opacity);
        });
        return JsonModel.success(labels);
    }

    /**
     * 获取文章推荐
     *
     * @param typeId
     * @param pageNum
     */
    @Override
    public JsonModel<PageInfo<ImageLink>> getArticleRecommended(Integer typeId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ImageLink> recommended = articleDao.getArticleRecommended(typeId);
        recommended.forEach(item -> {
            item.setImage(ImageUtil.getImageURL("", item.getImage(), 0, domain));
        });
        PageInfo<ImageLink> pageInfo = new PageInfo(recommended);
        return JsonModel.success(pageInfo);
    }

    /**
     * 获取相关文章
     *
     * @param id
     * @param labels
     * @param pageNum
     * @param pageSize
     */
    @Override
    public JsonModel<PageInfo<Article>> getArticleRelated(Integer id, String labels, int pageNum, int pageSize) {
        String[] labelArr = labels.split(",");
        PageHelper.startPage(pageNum, pageSize);
        List<Article> relateds = articleDao.getArticleRelated(id, labelArr);
        relateds.forEach(item -> {
            item.setImage(ImageUtil.getImageURL("", item.getImage(), 0, domain));
        });
        PageInfo<Article> pageInfo = new PageInfo(relateds);
        return JsonModel.success(pageInfo);
    }

    /**
     * 获取文章广告
     */
    @Override
    public JsonModel<List<ImageLink>> getLastestInfoAds() {
        List<ImageLink> adList = articleDao.getLastestInfoADs();
        return JsonModel.success(adList);
    }

    /**
     * 点击标签
     */
    @Override
    public JsonModel clickArticleLabel(Integer id) {
        articleDao.clickArticleLabel(id);
        return JsonModel.success();
    }

    /**
     * 点击广告
     */
    @Override
    public JsonModel clickArticleAd(Integer id) {
        articleDao.clickArticleAd(id);
        return JsonModel.success();
    }

    @Override
    public Article getArticleInfo(Integer id) {
        Article articleInfo = articleDao.getArticleInfo(id);
        if (articleInfo != null) {
            String[] labels = articleInfo.getLabel().split(",");
            if(labels.length > 0){
                boolean notEmpty = StringUtil.isNotEmpty(labels[0]);
                if(notEmpty){
                    List<Integer> labelIdList = articleDao.findLabelIdsByName(labels);
                    Integer[] labelIds = labelIdList.toArray(new Integer[labels.length]);
                    articleInfo.setLabels(labels);
                    articleInfo.setLabelIds(labelIds);
                }
            }
        }
        return articleInfo;
    }

    /**
     * 文章点赞
     *
     * @param id
     * @return
     */
    @Override
    public JsonModel articleLike(Integer id, ServerWebExchange serverWebExchange) {
        String ip = getIp(serverWebExchange);
        String key = "ip_" + ip + "_" + id;
        if(redisService.exists(key)) {
            return JsonModel.success(1,"您已经给该文章点过赞了","");
        } else {
            articleDao.articleLike(id);
            // 限制一个ip24小时内只能点一次赞
            redisService.set(key, 1, 24 * 60 * 60L);
            return JsonModel.success();
        }
    }

    private String getIp(ServerWebExchange serverWebExchange){
       ServerHttpRequest request = serverWebExchange.getRequest();
        return Objects.requireNonNull(request.getRemoteAddress()).getAddress().toString();
    }

}
