
package com.tmerclub.cloud.coupon.controller.app;

import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.coupon.constant.PutOnStatus;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.product.dto.ProductSearchDTO;
import com.tmerclub.cloud.common.product.vo.search.ProductSearchVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.coupon.constant.CouponStatus;
import com.tmerclub.cloud.coupon.constant.SuitableProdType;
import com.tmerclub.cloud.coupon.manager.CouponStockManager;
import com.tmerclub.cloud.coupon.service.CouponService;
import com.tmerclub.cloud.coupon.service.CouponUserService;
import com.tmerclub.cloud.coupon.vo.CouponAppVO;
import com.tmerclub.cloud.coupon.vo.CouponVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * 优惠券
 *
 * @author YXF
 * @date 2020-12-08 17:22:56
 */
@RestController("appCouponController")
@RequestMapping("/ma/coupon")
@Tag(name = "app-优惠券")
public class CouponController {

    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private CouponStockManager couponStockManager;


    @GetMapping("/platformCouponList")
    @Operation(summary = "平台优惠券列表(领券中心, 访客接口)", description = "平台优惠券列表")
    public ServerResponseEntity<List<CouponAppVO>> platformCouponList() {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        Long userId = null;
        if (Objects.nonNull(uidInfoBO)) {
            userId = uidInfoBO.getUserId();
        }
        return ServerResponseEntity.success(couponService.generalCouponList(userId));
    }

    @GetMapping("/getCouponPage")
    @Operation(summary = "店铺商品券列表(领券中心, 访客接口)", description = "获取店铺商品券列表")
    public ServerResponseEntity<PageVO<CouponAppVO>> getCouponPage(@Valid PageDTO page) {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        Long userId = null;
        if (Objects.nonNull(uidInfoBO)) {
            userId = uidInfoBO.getUserId();
        }
        PageVO<CouponAppVO> couponDto = couponService.getProdCouponPage(page, userId);
        return ServerResponseEntity.success(couponDto);
    }

    @GetMapping("/getShopOrSpuCouponList")
    @Operation(summary = "获取指定店铺或指定商品的所有优惠券 ", description = "通过shopId或shopId和spuId获取指定店铺或指定商品的所有优惠券")
    public ServerResponseEntity<List<CouponAppVO>> getShopOrSpuCouponList(Long shopId, Long spuId) {
        // 获取已投放优惠券
        List<CouponAppVO> coupons = couponService.getShopCouponList(shopId);
        if (Objects.isNull(spuId)) {
            setStock(coupons);
            return ServerResponseEntity.success(coupons);
        }
        // 过滤指定商品参与
        coupons.addAll(couponService.getShopCouponList(Constant.PLATFORM_SHOP_ID));
        Iterator<CouponAppVO> iterator = coupons.iterator();
        List<Long> couponIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        while (iterator.hasNext()) {
            CouponAppVO coupon = iterator.next();
            if (Objects.equals(coupon.getSuitableProdType(), SuitableProdType.ALL_SPU.value()) || (coupon.getSpuIds().contains(spuId))) {
                couponIds.add(coupon.getCouponId());
                continue;
            }
            iterator.remove();
        }
        couponUserService.listByAndShopIdOrSpuId(coupons, couponIds);
        setStock(coupons);
        return ServerResponseEntity.success(coupons);
    }

    private void setStock(List<CouponAppVO> coupons) {
        Iterator<CouponAppVO> iterator = coupons.iterator();
        while (iterator.hasNext()) {
            CouponAppVO coupon = iterator.next();
            if (Objects.equals(coupon.getStatus(), CouponStatus.NO_OVERDUE.value()) && Objects.equals(coupon.getPutonStatus(), PutOnStatus.PUT_ON.value())) {
                // 正在投放的优惠券的库存
                Integer stock = couponStockManager.getStockByCouponId(coupon.getCouponId());
                if (stock < 1) {
                    iterator.remove();
                    continue;
                }
                coupon.setStocks(stock);
            }
        }
    }


    @GetMapping("/getSpusByCouponId")
    @Operation(summary = "根据优惠券，获取可用的商品列表", description = "根据优惠券，获取可用的商品列表")
    @Parameter(name = "couponId", description = "优惠券id")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> getSpusByCouponId(PageDTO pageDTO, ProductSearchDTO productSearch,
                                                                             @RequestParam("couponId") Long couponId) {
        return ServerResponseEntity.success(couponService.spuListByCouponId(pageDTO, productSearch, couponId));
    }

    @GetMapping("/generalCouponList")
    @Operation(summary = "获取优惠券信息", description = "根据id获取")
    public ServerResponseEntity<CouponAppVO> generalCouponList(@RequestParam("couponId") Long couponId) {
        CouponVO coupon = couponService.getCouponAndProdData(couponId);
        CouponAppVO appVO = BeanUtil.map(coupon, CouponAppVO.class);
        return ServerResponseEntity.success(appVO);
    }
}
