package com.gxwebsoft.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.mapper.GoodsMapper;
import com.gxwebsoft.shop.service.GoodsService;
import com.gxwebsoft.shop.param.GoodsParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.service.GoodsSkuService;
import com.gxwebsoft.shop.service.GoodsSpecService;
import com.gxwebsoft.shop.service.MerchantService;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 商品记录表Service实现
 *
 * @author 科技小王子
 * @since 2024-07-25 19:22:01
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Resource
    private GoodsSpecService goodsSpecService;
    @Resource
    private GoodsSkuService goodsSkuService;
    @Resource
    private MerchantService merchantService;

    @Override
    public PageResult<Goods> pageRel(GoodsParam param) {
        // 按行业名称查找店铺ID
        if (ObjectUtil.isNotEmpty(param.getIndustryName())) {
          final List<Merchant> merchants = merchantService.list(new LambdaQueryWrapper<Merchant>().like(Merchant::getCategory, param.getIndustryName()));
          final Set<Integer> merchantIds = merchants.stream().map(Merchant::getMerchantId).collect(Collectors.toSet());
          param.setShopIdsByIndustry(merchantIds);
        }
        PageParam<Goods, GoodsParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<Goods> list = baseMapper.selectPageRel(page, param);

        final Set<Integer> goodsIds = list.stream().map(Goods::getGoodsId).collect(Collectors.toSet());
        if (!CollectionUtils.isEmpty(goodsIds)) {
          final User loginUser = param.getLoginUser();
          final List<GoodsSpec> specs = goodsSpecService.list(new LambdaQueryWrapper<GoodsSpec>().in(GoodsSpec::getGoodsId, goodsIds));
          final List<GoodsSku> skus = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>().in(GoodsSku::getGoodsId, goodsIds));
          final Map<Integer, List<GoodsSpec>> collectSpecs = specs.stream().collect(Collectors.groupingBy(GoodsSpec::getGoodsId));
          final Map<Integer, List<GoodsSku>> collectSkus = skus.stream().collect(Collectors.groupingBy(GoodsSku::getGoodsId));
          list.forEach(d -> {
            final List<GoodsSpec> goodsSpecs = collectSpecs.get(d.getGoodsId());
            if (!CollectionUtils.isEmpty(goodsSpecs)) {
              final GoodsSpec spec = goodsSpecs.get(0);
              final String value = spec.getSpecValue();
              final Object object = JSONUtil.parseObject(value,Object.class);
              d.setGoodsSpecValue(object);
              // 整理商品价格
              if (loginUser != null) {
                if(loginUser.getGradeId().equals(33)){
                  d.setPrice(d.getDealerPrice());
                }
                if(loginUser.getGradeId().equals(0)){
                  d.setPrice(d.getSalePrice());
                }
              }
            }
//            d.setGoodsSkus(collectSkus.get(d.getGoodsId()));
          });
        }

        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<Goods> listRel(GoodsParam param) {
        List<Goods> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<Goods, GoodsParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public Goods getByIdRel(Integer goodsId) {
        GoodsParam param = new GoodsParam();
        param.setGoodsId(goodsId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public void saveBatchByAsync(Goods goods) {
      // 保存商品多规格
      if (goods.getSpecs().equals(1)) {
        final GoodsSpec spec = goods.getGoodsSpec();
        if (spec != null) {
          spec.setGoodsId(goods.getGoodsId());
          if(spec.getSpecValue() == null){
            spec.setSpecValue(JSON.toJSONString(new ArrayList<>()));
          }
          goodsSpecService.save(spec);

          // 保存商品sku表
          final List<GoodsSku> goodsSkus = goods.getGoodsSkus();
          if (!CollectionUtils.isEmpty(goodsSkus)) {
            goodsSkus.forEach(d -> {
              d.setGoodsId(goods.getGoodsId());
            });
            goodsSkuService.saveBatch(goodsSkus);
          }
        }
      }
    }

  @Override
  public List<Goods> getGoodsSpec() {
    // 多表查询
    MPJLambdaWrapper<Goods> mpjLambdaWrapper = new MPJLambdaWrapper<>();
    mpjLambdaWrapper.selectAll(Goods.class)
      .select(GoodsSpec::getSpecValue)
      .select(GoodsSpec::getSpecName)
      .leftJoin(GoodsSpec.class,GoodsSpec::getGoodsId,GoodsSpec::getGoodsId);
    return baseMapper.selectJoinList(Goods.class, mpjLambdaWrapper);
  }

  @Override
  public List<Goods> getGoodsSpecType0() {
    // 多表查询
    MPJLambdaWrapper<Goods> mpjLambdaWrapper = new MPJLambdaWrapper<>();
    mpjLambdaWrapper.selectAll(Goods.class)
      .select(GoodsSpec::getSpecValue)
      .select(GoodsSpec::getSpecName)
      .leftJoin(GoodsSpec.class,GoodsSpec::getGoodsId,GoodsSpec::getGoodsId)
      .gt(Goods::getStock,0)
      .eq(Goods::getType,0);
    return baseMapper.selectJoinList(Goods.class, mpjLambdaWrapper);
  }

  @Override
  public List<Goods> getGoodsSpecType1() {
    // 多表查询
    MPJLambdaWrapper<Goods> mpjLambdaWrapper = new MPJLambdaWrapper<>();
    mpjLambdaWrapper.selectAll(Goods.class)
      .select(GoodsSpec::getSpecValue)
      .select(GoodsSpec::getSpecName)
      .leftJoin(GoodsSpec.class,GoodsSpec::getGoodsId,GoodsSpec::getGoodsId)
      .gt(Goods::getStock,0)
      .eq(Goods::getType,1);
    return baseMapper.selectJoinList(Goods.class, mpjLambdaWrapper);
  }

}
