package com.yiqi.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.app.domain.AppGoodsCollect;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.app.service.IAppGoodsCollectService;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.PageVO;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.core.domain.GoodsInfo;
import com.yiqi.core.domain.vo.weapp.WeAppGoodsInfoQueryVO;
import com.yiqi.core.service.IGoodsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author xiaohei
 * @date 2023/10/30
 */
@Api(tags = "商品收藏")
@RestController
@RequestMapping(value = UrlConstants.wxappApi + "/goods/collect")
public class WeAppGoodsCollectController extends BaseController {

    @Autowired
    private IAppGoodsCollectService appGoodsCollectService;

    @Autowired
    private IGoodsInfoService goodsInfoService;

    @ApiOperation("获取我的收藏列表")
    @PostMapping(value = "findPage")
    public R<List<WeAppGoodsInfoQueryVO>> findPage(@RequestBody @Valid PageVO pageVO) throws Exception{
        return R.ok(appGoodsCollectService.selectAppGoodsCollectList(pageVO));
    }

    @ApiOperation("收藏商品")
    @GetMapping(value = "add")
    public R add(@RequestParam @ApiParam("商品ID") long goodsId) throws Exception{
        if(appGoodsCollectService.count(new QueryWrapper<AppGoodsCollect>()
                .lambda().eq(AppGoodsCollect::getGoodsId,goodsId)
                .eq(AppGoodsCollect::getAppUserId, AuthHolder.userId())) > 0){
            throw new ServiceException("您已经收藏过该商品");
        }
        if(goodsInfoService.count(new QueryWrapper<GoodsInfo>().lambda().eq(GoodsInfo::getId,goodsId)) == 0){
            throw new ServiceException("未查询到商品");
        }

        AppGoodsCollect appGoodsCollect = new AppGoodsCollect();
        appGoodsCollect.setAppUserId(AuthHolder.userId());
        appGoodsCollect.setGoodsId(goodsId);
        appGoodsCollect.setCreateTime(DateUtils.getNowDate());
        appGoodsCollectService.save(appGoodsCollect);
        return R.ok();
    }


    /**
     * 删除商品收藏记录
     */
    @GetMapping("/delete")
    @ApiOperation(value = "删除商品收藏")
    public AjaxResult remove(@RequestParam @ApiParam("商品id集合，\",\"分割") String ids) {
        String[] idArray = ids.split(",");
        return toAjax(appGoodsCollectService.deleteAppGoodsCollectByIds(idArray));
    }

}
