package com.qs.mp.web.controller.api.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.qs.mp.admin.domain.ExchangeBanner;
import com.qs.mp.admin.domain.Goods;
import com.qs.mp.admin.domain.GoodsCategory;
import com.qs.mp.admin.domain.GoodsSku;
import com.qs.mp.admin.domain.GoodsTag;
import com.qs.mp.admin.domain.GoodsTagRel;
import com.qs.mp.admin.domain.vo.GoodsCategoryTreeVO;
import com.qs.mp.admin.domain.vo.GoodsListVO;
import com.qs.mp.admin.domain.vo.GoodsVO;
import com.qs.mp.admin.service.IExchangeBannerService;
import com.qs.mp.admin.service.IGoodsCategoryService;
import com.qs.mp.admin.service.IGoodsService;
import com.qs.mp.admin.service.IGoodsSkuService;
import com.qs.mp.admin.service.IGoodsTagRelService;
import com.qs.mp.admin.service.IGoodsTagService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.common.enums.GoodsStatusEnum;
import com.qs.mp.common.utils.StringUtils;
import com.qs.mp.user.domain.param.ExchangeGoodsListQueryParam;
import com.qs.mp.user.domain.param.ExchangeOrderParam;
import com.qs.mp.user.service.IUserExchangeOrderService;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.*;
import java.util.stream.Collectors;

import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/api/v1/mp/user/exchange")
@Api(tags = "盲票兑换大厅接口")
@AllArgsConstructor
public class UserExchangeController extends BaseApiController {


  @Autowired
  private IGoodsService goodsService;

  @Autowired
  private IGoodsSkuService goodsSkuService;

  @Autowired
  private IUserExchangeOrderService userExchangeOrderService;

  @Autowired
  private IGoodsTagRelService goodsTagRelService;

  @Autowired
  private IExchangeBannerService exchangeBannerService;

  @Autowired
  private IGoodsCategoryService goodsCategoryService;

  @Autowired
  private IGoodsTagService goodsTagService;

  @Autowired
  private MapperFacade mapperFacade;

  @PostMapping("/category/listTree")
  @ApiOperation("商品分类树状列表")
  @ApiResponses(
          @ApiResponse(code = 200, message = "success" , response = GoodsCategoryTreeVO.class)
  )
  public TableDataInfo listTree(@RequestBody JSONObject param) {
    startPage();

    // 获取父分类
    List<GoodsCategory> categoryList = goodsCategoryService.list(
            new LambdaQueryWrapper<GoodsCategory>()
                    .eq(GoodsCategory::getParentId, 0)
                    .eq(GoodsCategory::getIsShow, 1)
                    .orderByDesc(GoodsCategory::getSort));
    if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(categoryList)) {
      return getErrorDataTable("分类信息不存在");
    }

    List<GoodsCategoryTreeVO> treeList =  categoryList.stream().map(goodsCategory -> {
      GoodsCategoryTreeVO goodsCategoryTreeVO = new GoodsCategoryTreeVO();
      BeanUtils.copyProperties(goodsCategory, goodsCategoryTreeVO);
      // 获取子分类
      List<GoodsCategory> list = goodsCategoryService.list(
              new LambdaQueryWrapper<GoodsCategory>()
                      .eq(GoodsCategory::getParentId, goodsCategory.getCategoryId())
                      .eq(GoodsCategory::getIsShow, 1)
                      .orderByDesc(GoodsCategory::getSort));
      goodsCategoryTreeVO.setGoodsCategoryList(list);
      return goodsCategoryTreeVO;
    }).collect(Collectors.toList());

    return getDataTable(treeList);
  }


  /**
   * 商品列表
   */
  @PostMapping("/goods/list")
  @ApiOperation(value = "商品列表", notes = "获取所有可兑换商品")
  @ApiResponses(
          @ApiResponse(code = 200, message = "success" , response = GoodsListVO.class)
  )
  public TableDataInfo list(@RequestBody ExchangeGoodsListQueryParam param) {

    List<Long> goodsIds = new ArrayList<>();
    if (StringUtils.isNotBlank(param.getTagIds())) {
      List<GoodsTagRel> goodsTagRelList = goodsTagRelService.list(
          new LambdaQueryWrapper<GoodsTagRel>()
              .in(GoodsTagRel::getTagId, Arrays.asList(param.getTagIds().split(","))));
      goodsIds = goodsTagRelList.stream().map(GoodsTagRel::getGoodsId).collect(Collectors.toList());
    }
    List<Long> categoryIdList = param.getCategoryIdList();
    if (categoryIdList == null) {
      categoryIdList = new ArrayList<>();
    }
    if (Objects.nonNull(param.getCategoryId()) && param.getCategoryId() != 0) {
      List<GoodsCategory> goodsCategoryList = goodsCategoryService.list(new LambdaQueryWrapper<GoodsCategory>().eq(GoodsCategory::getParentId, param.getCategoryId()));
      if (!CollectionUtils.isEmpty(goodsCategoryList)) {
        List<Long> list = goodsCategoryList.stream().map(GoodsCategory::getCategoryId).collect(Collectors.toList());
        categoryIdList.addAll(list);
      }
      categoryIdList.add(param.getCategoryId());
    }
    startPage();
    LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<Goods>()
            .ge(null != param.getStartPrice() && 0 != param.getStartPrice(), Goods::getExchangePrice, param.getStartPrice())
            .le(null != param.getEndPrice() && 0 != param.getEndPrice(), Goods::getExchangePrice, param.getEndPrice())
            .in(!CollectionUtils.isEmpty(categoryIdList), Goods::getCategoryId, categoryIdList)
            .like(StringUtils.isNotBlank(param.getGoodsName()), Goods::getTitle, param.getGoodsName())
            .eq(Goods::getStatus, GoodsStatusEnum.PUT_ON)
            .eq(Goods::getExchangeShow, 1)
            .in(!CollectionUtils.isEmpty(goodsIds), Goods::getGoodsId, goodsIds);

    if (Objects.isNull(param.getSaleSort()) && Objects.isNull(param.getPriceSort())){
      queryWrapper.orderByDesc(Goods::getSortWeight)
              .orderByAsc(Goods::getExchangePrice);
    }
    if (Objects.nonNull(param.getSaleSort())) {
      if (param.getSaleSort() == 1) {
        queryWrapper.orderByAsc(Goods::getExchangedQty);
      } else if (param.getSaleSort() == 2) {
        queryWrapper.orderByDesc(Goods::getExchangedQty);
      }
    }

    if (Objects.nonNull(param.getPriceSort())){
      if (param.getPriceSort() == 1) {
        queryWrapper.orderByAsc(Goods::getExchangePrice);
      }else if (param.getPriceSort() == 2) {
        queryWrapper.orderByDesc(Goods::getExchangePrice);
      }
    }

    List<Goods> goodsList = goodsService.list(queryWrapper);
    List<GoodsListVO> goodsListVOList = mapperFacade.mapAsList(goodsList, GoodsListVO.class);
    TableDataInfo rspData = getDataTable(goodsList);
    rspData.setRows(goodsListVOList);
    return rspData;
  }


  /**
   * 查看商品详情
   */
  @PostMapping("/goods/detail")
  @ApiOperation(value = "查看商品详情", notes = "根据商品ID，获取商品信息")
  @ApiResponses(
          @ApiResponse(code = 200, message = "success" , response = GoodsVO.class)
  )
  public AjaxResult getInfo(@RequestBody Goods param) {
    if (null == param.getGoodsId() || 0 == param.getGoodsId()) {
      return AjaxResult.error("参数异常，商品ID缺失");
    }
    Goods goods = goodsService.getById(param.getGoodsId());
    GoodsVO goodsVo = new GoodsVO();
    BeanUtils.copyProperties(goods, goodsVo);
    // 查询SKU列表
    LambdaQueryWrapper<GoodsSku> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(GoodsSku::getGoodsId, goods.getGoodsId());
    queryWrapper.orderByDesc(GoodsSku::getCreatedTime);
    List<GoodsSku> skuList = goodsSkuService.list(queryWrapper);
    if (null != skuList && skuList.size() > 0) {
      goodsVo.setSkuList(skuList);
    }
    return AjaxResult.success(goodsVo);
  }

  /**
   * 提交兑换订单
   */
  @PostMapping("/submit")
  @ApiOperation(value = "提交兑换订单", notes = "提交兑换订单")
  public AjaxResult submit(@RequestBody ExchangeOrderParam param) {
    Long userId = SecurityUtils.getUserId();
    if (null == param.getGoodsId() || 0 == param.getGoodsId() || null == param.getOrderNum()
        || param.getOrderNum() == 0) {
      return AjaxResult.error("参数缺失");
    }
    boolean result = userExchangeOrderService.exchange(userId, param.getGoodsId(), param.getSkuId(),
        param.getOrderNum());
    if (!result) {
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1021);
    }
    return AjaxResult.success();
  }

  /**
   * 查询banner列表
   */
  @PostMapping("/banner/list")
  @ApiOperation(value = "查询banner列表", notes = "banner列表")
  public AjaxResult listBanner(@RequestBody JSONObject param) {
    String location = param.getString("location");
    List<ExchangeBanner> bannerList = exchangeBannerService.list(
        new LambdaQueryWrapper<ExchangeBanner>()
            .eq(ExchangeBanner::getLocation, location).orderByDesc(ExchangeBanner::getSort));
    return AjaxResult.success(bannerList);
  }

  /**
   * 查询分类列表
   */
  @PostMapping("/category/list")
  @ApiOperation(value = "查询分类列表", notes = "分类列表")
  public AjaxResult listCategory(@RequestBody JSONObject param) {
    List<GoodsCategory> categoryList = goodsCategoryService.list(
        new LambdaQueryWrapper<GoodsCategory>()
                .eq(GoodsCategory::getParentId, 0)
            .eq(GoodsCategory::getIsShow, 1).orderByDesc(GoodsCategory::getSort));
    return AjaxResult.success(categoryList);
  }

  /**
   * 查询标签列表
   */
  @PostMapping("/activity/list")
  @ApiOperation(value = "查询标签列表", notes = "标签列表")
  public AjaxResult listActivity(@RequestBody JSONObject param) {
    List<GoodsTag> tagList = goodsTagService.list(new LambdaQueryWrapper<GoodsTag>()
        .eq(GoodsTag::getIsShow, 1).orderByDesc(GoodsTag::getSort));
    Iterator<GoodsTag> iterator = tagList.iterator();
    while (iterator.hasNext()) {
      GoodsTag next = iterator.next();
      int cnt = goodsTagRelService.count(
          new LambdaQueryWrapper<GoodsTagRel>().eq(GoodsTagRel::getTagId, next.getTagId()));
      if (cnt < 2) {
        iterator.remove();
      }
    }
    return AjaxResult.success(tagList);
  }

}
