package com.yiqi.api.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yiqi.app.domain.AppGoodsMarket;
import com.yiqi.app.domain.dto.weapp.WeAppGoodsMarketSaveDTO;
import com.yiqi.app.domain.vo.weapp.WeAppGoodsMarketVO;
import com.yiqi.app.service.IAppGoodsMarketService;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.enums.DeleteStatus;
import com.yiqi.common.enums.SysBoolType;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.StringUtils;
import com.yiqi.core.domain.GoodsSkuSpec;
import com.yiqi.core.domain.vo.weapp.WeAppGoodsSkuVO;
import com.yiqi.core.service.IGoodsSkuSpecService;
import com.yiqi.core.service.IGoodsSkuStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiaohei
 * @date 2023/11/1
 */
@Api(tags = "购物车")
@RestController
@RequestMapping(value = UrlConstants.wxappApi + "/goods/market")
public class WeAppGoodsMarketController extends BaseController {

    @Autowired
    private IAppGoodsMarketService appGoodsMarketService;
    @Autowired
    private IGoodsSkuStoreService goodsSkuStoreService;
    @Autowired
    private IGoodsSkuSpecService goodsSkuSpecService;

    @ApiOperation("获取购物车列表")
    @GetMapping(value = "list")
    public R<List<WeAppGoodsMarketVO>> list() throws Exception {
        AppGoodsMarket appGoodsMarket = new AppGoodsMarket();
        appGoodsMarket.setAppUserId(AuthHolder.userId());
        List<WeAppGoodsMarketVO> weAppGoodsMarketVOS = appGoodsMarketService.selectAppGoodsMarketList(appGoodsMarket);
        if (weAppGoodsMarketVOS == null || weAppGoodsMarketVOS.size() == 0) {
            return R.ok(weAppGoodsMarketVOS);
        }
        for (WeAppGoodsMarketVO weAppGoodsMarketVO : weAppGoodsMarketVOS) {
            //values字符串数组转List
            if (StringUtils.isNotBlank(weAppGoodsMarketVO.getGoodsSkuVO().getSpecs())) {
                weAppGoodsMarketVO.getGoodsSkuVO().setSpecValLists(JSONUtil.toList(JSONUtil.parseArray(weAppGoodsMarketVO.getGoodsSkuVO().getSpecs()), String.class));
            }
        }
        return R.ok(weAppGoodsMarketVOS);
    }

    /**
     * 新增购物车
     */
    @PostMapping(value = "add")
    @ApiOperation(value = "新增购物车")
    public R add(@RequestBody @Valid WeAppGoodsMarketSaveDTO weAppGoodsMarketSaveDTO) {
        //如果已存在购物车，则只新增状态
        AppGoodsMarket appGoodsMarket = appGoodsMarketService.getOne(new QueryWrapper<AppGoodsMarket>().lambda()
                .eq(AppGoodsMarket::getGoodsSkuId, weAppGoodsMarketSaveDTO.getGoodsSkuId())
                .eq(AppGoodsMarket::getAppUserId, AuthHolder.userId()), false);
        if (appGoodsMarket != null) {
            appGoodsMarket.setBuyNum(appGoodsMarket.getBuyNum() + 1);
            appGoodsMarketService.updateById(appGoodsMarket);
            return R.ok();
        }
        appGoodsMarket = new AppGoodsMarket();
        BeanUtils.copyProperties(weAppGoodsMarketSaveDTO, appGoodsMarket);
        appGoodsMarket.setAppUserId(AuthHolder.userId());
        appGoodsMarket.setIsSelect(SysBoolType.YES.getCode());
        appGoodsMarket.setCreateTime(DateUtils.getNowDate());
        appGoodsMarketService.insertAppGoodsMarket(appGoodsMarket);
        return R.ok();
    }

    @ApiOperation("设置购物车数量")
    @GetMapping(value = "changeNum")
    public R changeNum(@RequestParam @ApiParam("购物车ID") long id, @RequestParam @ApiParam("购买数量") int buyNum) throws Exception {
        if (buyNum <= 0) {
            throw new ServiceException("购买数量最小为1");
        }
        if (buyNum > 99) {
            throw new ServiceException("购买数量最多99个");
        }
        appGoodsMarketService.update(new UpdateWrapper<AppGoodsMarket>().lambda()
                .set(AppGoodsMarket::getBuyNum, buyNum).eq(AppGoodsMarket::getId, id));
        return R.ok();
    }

    @ApiOperation("设置购物车选中状态")
    @GetMapping(value = "setSelect")
    public R setSelect(@RequestParam @ApiParam("购物车ID") long id, @RequestParam @ApiParam("是否选中（N=未选中，Y=选中）") String isSelect) throws Exception {
        appGoodsMarketService.update(new UpdateWrapper<AppGoodsMarket>().lambda()
                .set(AppGoodsMarket::getIsSelect, isSelect).eq(AppGoodsMarket::getId, id));
        return R.ok();
    }

    @ApiOperation("设置购物车全选状态")
    @GetMapping(value = "setAllSelect")
    public R setAllSelect(@RequestParam @ApiParam("是否选中（N=未选中，Y=选中）") String isSelect) throws Exception {
        appGoodsMarketService.update(new UpdateWrapper<AppGoodsMarket>().lambda()
                .eq(AppGoodsMarket::getAppUserId, AuthHolder.userId())
                .set(AppGoodsMarket::getIsSelect, isSelect));
        return R.ok();
    }


    /**
     * 删除购物车
     */
    @GetMapping(value = "delete")
    @ApiOperation(value = "删除购物车")
    public R remove(@RequestParam Long[] ids) {
        appGoodsMarketService.deleteAppGoodsMarketByIds(ids);
        return R.ok();
    }

}
