
package com.tmerclub.cloud.live.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.feign.SearchSpuFeignClient;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.cache.constant.LiveCacheNames;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.product.constant.SpuStatus;
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.SpuSearchVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.live.mapper.LiveRoomProdMapper;
import com.tmerclub.cloud.live.model.LiveRoomProd;
import com.tmerclub.cloud.live.service.LiveRoomProdService;
import com.tmerclub.cloud.live.vo.LiveMsgItemVO;
import com.tmerclub.cloud.live.vo.LiveRoomProdVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 直播商品
 * @author TRACK
 */
@Service
public class LiveRoomProdServiceImpl implements LiveRoomProdService {

    @Autowired
    private LiveRoomProdMapper liveRoomProdMapper;
    @DubboReference
    private SearchSpuFeignClient searchSpuFeignClient;

    @Override
    public void save(Long roomId, List<Long> spuIds) {
        if (CollUtil.isEmpty(spuIds)) {
            return;
        }
        // 过滤掉状态不正常的商品
        List<SpuSearchVO> spuList = getSpuList(spuIds);
        if (CollUtil.isEmpty(spuList)) {
            return;
        }
        List<LiveRoomProd> saveList = new ArrayList<>();
        for (SpuSearchVO spuSearchVO : spuList) {
            LiveRoomProd liveRoomProd = new LiveRoomProd();
            liveRoomProd.setSpuId(spuSearchVO.getSpuId());
            liveRoomProd.setRoomId(roomId);
            liveRoomProd.setExplainStatus(0);
            saveList.add(liveRoomProd);
        }
        // 批量保存
        liveRoomProdMapper.saveBatch(saveList);
    }

    private List<SpuSearchVO> getSpuList(List<Long> spuIds) {
        ProductSearchDTO productSearchDTO = new ProductSearchDTO();
        productSearchDTO.setSpuIds(spuIds);
        productSearchDTO.setSpuStatus(SpuStatus.PUT_SHELF.value());
        ServerResponseEntity<List<SpuSearchVO>> spuResponse = searchSpuFeignClient.simpleList(productSearchDTO);
        if (!spuResponse.isSuccess()) {
            throw new LuckException(spuResponse.getMsg());
        }
        List<SpuSearchVO> spuList = spuResponse.getData();
        return spuList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = LiveCacheNames.LIVE_ROOM_PROD, key = "#roomId")
    public void update(Long roomId, List<Long> spuIds) {
        liveRoomProdMapper.deleteByRoomId(roomId);
        save(roomId, spuIds);
    }

    @Override
    @CacheEvict(cacheNames = LiveCacheNames.LIVE_ROOM_PROD, key = "#roomId")
    public void delete(Long roomId) {
        liveRoomProdMapper.deleteByRoomId(roomId);
    }

    @Override
    public List<LiveRoomProdVO> listLiveRoomProdInfo(Long roomId) {
        List<LiveRoomProdVO> liveRoomProds = liveRoomProdMapper.getByRoomId(roomId);
        if (CollUtil.isEmpty(liveRoomProds)) {
            return new ArrayList<>();
        }
        List<Long> spuIds = liveRoomProds.stream().map(LiveRoomProdVO::getSpuId).toList();
        List<SpuSearchVO> spuList = getSpuList(spuIds);
        if (CollUtil.isEmpty(spuList)) {
            return new ArrayList<>();
        }
        Map<Long, SpuSearchVO> spuMap = spuList.stream().collect(Collectors.toMap(SpuSearchVO::getSpuId, s -> s));
        Iterator<LiveRoomProdVO> iterator = liveRoomProds.iterator();
        while (iterator.hasNext()) {
            LiveRoomProdVO liveRoomProdVO = iterator.next();
            SpuSearchVO spuSearchVO = spuMap.get(liveRoomProdVO.getSpuId());
            if (Objects.isNull(spuSearchVO)) {
                iterator.remove();
                continue;
            }
            liveRoomProdVO.setSpuSearchVO(spuSearchVO);
        }
        return liveRoomProds;
    }

    @Override
    @Cacheable(cacheNames = LiveCacheNames.LIVE_ROOM_PROD, key = "#roomId")
    public List<LiveRoomProdVO> listLiveRoomProd(Long roomId) {
        return liveRoomProdMapper.getByRoomId(roomId);
    }

    @Override
    @CacheEvict(cacheNames = LiveCacheNames.LIVE_ROOM_PROD, key = "#roomId")
    public int updateExplainStatus(Long roomId, Long spuId, Integer explainStatus) {
        return liveRoomProdMapper.updateExplainStatus(roomId, spuId, explainStatus);
    }

    @Override
    public LiveMsgItemVO handleLiveProd(LiveMsgItemVO liveMsgItem) {
        ProductSearchDTO productSearchDTO = new ProductSearchDTO();
        productSearchDTO.setPageNum(1);
        productSearchDTO.setPageSize(1);
        productSearchDTO.setSpuId(liveMsgItem.getSpuId());
        productSearchDTO.setSpuStatus(SpuStatus.PUT_SHELF.value());
        ServerResponseEntity<EsPageVO<ProductSearchVO>> spuResponse = searchSpuFeignClient.search(productSearchDTO);
        if (!spuResponse.isSuccess()) {
            throw new LuckException(spuResponse.getMsg());
        }
        EsPageVO<ProductSearchVO> spuData = spuResponse.getData();
        List<ProductSearchVO> productSearchList = spuData.getList();
        if (CollUtil.isEmpty(productSearchList) || CollUtil.isEmpty(productSearchList.get(0).getSpus())) {
            return null;
        }

        List<SpuSearchVO> spuList = productSearchList.get(0).getSpus();
        SpuSearchVO spuSearchVO = spuList.get(0);
        liveMsgItem.setSpuName(spuSearchVO.getSpuName());
        liveMsgItem.setPic(spuSearchVO.getMainImgUrl());
        liveMsgItem.setPrice(spuSearchVO.getPriceFee());
        liveMsgItem.setActivityPrice(spuSearchVO.getActivityPrice());
        return liveMsgItem;
    }

    @Override
    public LiveRoomProdVO getLivingRoomBySpuId(Long spuId) {
        return liveRoomProdMapper.getLivingRoomBySpuId(spuId);
    }
}
