
package com.tmerclub.cloud.search.controller.platform;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.dto.EsPageDTO;
import com.tmerclub.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.tmerclub.cloud.api.multishop.vo.ShopDetailVO;
import com.tmerclub.cloud.api.product.feign.SkuStockFeignClient;
import com.tmerclub.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.tmerclub.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.product.constant.SupplierSpuType;
import com.tmerclub.cloud.common.product.dto.ProductSearchDTO;
import com.tmerclub.cloud.common.product.vo.search.ProductSearchVO;
import com.tmerclub.cloud.common.product.vo.search.SearchSpuTagVO;
import com.tmerclub.cloud.common.product.vo.search.SpuAdminVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.search.constant.EsConstant;
import com.tmerclub.cloud.search.manager.ProductSearchManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品搜索
 *
 * @author tmerclub
 * @date 2020/11/16
 */
@RestController("platformSearchSpuController")
@RequestMapping("/p/search")
@Tag(name = "platform-spu列表接口")
public class ProductSearchController {

    @Autowired
    private ProductSearchManager productSearchManager;
    @DubboReference
    private SkuStockFeignClient skuStockFeignClient;
    @DubboReference
    private ShopDetailFeignClient shopDetailFeignClient;
    @DubboReference
    private SupplierDetailFeignClient supplierDetailFeignClient;

    @GetMapping("/page")
    @Operation(summary = "商品管理信息列表（平台端）", description = "商品管理信息列表（平台端）")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> adminPage(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        productSearchDTO.setFetchSource(EsConstant.PLATFORM_FETCH_SOURCE);
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        List<SpuAdminVO> spuAdminVOList = searchPage.getList();
        List<SpuAdminVO> supplierSpuList = spuAdminVOList.stream().filter(s -> Objects.equals(s.getSupplierSpuType(), SupplierSpuType.YES.value())).collect(Collectors.toList());
        List<Long> supplierIds = supplierSpuList.stream().map(SpuAdminVO::getSupplierId).collect(Collectors.toList());
        List<SupplierApiDetailVO> supplierApiDetailVOList = supplierDetailFeignClient.listSupplierDetailBySupplierIds(supplierIds).getData();
        Map<Long, SupplierApiDetailVO> supplierMap = supplierApiDetailVOList.stream().collect(Collectors.toMap(SupplierApiDetailVO::getSupplierId, s -> s));
        //供应商商品的店铺名称
        for (SpuAdminVO supplierSpu : supplierSpuList) {
            supplierSpu.setShopName(supplierMap.get(supplierSpu.getSupplierId()).getSupplierName());
        }
        // 店铺名称
        if (CollUtil.isNotEmpty(spuAdminVOList) && spuAdminVOList.size() != 0) {
            List<Long> shopIdList = spuAdminVOList.stream().map(SpuAdminVO::getShopId).collect(Collectors.toList());
            List<ShopDetailVO> shopDetailVOList = shopDetailFeignClient.listByShopIds(shopIdList).getData();
            Map<Long, List<ShopDetailVO>> shopDetailVoMap = shopDetailVOList.stream().collect(Collectors.groupingBy(ShopDetailVO::getShopId));
            for (SpuAdminVO spuAdminVO : spuAdminVOList) {
                List<ShopDetailVO> shopDetailList = shopDetailVoMap.get(spuAdminVO.getShopId());
                if (Objects.isNull(shopDetailList)) {
                    continue;
                }
                spuAdminVO.setShopName(shopDetailList.get(0).getShopName());
            }
        }
        // 加载商品总库存
        this.loadSpuStock(searchPage);
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/scorePage")
    @Operation(summary = "积分商品搜索（平台端）", description = "积分商品搜索（平台端）")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> scorePage(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        productSearchDTO.setFetchSource(EsConstant.PLATFORM_FETCH_SOURCE);
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        for (SpuAdminVO spuAdminVO : searchPage.getList()) {
            if (Objects.equals(spuAdminVO.getSupplierSpuType(), SupplierSpuType.YES.value()) && Objects.isNull(spuAdminVO.getShopName())) {
                spuAdminVO.setShopName(spuAdminVO.getSupplierName());
            }
        }
        // 加载商品总库存
        this.loadSpuStock(searchPage);
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/tagPage")
    @Operation(summary = "分组商品列表（平台端）", description = "分组商品列表（平台端）")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> tagPage(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        productSearchDTO.setFetchSource(EsConstant.PLATFORM_TAG_FETCH_SOURCE);
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        // 插入序号
        for (SpuAdminVO spuAdminVO : searchPage.getList()) {
            for (SearchSpuTagVO tag : spuAdminVO.getTags()) {
                if (Objects.equals(productSearchDTO.getTagId(), tag.getTagId())) {
                    spuAdminVO.setSeq(tag.getSeq());
                }
            }
            spuAdminVO.setTags(null);
        }
        // 加载商品总库存
        this.loadSpuStock(searchPage);
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/renovationPage")
    @Operation(summary = "商品信息列表(平台装修商品列表)", description = "商品信息列表(平台装修商品列表)")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> renovationPage(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        EsPageVO<ProductSearchVO> searchPage = productSearchManager.showSpuTypeRenovationPage(pageDTO, productSearchDTO);
        return ServerResponseEntity.success(searchPage);
    }

    private void loadSpuStock(EsPageVO<SpuAdminVO> searchPage) {
        ServerResponseEntity<List<SpuAdminVO>> listServerResponseEntity = skuStockFeignClient.loadProdStock(searchPage.getList());
        if (!listServerResponseEntity.isSuccess()) {
            throw new LuckException(listServerResponseEntity.getMsg());
        }
        searchPage.setList(listServerResponseEntity.getData());
    }
}
