package com.yonge.cooleshow.portal.controller;

import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.CacheNameEnum;
import com.yonge.cooleshow.mall.common.api.CommonResult;
import com.yonge.cooleshow.mall.common.enums.OrderCacheEnum;
import com.yonge.cooleshow.mbg.model.OmsCartItem;
import com.yonge.cooleshow.portal.domain.CartProduct;
import com.yonge.cooleshow.portal.domain.CartPromotionItem;
import com.yonge.cooleshow.portal.dto.OrderPayRes;
import com.yonge.cooleshow.portal.service.OmsCartItemService;
import com.yonge.cooleshow.portal.service.UmsMemberService;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.payment.util.DistributedLock;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.yonge.cooleshow.mall.common.api.CommonResult.failed;
import static com.yonge.cooleshow.mall.common.enums.OrderCacheEnum.LOCK_STOCK_MALL;

/**
 * 购物车管理Controller
 * Created by macro on 2018/8/2.
 */
@Controller
@Api(tags = "OmsCartItemController 购物车管理")
@RequestMapping("/cart")
public class OmsCartItemController {
    @Autowired
    private OmsCartItemService cartItemService;
    @Autowired
    private UmsMemberService memberService;


    @Autowired
    private RedissonClient redissonClient;

    @ApiOperation("添加商品到购物车")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<OmsCartItem> add(@RequestBody OmsCartItem cartItem) {

        RLock lock = redissonClient.getLock(OrderCacheEnum.LOCK_STOCK_MALL.getRedisKey(cartItem.getProductSkuId()));
        try {
            boolean b = lock.tryLock(60, TimeUnit.SECONDS);
            if (b) {
                OmsCartItem omsCartItem = cartItemService.add(cartItem);
                return CommonResult.success(omsCartItem);
            }
            return failed("请求超时");
        } catch (BizException e) {
            return failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求超时");
        } finally {
            if (lock.getHoldCount()>0) {
                lock.unlock();
            }
        }

    }

    @ApiOperation("获取当前会员的购物车列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<OmsCartItem>> list() {
        List<OmsCartItem> cartItemList = cartItemService.list(memberService.getCurrentMember().getId());
        return CommonResult.success(cartItemList);
    }

    @ApiOperation("获取当前会员的购物车列表,包括促销信息")
    @RequestMapping(value = "/list/promotion", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<CartPromotionItem>> listPromotion(@RequestParam(required = false) String cartIds) {
        List<Long> list = StringUtil.toLongList(cartIds);
        List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(memberService.getCurrentMember().getId(), list,
                                                                                      false);
        return CommonResult.success(cartPromotionItemList);
    }

    @ApiOperation("修改购物车中指定商品的数量")
    @RequestMapping(value = "/update/quantity", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult updateQuantity(@RequestParam Long id,
                                       @RequestParam Integer quantity) {

        OmsCartItem omsCartItem = cartItemService.get(id);

        RLock lock = redissonClient.getLock(OrderCacheEnum.LOCK_STOCK_MALL.getRedisKey(omsCartItem.getProductSkuId()));
        try {
            boolean b = lock.tryLock(60, TimeUnit.SECONDS);
            if (b) {
                int i = cartItemService.updateQuantity(id, memberService.getCurrentMember().getId(), quantity);
                return CommonResult.success(i);
            }
            return failed("请求超时");
        } catch (BizException e) {
            return failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求超时");
        } finally {
            if (lock.getHoldCount()>0) {
                lock.unlock();
            }
        }

    }

    @ApiOperation("获取购物车中指定商品的规格,用于重选规格")
    @RequestMapping(value = "/getProduct/{productId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CartProduct> getCartProduct(@PathVariable Long productId) {
        CartProduct cartProduct = cartItemService.getCartProduct(productId);
        return CommonResult.success(cartProduct);
    }

    @ApiOperation("修改购物车中商品的规格")
    @RequestMapping(value = "/update/attr", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateAttr(@RequestBody OmsCartItem cartItem) {
        int count = cartItemService.updateAttr(cartItem);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return failed();
    }

    @ApiOperation("删除购物车中的指定商品")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@RequestParam("ids") String ids) {
        List<Long> list = StringUtil.toLongList(ids);
        int count = cartItemService.delete(memberService.getCurrentMember().getId(), list);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return failed();
    }

    @ApiOperation("清空当前会员的购物车")
    @RequestMapping(value = "/clear", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult clear() {
        int count = cartItemService.clear(memberService.getCurrentMember().getId());
        if (count > 0) {
            return CommonResult.success(count);
        }
        return failed();
    }
}
