/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.seckill.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.seckill.api.dto.SeckillProductDto;
import com.yami.shop.seckill.comment.dto.SeckillProductSimpleDto;
import com.yami.shop.seckill.api.dto.SeckillSkuDto;
import com.yami.shop.seckill.comment.model.Seckill;
import com.yami.shop.seckill.comment.model.SeckillSku;
import com.yami.shop.seckill.comment.service.SeckillService;
import com.yami.shop.seckill.comment.service.SeckillSkuService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.SkuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
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.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 秒杀信息
 *
 * @author LGH
 * @date 2019-08-28 09:36:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/seckill" )
@Api(tags = "秒杀商品接口")
public class SeckillProdController {

    private final SeckillService seckillService;

    private final MapperFacade mapperFacade;

    private final ProductService productService;

    private final SeckillSkuService seckillSkuService;

    private final SkuService skuService;

    private final ShopDetailService shopDetailService;

    @GetMapping("/prod" )
    @ApiOperation(value = "获取秒杀商品信息", notes = "根据秒杀活动id，获取当前秒杀的商品信息，状态码204表示活动已结束")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "seckillId", value = "秒杀ID", required = true, dataType = "Long"),
    })
    public ResponseEntity<SeckillProductDto> getSeckillPage(Long seckillId) {

        // 秒杀活动信息（来自缓存）
        Seckill seckill = seckillService.getSeckillById(seckillId);

        // 秒杀已经下线
        if (seckill == null || Objects.equals(seckill.getStatus(), 0)) {
            return ResponseEntity.noContent().build();
        }
        //判断是否删除
        if(Objects.equals(seckill.getIsDelete(), 1)){
            return ResponseEntity.noContent().build();
        }
        // 秒杀结束时间
        if (seckill.getEndTime().getTime() < System.currentTimeMillis()) {
            return ResponseEntity.noContent().build();
        }
        // 商品信息（来自缓存）
        Product product = productService.getProductByProdId(seckill.getProdId());
        // 商品下线，状态异常时
//        if (product == null || Objects.equals(product.getStatus(), 0)) {
        if (product == null || !Objects.equals(product.getStatus(), 1)) {
            return ResponseEntity.noContent().build();
        }

        // 店铺详情（来自缓存）
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(product.getShopId());

        SeckillProductDto seckillProductDto = mapperFacade.map(product, SeckillProductDto.class);
        seckillProductDto.setSeckill(seckill);
        seckillProductDto.setPrice(product.getPrice());

        seckillProductDto.setShopName(shopDetail.getShopName());
        seckillProductDto.setShopId(shopDetail.getShopId());

        // 秒杀活动sku信息（来自缓存）
        List<SeckillSku> seckillSkus = seckillSkuService.listSeckillSkuBySeckillId(seckillId);

        // 商品sku信息（来自缓存）
        List<Sku> skuList = skuService.listByProdId(product.getProdId());


        List<SeckillSkuDto> seckillSkuDtos = seckillSkus.stream().map(seckillSku -> {

            SeckillSkuDto seckillSkuDto = new SeckillSkuDto();
            for (Sku sku : skuList) {
                if (!Objects.equals(sku.getSkuId(), seckillSku.getSkuId())) {
                    continue;
                }
                seckillSkuDto.setProdName(sku.getProdName());
                seckillSkuDto.setProperties(sku.getProperties());
                seckillSkuDto.setSeckillId(seckillId);
                seckillSkuDto.setSeckillPrice(seckillSku.getSeckillPrice());
                seckillSkuDto.setSeckillStocks(seckillSku.getSeckillStocks());
                seckillSkuDto.setSkuId(sku.getSkuId());
                seckillSkuDto.setSeckillSkuId(seckillSku.getSeckillSkuId());
            }

            return seckillSkuDto;
        }).collect(Collectors.toList());

        seckillProductDto.setSkuList(seckillSkuDtos);
        return ResponseEntity.ok(seckillProductDto);
    }


    @GetMapping("/pageProd")
    @ApiOperation(value = "秒杀商品列表（分页）", notes = "分页获取秒杀商品列表")
    public ResponseEntity<IPage<SeckillProductSimpleDto>> pageProd(PageParam<SeckillProductSimpleDto> page,
                                                                   @RequestParam(value = "lat", required = false) String lat,
                                                                   @RequestParam(value = "lon", required = false) String lon,
                                                                   @RequestParam(value = "distance", required = false) String distance) {
        return ResponseEntity.ok(seckillService.pageSeckillProd(page, lat, lon, distance));
    }


    @GetMapping("/indexList")
    @ApiOperation(value = "首页中的秒杀商品列表", notes = "获取最新前5条秒杀商品数据")
    public ResponseEntity<List<SeckillProductSimpleDto>> indexList() {
        PageParam<SeckillProductSimpleDto> page = new PageParam<>();
        page.setSearchCount(false);
        page.setCurrent(1L);
        page.setSize(5);
        page.setTotal(5);
        IPage<SeckillProductSimpleDto> prodPage = seckillService.pageSeckillProd(page, null, null,null);
        return ResponseEntity.ok(prodPage.getRecords());
    }

}
