package com.slodon.b2b2c.controller.promotion.seller;

import com.slodon.b2b2c.core.constant.RedisConst;
import com.slodon.b2b2c.core.constant.SeckillConst;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.goods.pojo.Product;
import com.slodon.b2b2c.model.goods.ProductModel;
import com.slodon.b2b2c.model.promotion.SeckillModel;
import com.slodon.b2b2c.model.promotion.SeckillStageProductModel;
import com.slodon.b2b2c.promotion.example.SeckillExample;
import com.slodon.b2b2c.promotion.example.SeckillStageProductExample;
import com.slodon.b2b2c.promotion.pojo.Seckill;
import com.slodon.b2b2c.promotion.pojo.SeckillStageProduct;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.vo.promotion.SeckillProductListVO;
import com.slodon.b2b2c.vo.promotion.SellerJoinSeckillVO;
import com.slodon.b2b2c.vo.promotion.SellerSeckillProductVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "seller-已参加秒杀活动")
@RestController
@Slf4j
@RequestMapping("v3/promotion/seller/joinSeckill")
public class SellerJoinSeckillController extends BaseController {

    @Resource
    private SeckillModel seckillModel;
    @Resource
    private SeckillStageProductModel seckillStageProductModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("已参加活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "seckillName", value = "活动名称", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "活动状态 1-未开始；2-进行中;3-已结束", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<SellerJoinSeckillVO>> getList(HttpServletRequest request,
                                                           @RequestParam(value = "seckillName", required = false) String seckillName,
                                                           @RequestParam(value = "startTime", required = false) Date startTime,
                                                           @RequestParam(value = "endTime", required = false) Date endTime,
                                                           @RequestParam(value = "state", required = false) Integer state) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        PagerInfo pager = WebUtil.handlerPagerInfo(request);

        SeckillExample seckillExample = new SeckillExample();
        seckillExample.setSeckillNameLike(seckillName);
        seckillExample.setStartTimeBefore(endTime);
        seckillExample.setEndTimeAfter(startTime);
        seckillExample.setStoreId(vendor.getStoreId());
        if (!StringUtil.isNullOrZero(state)) {
            switch (state) {
                case SeckillConst.SECKILL_STATE_1:
                    //未开始
                    seckillExample.setStartTimeAfter(new Date());
                    break;
                case SeckillConst.SECKILL_STATE_2:
                    //进行中
                    seckillExample.setStartTimeBefore(new Date());
                    seckillExample.setEndTimeAfter(new Date());
                    break;
                case SeckillConst.SECKILL_STATE_3:
                    //已结束
                    seckillExample.setEndTimeBefore(new Date());
            }
        }
        List<Seckill> seckillList = seckillModel.getSeckillList(seckillExample, pager);
        List<SellerJoinSeckillVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(seckillList)) {
            for (Seckill seckill : seckillList) {
                SellerJoinSeckillVO vo = new SellerJoinSeckillVO(seckill);
                vos.add(vo);
            }
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("查看商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "seckillId", value = "秒杀活动id", required = true),
            @ApiImplicitParam(name = "goodsName", value = "商品名称", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "审核状态：1-待审核，2-审核通过，3-审核拒绝", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("goodsList")
    public JsonResult<PageVO<SeckillProductListVO>> getGoodsList(HttpServletRequest request,
                                                                 @RequestParam("seckillId") Integer seckillId,
                                                                 @RequestParam(value = "goodsName", required = false) String goodsName,
                                                                 @RequestParam(value = "startTime", required = false) Date startTime,
                                                                 @RequestParam(value = "endTime", required = false) Date endTime,
                                                                 @RequestParam(value = "state", required = false) Integer state) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        PagerInfo pager = WebUtil.handlerPagerInfo(request);

        //根据商品id分组,获取所有的商品id列表
        String fields = "goods_id,stage_id,main_image,goods_name,stage_name,start_time,end_time,label_name,verify_state,remark";
        SeckillStageProductExample example = new SeckillStageProductExample();
        example.setSeckillId(seckillId);
        example.setStoreId(vendor.getStoreId());
        example.setGoodsNameLike(goodsName);
        example.setStartTimeBefore(endTime);
        example.setEndTimeAfter(startTime);
        example.setVerifyState(state);
        example.setGroupBy(fields);
        example.setOrderBy("stage_id ASC");

        List<SeckillStageProduct> seckillStageProductList = seckillStageProductModel.getSeckillStageProducts(fields, example, pager);
        List<SeckillProductListVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(seckillStageProductList)) {
            for (SeckillStageProduct seckillProduct : seckillStageProductList) {
                SeckillProductListVO vo = new SeckillProductListVO(seckillProduct);
                vos.add(vo);
            }
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("删除秒杀商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "seckillId", value = "秒杀活动id", required = true),
            @ApiImplicitParam(name = "goodsId", value = "商品id", required = true)
    })
    @PostMapping("del")
    public JsonResult<Integer> delSeckillProduct(HttpServletRequest request,
                                                 @RequestParam("seckillId") Integer seckillId,
                                                 @RequestParam("goodsId") Long goodsId) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        //根据goodsId,seckillId查询秒杀商品
        SeckillStageProductExample example = new SeckillStageProductExample();
        example.setSeckillId(seckillId);
        example.setGoodsId(goodsId);
        example.setStoreId(vendor.getStoreId());
        example.setVerifyStateIn(SeckillConst.SECKILL_AUDIT_STATE_1 + "," + SeckillConst.SECKILL_AUDIT_STATE_3);
        seckillStageProductModel.deleteSeckillStageProductByExample(example);

        String logMsg = "删除秒杀商品[删除成功][商品ID:" + goodsId + "]";
        return SldResponse.success("删除成功", logMsg);
    }

    @ApiOperation("查看SKU")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "seckillId", value = "秒杀活动id", required = true, paramType = "query"),
            @ApiImplicitParam(name = "stageId", value = "场次id", required = true, paramType = "query"),
            @ApiImplicitParam(name = "goodsId", value = "商品id", required = true, paramType = "query")
    })
    @GetMapping("productList")
    public JsonResult<List<SellerSeckillProductVO>> getProductList(HttpServletRequest request,
                                                                   @RequestParam("seckillId") Integer seckillId,
                                                                   @RequestParam("stageId") Integer stageId,
                                                                   @RequestParam("goodsId") Long goodsId) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        SeckillStageProductExample example = new SeckillStageProductExample();
        example.setSeckillId(seckillId);
        example.setStageId(stageId);
        example.setGoodsId(goodsId);
        example.setStoreId(vendor.getStoreId());
        List<SeckillStageProduct> seckillStageProductList = seckillStageProductModel.getSeckillStageProductList(example, null);
        List<SellerSeckillProductVO> vos = new ArrayList();
        if (!CollectionUtils.isEmpty(seckillStageProductList)) {
            for (SeckillStageProduct seckillStageProduct : seckillStageProductList) {
                //审核拒绝的直接展示数据库库存
                if (seckillStageProduct.getVerifyState() == SeckillConst.SECKILL_AUDIT_STATE_3) {
                    seckillStageProduct.setSeckillStock(seckillStageProduct.getSeckillStock());
                } else {
                    //秒杀库存取redis
                    String seckillStock = stringRedisTemplate.opsForValue().get(RedisConst.REDIS_SECKILL_PRODUCT_STOCK_PREFIX + seckillStageProduct.getProductId());
                    seckillStageProduct.setSeckillStock(seckillStock == null ? 0 : Integer.parseInt(seckillStock));
                }
                //货品规格
                Product product = productModel.getProductByProductId(seckillStageProduct.getProductId());
                AssertUtil.notNull(product, "货品信息不存在");
                SellerSeckillProductVO vo = new SellerSeckillProductVO(seckillStageProduct);
                vo.setProductStock(product.getProductStock());
                vo.setSpecValues(product.getSpecValues());
                vos.add(vo);
            }
        }
        return SldResponse.success(vos);
    }
}
