package com.cyksj.web.controller.information;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.InformationCategory;
import com.cyksj.model.views.GoodsFrontListView;
import com.cyksj.model.views.InformationDetailView;
import com.cyksj.model.views.InformationListView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.information.InformationCategoryService;
import com.cyksj.service.information.InformationService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zwhui
 * @date 2023/10/12 17:20
 */
@Slf4j
@RestController
@RequestMapping("/applets/information")
@RequiredArgsConstructor
public class InformationController {
    private final BeanSearcher beanSearcher;

    private final InformationCategoryService informationCategoryService;

    private final InformationService informationService;

    private final HttpServletRequest request;

    private final RedisService redisService;

    /**
     * 查询发现页文章列表
     */
    @GetMapping("/get")
    public Result<IPage<InformationListView>> getInformation(Long categoryId, @RequestParam(defaultValue = "0") Integer start, @RequestParam(defaultValue = "5") Integer limit) {
        String key = RedisService.key.INFORMATION_KEY.getName() + String.format(":list:%s:%s", start, limit);
        if (categoryId != null) {
            key += ":ct:" + categoryId;
        }
        IPage<InformationListView> information  = (IPage<InformationListView>) redisService.get(key);
        if (information == null) {
            information = informationService.getInformation(categoryId, start, limit);
            redisService.setNx(key, information, RedisService.key.INFORMATION_KEY.getTimeout() + RandomUtil.randomInt(10000));
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult(information);
    }


    /**
     * 查询分类
     */
    @GetMapping("/get/category")
    public Result<List<InformationCategory>> getInformationCategory() {
        String key = RedisService.key.INFORMATION_KEY.getName() + ":category";
        List<InformationCategory> informationCategory = (List<InformationCategory>) redisService.get(key);
        if (informationCategory == null) {
            informationCategory = informationCategoryService.getInformationCategory();
            if (CollUtil.isEmpty(informationCategory)) {
                return GatewayResponse.SUCCESS.newBuilder().toResult();
            }
            redisService.setNx(key, informationCategory, RedisService.key.INFORMATION_KEY.getTimeout() + RandomUtil.randomInt(100000));
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult(informationCategory);
    }

    /**
     * 获取文章详情
     */
    @GetMapping("/get/detail/{id}")
    public Result<InformationDetailView> getInformation(@PathVariable Long id) {
        String key = RedisService.key.INFORMATION_KEY.getName() + "id:" + id;
        InformationDetailView view = (InformationDetailView) redisService.get(key);
        if (view == null){
            view = beanSearcher.searchFirst(InformationDetailView.class, MapUtils.flatBuilder(request.getParameterMap())
                    .field(InformationDetailView::getId, id).build());
            try {
                List<Long> goodsIds = Jsons.parseList(view.getGoodsIds(), Long.class);
                List<GoodsFrontListView> goodsList = beanSearcher.searchAll(GoodsFrontListView.class, MapUtils.flatBuilder(request.getParameterMap()).field(GoodsFrontListView::getId,goodsIds).op(Operator.InList).build());
                view.setGoods(goodsList);
            } catch (Exception e) {
                e.printStackTrace();
            }
            redisService.setNx(key, view, RedisService.key.INFORMATION_KEY.getTimeout());
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult(view);
    }
}
