/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.yshop.module.cart.controller.app.cart;

import cn.hutool.core.util.ObjectUtil;
import co.yixiang.yshop.framework.common.pojo.CommonResult;
import co.yixiang.yshop.framework.security.core.annotations.PreAuthenticated;
import co.yixiang.yshop.module.cart.controller.app.cart.param.AppCartChangeSkuParam;
import co.yixiang.yshop.module.cart.controller.app.cart.param.AppCartIdsParm;
import co.yixiang.yshop.module.cart.controller.app.cart.param.AppCartNumParam;
import co.yixiang.yshop.module.cart.controller.app.cart.param.AppCartParam;
import co.yixiang.yshop.module.cart.enums.OrderTypeEnum;
import co.yixiang.yshop.module.cart.service.storecart.AppStoreCartService;
import co.yixiang.yshop.module.product.controller.app.campaigninfo.vo.CampaignNumberJudgeVO;
import co.yixiang.yshop.module.product.controller.app.couponrelation.vo.CartCouponVO;
import co.yixiang.yshop.module.product.service.campaigninfo.AppCampaignInfoService;
import co.yixiang.yshop.module.product.service.teamworkinfo.TeamworkInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static co.yixiang.yshop.framework.common.pojo.CommonResult.success;
import static co.yixiang.yshop.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * <p>
 * 购物车控制器
 * </p>
 *
 * @author hupeng
 * @since 2023-6-16
 */
@Slf4j
@RestController
@Tag(name = "用户 APP - 购物车")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/cart")
public class AppCartController {

    private final AppStoreCartService appStoreCartService;

    private final TeamworkInfoService teamworkInfoService;

    private final AppCampaignInfoService appCampaignInfoService;

    /**
     * 购物车 获取数量
     */
    @PreAuthenticated
    @GetMapping("/count")
    @Operation(summary = "获取数量")
    public CommonResult<Map<String, Object>> count() {
        Map<String, Object> map = new LinkedHashMap<>();
        Long uid = getLoginUserId();
        map.put("count", appStoreCartService.getUserCartNum(uid));
        return success(map);
    }

    /**
     * 购物车 添加
     */
    @PreAuthenticated
    @PostMapping("/add")
    @Operation(summary = "添加购物车")

    public CommonResult<Map<String, Object>> add(@Validated @RequestBody AppCartParam cartParam) {
        Long uid = getLoginUserId();
        if (OrderTypeEnum.CAMPAIGN_ORDER.getValue().equals(cartParam.getOrderType())) {
            // 判断是否重复参加拼团
            if (ObjectUtil.isNotEmpty(cartParam.getTeamworkId()))
                teamworkInfoService.joinJudge(uid, cartParam.getTeamworkId());
            // 活动商品购买数量限制
            appCampaignInfoService.numberJudge(new CampaignNumberJudgeVO
                    (cartParam.getUniqueId(), uid, cartParam.getCartNum()));
        }
        // 加入购物车并返回购物车id
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("cartId", appStoreCartService.addCart(uid, cartParam.getProductId(), cartParam.getCartNum(),
                cartParam.getUniqueId(), cartParam.getIsNew(), cartParam.getCombinationId(),
                cartParam.getSecKillId(), cartParam.getBargainId()));
        return success(map);
    }


    /**
     * 购物车列表
     */
    @PreAuthenticated
    @GetMapping("/cart/list")
    @Operation(summary = "购物车列表")
    public CommonResult<Map<String, Object>> getList() {
        Long uid = getLoginUserId();
        return success(appStoreCartService.getUserProductCartList(uid, "", null));
    }

    /**
     * 修改产品数量
     */
    @PreAuthenticated
    @PostMapping("/num")
    @Operation(summary = "修改产品数量")
    public CommonResult<Boolean> cartNum(@Validated @RequestBody AppCartNumParam param) {
        Long uid = getLoginUserId();
        appStoreCartService.changeUserCartNum(param.getId(), param.getNumber(), uid);
        return success(true);
    }

    /**
     * 购物车删除产品
     */
    @PreAuthenticated
    @PostMapping("/cart/del")
    @Operation(summary = "购物车删除产品")
    public CommonResult<Boolean> cartDel(@Validated @RequestBody AppCartIdsParm parm) {
        Long uid = getLoginUserId();
        appStoreCartService.removeUserCart(uid, parm.getIds());
        return success(true);
    }

    /**
     * 购物车更换sku
     */
    @PreAuthenticated
    @PostMapping("/cart/changeSku")
    @Operation(summary = "购物车更换产品规格")
    public CommonResult<Boolean> changeSku(@Validated @RequestBody AppCartChangeSkuParam param) {
        Long uid = getLoginUserId();
        appStoreCartService.changeSku(uid, param);
        return success(true);
    }

    @GetMapping("/coupon")
    @Operation(summary = "查询购物车可用优惠券")
    @Parameter(name = "cartIds", description = "购物车id合集，用,隔开", required = true, example = "1,2")
    public CommonResult<List<CartCouponVO>> searchCartAvailableCoupon(@RequestParam String cartIds) {
        return success(appStoreCartService.searchCartAvailableCoupon(cartIds));
    }


}

