package com.mmc.pms.service.Impl;

import com.mmc.pms.common.ResultBody;
import com.mmc.pms.common.ResultEnum;
import com.mmc.pms.dao.MiniProgramProductMallDao;
import com.mmc.pms.dao.WebDeviceDao;
import com.mmc.pms.entity.GoodsInfoDO;
import com.mmc.pms.entity.*;
import com.mmc.pms.model.dto.*;
import com.mmc.pms.model.qo.GoodsInfoQO;
import com.mmc.pms.page.PageResult;
import com.mmc.pms.service.MiniProgramProductMallService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author small @Date 2023/5/16 15:08 @Version 1.0
 */
@Service
public class MiniProgramProductMallServiceImpl implements MiniProgramProductMallService {

  @Autowired private MiniProgramProductMallDao goodsInfoDao;
  @Autowired private WebDeviceDao webDeviceDao;

  @Override
  public ResultBody getAppGoodsInfoDetail(Integer goodsId) {
    // 查询此商品是否下架或删除
    GoodsInfoDO goodsInfoDO = goodsInfoDao.getGoodsInfoByGoodsId(goodsId);
    if (goodsInfoDO == null || goodsInfoDO.getShelfStatus().equals(0)) {
      return ResultBody.error(ResultEnum.SHOP_GOODS_NOT_ERROR);
    }
    AppGoodsInfoDetailDTO appGoodsInfoDetailDTO = new AppGoodsInfoDetailDTO();
    appGoodsInfoDetailDTO
        .setId(goodsInfoDO.getId())
        .setGoodsName(goodsInfoDO.getGoodsName())
        .setGoodsVideoId(goodsInfoDO.getGoodsVideoId())
        .setMasterTypeId(goodsInfoDO.getMasterTypeId())
        .setRepoId(goodsInfoDO.getRepoId())
        .setSortTypeId(goodsInfoDO.getSortTypeId())
        .setShelfStatus(goodsInfoDO.getShelfStatus())
        .setSlaveTypeId(goodsInfoDO.getSlaveTypeId())
        .setShareFlyServiceId(goodsInfoDO.getShareFlyServiceId())
        .setGoodsVideo(goodsInfoDO.getVideoUrl())
        .setTag(goodsInfoDO.getTag())
        .setPid(goodsInfoDO.getPid());
    // 获取商品图片信息
    List<GoodsImgDO> goodsImgDO = goodsInfoDao.listGoodsInfoByGoodsId(goodsId);
    appGoodsInfoDetailDTO.setImages(
        goodsImgDO.stream().map(GoodsImgDO::buildGoodsImgDTO).collect(Collectors.toList()));
    // 获取商品详情信息
    GoodsDetailDO goodsDetailDO = goodsInfoDao.getGoodsDetailByGoodsId(goodsId);
    appGoodsInfoDetailDTO.setGoodsDetail(goodsDetailDO.buildGoodsDetailInfoDTO());
    // 获取常见问题信息
    List<GoodsQaDO> goodsQaDO = goodsInfoDao.listGoodsQaInfoByGoodsId(goodsId);
    appGoodsInfoDetailDTO.setQuestion(
        goodsQaDO.stream().map(GoodsQaDO::buildGoodsQaDTO).collect(Collectors.toList()));
    // 获取其他服务信息
    List<GoodsServiceDO> goodsServiceDO = goodsInfoDao.listGoodsServiceByGoodsId(goodsId);
    appGoodsInfoDetailDTO.setOtherService(
        goodsServiceDO.stream()
            .map(GoodsServiceDO::buildGoodsOtherServiceDTO)
            .collect(Collectors.toList()));
    // 判断商品是什么类型
    if (!goodsInfoDO.getSortTypeId().equals(2)) {
      // 获取该商品绑定的sku信息
      List<MallProdSkuInfoDO> mallProdSkuInfo = goodsInfoDao.getMallProdInfoByGoodsId(goodsId);
      // 获取该商品绑定的规格信息
      List<MallProdSkuInfoSpecDO> mallProdSkuInfoSpecList =
          goodsInfoDao.listMallProdSkuInfoSpec(goodsId);
      Map<Integer, List<MallProdSkuInfoSpecDO>> specMap =
          mallProdSkuInfoSpecList.stream()
              .collect(Collectors.groupingBy(MallProdSkuInfoSpecDO::getMallProdSkuInfoId));
      List<GoodsSpecDTO> list =
          mallProdSkuInfo.stream()
              .map(
                  d -> {
                    // 获取sku下规格信息
                    List<MallProdSkuInfoSpecDO> mallProdSkuInfoSpecDOList = specMap.get(d.getId());
                    List<ProductSpecDO> productSpecList =
                        goodsInfoDao.listProductSpecInfo(
                            mallProdSkuInfoSpecDOList.stream()
                                .map(MallProdSkuInfoSpecDO::getProductSpecId)
                                .collect(Collectors.toList()));
                    List<MallProductSpecDTO> collect =
                        productSpecList.stream()
                            .map(ProductSpecDO::buildMallProductSpecDTO)
                            .collect(Collectors.toList());
                    collect.stream()
                        .peek(
                            m -> {
                              for (MallProdSkuInfoSpecDO mallProdSkuInfoSpecDO :
                                  mallProdSkuInfoSpecDOList) {
                                if (m.getProductSpec()
                                    .equals(mallProdSkuInfoSpecDO.getProductSpecId())) {
                                  m.setId(mallProdSkuInfoSpecDO.getId());
                                  break;
                                }
                              }
                            })
                        .collect(Collectors.toList());
                    GoodsSpecDTO goodsSpecDTO = new GoodsSpecDTO();
                    goodsSpecDTO
                        .setId(d.getId())
                        .setSkuId(d.getProdSkuId())
                        .setGoodsSpecName(d.getProdSkuSpecName())
                        .setSkuName(d.getProductSkuName())
                        .setBrandInfoId(d.getBrandInfoId())
                        .setGoodsTypeId(d.getGoodsTypeId())
                        .setTypeName(d.getTypeName())
                        .setChooseType(d.getChooseType())
                        .setSkuUnitId(d.getSkuUnitId())
                        .setUnitName(d.getUnitName())
                        .setMust(d.getMust())
                        .setProductSpecList(collect);
                    return goodsSpecDTO;
                  })
              .collect(Collectors.toList());
      appGoodsInfoDetailDTO.setGoodsSpec(list);
    } else {
      appGoodsInfoDetailDTO.setGoodsSpec(getIndustrySpecInfo(goodsId));
    }
    return ResultBody.success(appGoodsInfoDetailDTO);
  }

  @Override
  public ResultBody listGoodsByQO(GoodsInfoQO param) {
    int count = goodsInfoDao.countListGoodsByQO(param);
    if (count == 0) {
      return ResultBody.success(
          PageResult.buildPage(param.getPageNo(), param.getPageSize(), count));
    }
    int pageNo = param.getPageNo();
    param.buildCurrentPage();
    List<GoodsInfoDO> list = goodsInfoDao.listGoodsByQO(param);
    // 找出行业对应的序号
    List<GoodsTypeDO> ids = goodsInfoDao.listIndustryIdBySort();
    int order = 0;
    /*if (param.getMasterTypeId() != null) {
      for (int i = 0; i < ids.size(); i++) {
        if (param.getMasterTypeId().toString().equals(ids.get(i).getId().toString())) {
          order = i + 1;
          break;
        }
      }
    }*/
    List<AppGoodsInfoDTO> pageList = new ArrayList<>();
    for (GoodsInfoDO d : list) {
      AppGoodsInfoDTO appGoodsInfoDTO = d.buildAppGoodsInfoDTO();
      // 直接看该服务在当前行业对应所有服务中在第几个
      for (int j = 0; j < list.size(); j++) {
        if (appGoodsInfoDTO.getId().toString().equals(list.get(j).getId().toString())) {
          if (j < 9) {
            appGoodsInfoDTO.setCode(order + "0" + (j + 1));
          } else {
            appGoodsInfoDTO.setCode(order + "" + (j + 1));
          }
          break;
        }
      }
      if (appGoodsInfoDTO.getShelfStatus() == 1) {
        pageList.add(appGoodsInfoDTO);
      }
    }
    return ResultBody.success(PageResult.buildPage(pageNo, param.getPageSize(), count, pageList));
  }


  private List<GoodsSpecDTO> getIndustrySpecInfo(Integer goodsInfoId) {
    // 获取商品对应绑定的行业sku信息
    List<MallIndustrySkuInfoDO> mallIndustrySkuInfoList = goodsInfoDao.getMallIndustrySkuInfo(goodsInfoId);
    List<GoodsSpecDTO> list = mallIndustrySkuInfoList.stream().map(MallIndustrySkuInfoDO::buildGoodsSpecDTO).collect(Collectors.toList());
    // 根据商品id查出该商品下绑定的规格信息
    List<MallIndustrySkuInfoSpecDO> mallIndustrySkuInfoSpec = goodsInfoDao.getIndustrySkuInfoSpec(goodsInfoId);
    list = list.stream().peek(d -> {
      List<MallIndustrySpecDTO> industrySpec = new ArrayList<>();
      for (MallIndustrySkuInfoSpecDO e : mallIndustrySkuInfoSpec) {
        if (d.getId().equals(e.getMallIndustrySkuInfoId())) {
          IndustrySpecDO industrySpecDO = e.getIndustrySpecDO();
          // 获取商品清单信息
          List<IndustryProductInventoryDO> industryProdInventory = goodsInfoDao.getIndustryProductInventory(e.getIndustrySpecId());
          List<ProductInventoryVO> productInventoryList = new ArrayList<>();
          // 获取行业规格绑定的产品规格信息
          List<InventorySpecDO> inventorySpecDOList = goodsInfoDao.listInventorySpec(industryProdInventory.stream().map(IndustryProductInventoryDO::getId).collect(Collectors.toList()));
          Map<Integer, List<InventorySpecDO>> inventoryMap = inventorySpecDOList.stream().collect(Collectors.groupingBy(InventorySpecDO::getIndustryProductInventoryId));
          getIndustrySpecOnProdSpecInfo(industryProdInventory, productInventoryList, inventoryMap);
          MallIndustrySpecDTO industrySpecDTO = industrySpecDO.buildMallIndustrySpecDTO();
          industrySpecDTO.setId(e.getId());
          industrySpecDTO.setIndustrySpecId(e.getIndustrySpecId());
          industrySpecDTO.setIndustrySkuId(d.getSkuId());
          industrySpecDTO.setProductInventoryList(productInventoryList);
          industrySpec.add(industrySpecDTO);
        }
      }
      d.setIndustrySpecList(industrySpec);
    }).collect(Collectors.toList());
    return list;
  }

  private void getIndustrySpecOnProdSpecInfo(
      List<IndustryProductInventoryDO> industryProdInventory,
      List<ProductInventoryVO> productInventoryList,
      Map<Integer, List<InventorySpecDO>> inventoryMap) {
    for (IndustryProductInventoryDO industryProductInventoryDO : industryProdInventory) {
      List<InventorySpecDO> inventorySpec = inventoryMap.get(industryProductInventoryDO.getId());
      if (!CollectionUtils.isEmpty(inventorySpec)) {
        List<ProductSpecVO> productSpecList =
            inventorySpec.stream()
                .map(
                    in -> {
                      ProductSpecDO productSpecDetail =
                          goodsInfoDao.getProductSpecDetail(in.getProductSpecId());
                      ProductSpecVO productSpecVO = new ProductSpecVO();
                      BeanUtils.copyProperties(productSpecDetail, productSpecVO);
                      return productSpecVO;
                    })
                .collect(Collectors.toList());
        ProductSkuDO productSkuDetail =
            goodsInfoDao.getProductSkuDetail(industryProductInventoryDO.getProductSkuId());
        GoodsProductSkuVO goodsProductSkuVO = new GoodsProductSkuVO();
        BeanUtils.copyProperties(productSkuDetail, goodsProductSkuVO);
        // 添加数据
        ProductInventoryVO productInventoryVO = new ProductInventoryVO();
        productInventoryVO.setSelect(industryProductInventoryDO.getSelected());
        productInventoryVO.setProductSku(goodsProductSkuVO);
        productInventoryVO.setProductSpecList(productSpecList);
        productInventoryList.add(productInventoryVO);
      }
    }
  }
}
