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

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.dto.EsPageDTO;
import com.tmerclub.cloud.api.product.feign.CategoryFeignClient;
import com.tmerclub.cloud.api.product.feign.SkuStockFeignClient;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.i18n.I18nMessage;
import com.tmerclub.cloud.common.i18n.LanguageEnum;
import com.tmerclub.cloud.common.product.bo.EsBrandBO;
import com.tmerclub.cloud.common.product.constant.SpuMold;
import com.tmerclub.cloud.common.product.constant.SupplierSpuType;
import com.tmerclub.cloud.common.product.dto.ProductSearchDTO;
import com.tmerclub.cloud.common.product.vo.CategoryVO;
import com.tmerclub.cloud.common.product.vo.search.SpuAdminVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
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.commons.compress.utils.Lists;
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.Set;
import java.util.stream.Collectors;

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

    @Autowired
    private ProductSearchManager productSearchManager;
    @Autowired
    private SkuStockFeignClient skuStockFeignClient;

    @DubboReference
    private CategoryFeignClient categoryFeignClient;

    @GetMapping("/page")
    @Operation(summary = "商品信息列表", description = "商品信息列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> page(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        Long supplierId = AuthUserContext.get().getTenantId();
        productSearchDTO.setFetchSource(EsConstant.SUPPLIER_FETCH_SOURCE);
        productSearchDTO.setSupplierId(supplierId);
        productSearchDTO.setShopId(-1L);
        productSearchDTO.setSupplierSpuType(SupplierSpuType.YES.value());
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        List<SpuAdminVO> list = searchPage.getList();
        Set<Long> categoryIds = list.stream().map(SpuAdminVO::getCategoryId).collect(Collectors.toSet());
        ServerResponseEntity<List<CategoryVO>> categoryResp = categoryFeignClient.getByCategoryIds(categoryIds);
        Map<Long, CategoryVO> categoryMap = categoryResp.getData().stream().collect(Collectors.toMap(CategoryVO::getCategoryId, c -> c));
        List<Long> comboSpuList = Lists.newArrayList();
        for (SpuAdminVO spuAdminVO : list) {
            //品牌名称
            setBrandName(spuAdminVO);
            spuAdminVO.setCategoryNames(Objects.nonNull(spuAdminVO.getCategoryId()) ? Objects.equals(I18nMessage.getLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang()) ? categoryMap.get(spuAdminVO.getCategoryId()).getCategoryLangList().get(0).getName() : categoryMap.get(spuAdminVO.getCategoryId()).getCategoryLangList().get(1).getName() : null);
            if(Objects.equals(spuAdminVO.getSpuMold(), SpuMold.COMBO.value())) {
                comboSpuList.add(spuAdminVO.getSpuId());
            }
        }
        // 如果是组合商品,需要重新计算一下库存
        if (CollUtil.isNotEmpty(comboSpuList)) {
            ServerResponseEntity<Map<Long, Integer>> spuIdStockMapResp = skuStockFeignClient.calculateStockByComboSpuList(comboSpuList);
            Map<Long, Integer> spuStockMap = spuIdStockMapResp.getData();
            for (SpuAdminVO spuAdminVO : list) {
                if(!spuStockMap.containsKey(spuAdminVO.getSpuId())){
                    continue;
                }
                spuAdminVO.setStock(spuStockMap.get(spuAdminVO.getSpuId()));
            }
        }
        // 加载商品总库存
        this.loadSpuStock(searchPage);
        return ServerResponseEntity.success(searchPage);

    }

    @GetMapping("/pageDistributionSpu")
    @Operation(summary = "分销商品列表", description = "分销商品列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> pageDistributionSpu(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        if (!Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
            productSearchDTO.setShopId(shopId);
        }
        productSearchDTO.setFetchSource(EsConstant.DISTRIBUTION_SPU_SOURCE);
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        List<SpuAdminVO> list = searchPage.getList();
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/stockWarningCount")
    @Operation(summary = "库存预警数目", description = "库存预警数目")
    public ServerResponseEntity<Long> stockWarningCount() {
        Long supplierId = AuthUserContext.get().getTenantId();
        ProductSearchDTO productSearchDTO = new ProductSearchDTO();
        productSearchDTO.setFetchSource(EsConstant.SUPPLIER_FETCH_SOURCE);
        productSearchDTO.setSupplierId(supplierId);
        productSearchDTO.setShopId(-1L);
        productSearchDTO.setSupplierSpuType(SupplierSpuType.YES.value());
        productSearchDTO.setStockWarning(1);
        productSearchDTO.setDataType(0);
        EsPageDTO pageDTO = new EsPageDTO();
        pageDTO.setPageSize(1);
        pageDTO.setPageNum(1);
        EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO);
        return ServerResponseEntity.success(searchPage.getTotal());
    }

    public void setBrandName(SpuAdminVO spuAdminVO) {
        //品牌名称
        Integer lang = I18nMessage.getLang();
        EsBrandBO brand = spuAdminVO.getBrand();
        if (!Objects.isNull(brand)) {
            if (Objects.equals(lang, LanguageEnum.LANGUAGE_ZH_CN.getLang())) {
                spuAdminVO.setBrandName(brand.getBrandNameZh());
            }
            if (Objects.equals(lang, LanguageEnum.LANGUAGE_EN.getLang())) {
                spuAdminVO.setBrandName(brand.getBrandNameEn());
            }
        }
    }

    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());
    }
}
