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

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.dto.EsPageDTO;
import com.tmerclub.cloud.api.product.feign.SpuFeignClient;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.product.constant.SupplierDeliveryType;
import com.tmerclub.cloud.common.product.constant.SupplierSpuType;
import com.tmerclub.cloud.common.product.dto.ProductSearchDTO;
import com.tmerclub.cloud.common.product.vo.SpuVO;
import com.tmerclub.cloud.common.product.vo.search.ProductSearchVO;
import com.tmerclub.cloud.common.product.vo.search.SpuAdminVO;
import com.tmerclub.cloud.common.product.vo.search.SpuSearchVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.BeanUtil;
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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品搜索
 *
 * @author tmerclub
 * @date 2020/11/16
 */
@RestController("appSearchSpuController")
@RequestMapping("/ua/search")
@Tag(name = "spu搜索接口")
public class ProductSearchController {

    @Autowired
    private ProductSearchManager productSearchManager;
    @DubboReference
    private SpuFeignClient spuFeignClient;


    @GetMapping("/pcPage")
    @Operation(summary = "pc端商品搜索接口", description = "pc端商品搜索接口")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> pcPage(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        productSearchDTO.setAttrMap(productSearchManager.splitAttr(productSearchDTO.getAttrIds()));
        productSearchDTO.setAppDisplay(true);
        productSearchDTO.setIsSupplierType(1);
        EsPageVO<ProductSearchVO> searchPage = productSearchManager.page(pageDTO, productSearchDTO);
        productSearchManager.loadData(productSearchDTO, searchPage.getList());
        //检查代销商品是否改变了原有得供应商图片和名字，如果改变了显示商家改变后的图片和名字，没有改变则显示供应商信息
        ServerResponseEntity<List<ProductSearchVO>> listServerResponseEntity = spuFeignClient.usCheckCommissionSpuIsUpdateMsg(searchPage.getList());
        List<ProductSearchVO> result = listServerResponseEntity.getData();
        //仅看有货
        if (Objects.nonNull(productSearchDTO.getHasStock()) && Objects.equals(productSearchDTO.getHasStock(), 1)) {
            //供应商发货的代销商品Spu
            List<SpuSearchVO> commissionList = searchPage.getList().get(0).getSpus().stream().filter(item -> Objects.equals(item.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value()) && Objects.equals(item.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value())).collect(Collectors.toList());
            List<Long> commisionIds = commissionList.stream().map(SpuSearchVO::getSpuId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(commisionIds)) {
                List<SpuVO> spuIsSyn = spuFeignClient.getSpuIsSynUpdate(commisionIds).getData();
                Map<Long, Integer> stockInfo = spuIsSyn.stream().collect(Collectors.toMap(SpuVO::getSpuId, SpuVO::getTotalStock));
                List<Long> zeroStock = new ArrayList<>(Constant.INITIAL_CAPACITY);
                for (Long spuId : commisionIds) {
                    if (Objects.equals(stockInfo.get(spuId), 0)) {
                        zeroStock.add(spuId);
                    }
                }
                //获取供应商发货的代销商品的id,过滤掉供应商库存为0的商品
                List<SpuSearchVO> searchList = result.get(0).getSpus().stream().filter(spuSearch -> !zeroStock.contains(spuSearch.getSpuId())).collect(Collectors.toList());
                result.get(0).setSpus(searchList);
            }

        }


        searchPage.setList(result);
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/page")
    @Operation(summary = "商品搜索接口（仅商品信息）", description = "商品搜索接口")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> page(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        return ServerResponseEntity.success(simplePage(pageDTO, productSearchDTO));
    }

    @GetMapping("/searchPage")
    @Operation(summary = "手机端商品搜索接口", description = "手机端商品搜索接口")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> searchPage(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        productSearchDTO.setAttrMap(productSearchManager.splitAttr(productSearchDTO.getAttrIds()));
        EsPageVO<ProductSearchVO> page = simplePage(pageDTO, productSearchDTO);
        ProductSearchVO productSearchVO = page.getList().get(0);
        ProductSearchVO productInfo = productSearchManager.searchExtension(pageDTO, productSearchDTO);
        if (!Objects.isNull(productInfo.getAttrs())) {
            productSearchManager.loadAttr(productInfo, null);
        }
        productSearchVO.setBrands(productInfo.getBrands());
        productSearchVO.setAttrs(productInfo.getAttrs());
        productSearchVO.setCategorys(productInfo.getCategorys());
        //检查代销商品是否改变了原有得供应商图片和名字，如果改变了显示商家改变后的图片和名字，没有改变则显示供应商信息
        ServerResponseEntity<List<ProductSearchVO>> listServerResponseEntity = spuFeignClient.usCheckCommissionSpuIsUpdateMsg(page.getList());
        List<ProductSearchVO> result = listServerResponseEntity.getData();
        page.setList(result);
        return ServerResponseEntity.success(page);
    }

    @GetMapping("/pageDistributionSpu")
    @Operation(summary = "分销商品列表", description = "分销商品列表")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> pageDistributionSpu(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        productSearchDTO.setDistributionSpu(Boolean.TRUE);
        productSearchDTO.setFetchSource(EsConstant.DISTRIBUTION_SPU_SOURCE);
        EsPageVO<ProductSearchVO> searchPage = productSearchManager.page(pageDTO, productSearchDTO);
        return ServerResponseEntity.success(searchPage);
    }

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

    private EsPageVO<ProductSearchVO> simplePage(EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        EsPageVO<ProductSearchVO> searchPage = productSearchManager.spuPage(pageDTO, productSearchDTO);
        productSearchManager.loadData(productSearchDTO, searchPage.getList());
        //检查代销商品是否改变了原有得供应商图片和名字，如果改变了显示商家改变后的图片和名字，没有改变则显示供应商信息
        List<SpuSearchVO> spus = searchPage.getList().get(0).getSpus();
        List<SpuAdminVO> spuAdminList = BeanUtil.mapAsList(spus, SpuAdminVO.class);
        List<SpuAdminVO> data = spuFeignClient.checkCommissionSpuIsUpdateMsg(spuAdminList).getData();
        List<SpuSearchVO> spuSearchList = BeanUtil.mapAsList(data, SpuSearchVO.class);
        Map<Long, SpuSearchVO> spuMap = spus.stream().collect(Collectors.toMap(SpuSearchVO::getSpuId, s -> s));
        for (SpuSearchVO spuSearchVO : spuSearchList) {
            if (!spuMap.containsKey(spuSearchVO.getSpuId())) {
                continue;
            }
            SpuSearchVO spu = spuMap.get(spuSearchVO.getSpuId());
            spuSearchVO.setSpuActivity(spu.getSpuActivity());
        }

        searchPage.getList().get(0).setSpus(spuSearchList);
        return searchPage;
    }
}
