package com.liquidnet.service.platform.controller.goblin.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.candy.entity.CandyMgtCoupon;
import com.liquidnet.service.goblin.entity.GoblinGoods;
import com.liquidnet.service.platform.service.impl.goblin.PlatformGoblinGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商城商品任务处理
 *
 * @author zhanggb
 * Created by IntelliJ IDEA at 2022/1/21
 */
@Slf4j
@RestController
@RequestMapping("ggoods/task")
public class PlatformGoblinGoodsTaskController {
    @Autowired
    private PlatformGoblinGoodsService platformGoblinGoodsService;

    @PutMapping("onshelves")
    public ResponseDto<String> ggoodsOnShelvesHandler() {
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<GoblinGoods> queryWrapper = Wrappers.lambdaQuery(GoblinGoods.class);
        queryWrapper.eq(GoblinGoods::getDelFlg, "0");
        queryWrapper.eq(GoblinGoods::getStatus, "3");
        queryWrapper.eq(GoblinGoods::getSpuAppear, "0");
        queryWrapper.eq(GoblinGoods::getShelvesHandle, "3");
        queryWrapper.le(GoblinGoods::getShelvesTime, now);
//        queryWrapper.eq(GoblinGoods::getShelvesStatus, "0");
        queryWrapper.in(GoblinGoods::getShelvesStatus, "0", "1");
        queryWrapper.orderByAsc(GoblinGoods::getShelvesTime);
        queryWrapper.select(GoblinGoods::getSpuId);

        List<GoblinGoods> goodsList = platformGoblinGoodsService.list(queryWrapper);
        boolean empty = CollectionUtils.isEmpty(goodsList);
        int totalCount = empty ? 0 : goodsList.size();
        if (!empty) {
            List<String> spuIdList = goodsList.stream().map(GoblinGoods::getSpuId).collect(Collectors.toList());

            try {
                platformGoblinGoodsService.shelvesProcessing(spuIdList);
            } catch (Exception e) {
                log.error("Ex.商品上架处理[totalCount={},spuIdList={}],{}", totalCount, JsonUtils.toJson(spuIdList), e.getMessage());
                return ResponseDto.failure(String.format("商品上架处理失败[totalCount=%s]", totalCount));
            }
        }
        return ResponseDto.success(String.format("商品上架处理成功[totalCount=%s]", totalCount));
    }
}
