package com.liquidnet.service.goblin.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.liquidnet.common.exception.constant.ErrorCode;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.constant.GoblinStatusConst;
import com.liquidnet.service.goblin.dto.vo.*;
import com.liquidnet.service.goblin.param.CouponCountParam;
import com.liquidnet.service.goblin.service.GoblinCouponService;
import com.liquidnet.service.goblin.util.GoblinRedisUtils;
import com.liquidnet.service.goblin.util.ObjectUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.List;

@ApiSupport(order = 145001)
@Api(tags = "商城:POS机相关")
@Slf4j
@RestController
@RequestMapping("store/pos")
public class GoblinPosController {
    @Autowired
    GoblinRedisUtils goblinRedisUtils;
    @Autowired
    GoblinCouponService goblinCouponService;

    @PostMapping("coupon/receive")
    @ApiOperation("领券")
    @ApiResponse(code = 200, message = "接口返回对象参数")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "storeCouponId", value = "平台券id"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "uid", value = "UID"),
    })
    public ResponseDto<GoblinUserCouponVo> checkOrderResult(@NotBlank(message = "参数无效:storeCouponId") @RequestParam("storeCouponId") String storeCouponId,
                                                            @NotBlank(message = "参数无效:uid") @RequestParam("uid") String uid) {
        String currentUid = CurrentUtil.getCurrentUid();
        GoblinStoreInfoVo storeInfoVo = goblinRedisUtils.getStoreInfoVoByUid(currentUid);
        GoblinStoreCouponVo storeCouponVo = goblinRedisUtils.getStoreCouponVo(storeCouponId);
        if (null == storeCouponVo) {
            log.warn("商城:POS机相关:领取券:优惠券不存在:[uid={},storeCouponId={}]", uid, storeCouponId);
            return ResponseDto.failure(ErrorMapping.get("140050"));
        } else if (null == storeInfoVo) {
            log.warn("商城:POS机相关:领取券:未创建店铺不可领取优惠券:[uid={},storeCouponId={}]", uid, storeCouponId);
            return ResponseDto.failure(ErrorCode.HTTP_PARAM_ERROR.getCode(), "店铺不存在");
        } else if (!storeCouponVo.getStoreId().equals(storeInfoVo.getStoreId())) {
            log.warn("商城:POS机相关:领取券:非本店铺优惠券不可领取:[uid={},storeId={},storeCouponId={}]", uid, storeInfoVo.getStoreId(), storeCouponId);
            return ResponseDto.failure(ErrorCode.HTTP_PARAM_ERROR.getCode(), "非本店铺优惠券不可领取");
        } else if (!storeCouponVo.getState().equals("1")) {
            return ResponseDto.failure(ErrorMapping.get("140051"));
        }
        // TODO: 2022/2/24 zhanggb==暂不进行UID真实校验
        List<GoblinUserCouponVo> userCouponVos = goblinRedisUtils.getUserCouponVos(uid);
        if (!CollectionUtils.isEmpty(userCouponVos)) {
            int beforeSize = userCouponVos.size();
            userCouponVos.removeIf(vo -> vo.getStoreCouponId().equals(storeCouponId));
            if ((beforeSize - userCouponVos.size()) >= storeCouponVo.getReceiveLimit()) {
                return ResponseDto.failure(ErrorMapping.get("140052"));
            }
        }
        if (storeCouponVo.getStock().equals(0) || goblinRedisUtils.getStoreCouponStock(storeCouponId) > 0) {
            Boolean resultFlg = goblinCouponService.receiveCoupon(uid, userCouponVos, storeCouponVo);
            return resultFlg ? ResponseDto.success(userCouponVos.stream().filter(r -> r.getStoreCouponId().equals(storeCouponId)).findFirst().get()) : ResponseDto.failure();
        }
        return ResponseDto.failure(ErrorMapping.get("140053"));
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "商品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "skuids", value = "多个skuId以,分隔"),
    })
    @PostMapping("goods/skuinfo")
    public ResponseDto<List<GoblinPosGoodsVo>> skuInfoList(@NotBlank(message = "参数无效:skuIds") @RequestBody String skuids) {
        log.info("商城:POS机相关:SKU列表[skuIds={}]", skuids);
        String currentUid = CurrentUtil.getCurrentUid();
        GoblinStoreInfoVo storeInfoVo = goblinRedisUtils.getStoreInfoVoByUid(currentUid);
        if (null == storeInfoVo) {
            log.warn("商城:POS机相关:SKU明细:店铺不存在[uid={},skuIds={}]", currentUid, skuids);
            return ResponseDto.failure(ErrorCode.HTTP_PARAM_ERROR.getCode(), "店铺不存在");
        }
        String storeId = storeInfoVo.getStoreId();
        skuids = skuids.replaceFirst("skuids","").replaceAll("[\":{}]", "");

        String[] skuIdArr = skuids.split(",");
        List<GoblinPosGoodsVo> posGoodsVoList = ObjectUtil.getGoblinPosGoodsVoArrayList();
        for (String skuId : skuIdArr) {
            GoblinGoodsSkuInfoVo goodsSkuInfoVo = goblinRedisUtils.getGoodsSkuInfoVo(skuId);
            if (null != goodsSkuInfoVo && goodsSkuInfoVo.getDelFlg().equals("0") && storeId.equals(goodsSkuInfoVo.getStoreId()) && goodsSkuInfoVo.getShelvesStatus().equals("3")) {
                String spuId = goodsSkuInfoVo.getSpuId();
                GoblinGoodsInfoVo goodsInfoVo = goblinRedisUtils.getGoodsInfoVo(spuId);
                if (null != goodsInfoVo && goodsInfoVo.getDelFlg().equals("0")) {
                    GoblinPosGoodsVo posGoodsVo = GoblinPosGoodsVo.getNew();
                    posGoodsVo.setSkuId(skuId);
                    posGoodsVo.setName(goodsSkuInfoVo.getName());
                    posGoodsVo.setPrice(goodsSkuInfoVo.getPrice());
                    posGoodsVo.setSpuId(spuId);
                    posGoodsVo.setSpuName(goodsInfoVo.getName());
                    String pre = GoblinStatusConst.MarketPreStatus.getPre(spuId);
                    int stock = goblinRedisUtils.getSkuStock(pre, skuId);
                    posGoodsVo.setRestStock(stock);
                    if (stock > 0) {
                        posGoodsVoList.add(posGoodsVo);
                    }
                }
            }
        }
        return ResponseDto.success(posGoodsVoList);
    }

//    @PostMapping("coupon/count")
//    @ApiOperation("券领取次数")
//    @ResponseBody
//    public ResponseDto<List<CouponCountVo>> couponCount(@RequestBody CouponCountParam param) {
//        String uid = param.getUid();
//        List<String> storeCouponIds = param.getStoreCouponIds();
//        List<GoblinUserCouponVo> userCouponVos = goblinRedisUtils.getUserCouponVos(uid);
//        List<CouponCountVo> voList = ObjectUtil.couponCountVos();
//        for (String storeCouponId : storeCouponIds) {
//            if (!CollectionUtils.isEmpty(userCouponVos)) {
//                int beforeSize = userCouponVos.size();
//                userCouponVos.removeIf(vo -> vo.getStoreCouponId().equals(storeCouponId));
//                int receiveCount = (beforeSize - userCouponVos.size());
//                CouponCountVo single = CouponCountVo.getNew();
//                single.setStoreCouponId(storeCouponId);
//                single.setCount(receiveCount);
//                voList.add(single);
//            }
//        }
//        return ResponseDto.success(voList);
//    }

    @PostMapping("coupon/count")
    @ApiOperation("券领取次数")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = " List<String>", name = "storeCouponId", value = "平台券id"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "uid", value = "UID"),
    })
    public ResponseDto<List<CouponCountVo>> couponCount(@NotBlank(message = "参数无效:storeCouponId") @RequestParam("storeCouponId") List<String> storeCouponIds,
                                                         @NotBlank(message = "参数无效:uid") @RequestParam("uid") String uid) {
        List<GoblinUserCouponVo> userCouponVos = goblinRedisUtils.getUserCouponVos(uid);
        List<CouponCountVo> voList = ObjectUtil.couponCountVos();
        for (String storeCouponId : storeCouponIds) {
            if (!CollectionUtils.isEmpty(userCouponVos)) {
                int beforeSize = userCouponVos.size();
                userCouponVos.removeIf(vo -> vo.getStoreCouponId().equals(storeCouponId));
                int receiveCount = (beforeSize - userCouponVos.size());
                CouponCountVo single = CouponCountVo.getNew();
                single.setStoreCouponId(storeCouponId);
                single.setCount(receiveCount);
                voList.add(single);
            }
        }
        return ResponseDto.success(voList);
    }
}
