package com.tmerclub.cloud.live.feign;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.live.feign.LiveFeignClient;
import com.tmerclub.cloud.common.cache.constant.CacheNames;
import com.tmerclub.cloud.common.cache.constant.LiveCacheNames;
import com.tmerclub.cloud.common.cache.util.RedisUtil;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.live.constant.LiveRoomStatusType;
import com.tmerclub.cloud.live.mapper.LiveRoomProdMapper;
import com.tmerclub.cloud.live.service.LiveRoomService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TRACK
 */
@DubboService
public class LiveFeignController implements LiveFeignClient {

    @Autowired
    private LiveRoomService liveRoomService;
    @Autowired
    private LiveRoomProdMapper liveRoomProdMapper;

    @Override
    public ServerResponseEntity<Void> deleteLiveRoomProd(Long spuId) {
        List<Long> roomIds = liveRoomProdMapper.listRoomIdBySpuId(spuId);
        if (CollUtil.isEmpty(roomIds)) {
            return ServerResponseEntity.success();
        }
        liveRoomProdMapper.deleteBySpuId(spuId, roomIds);
        // 清除缓存
        List<String> keys = new ArrayList<>();
        for (Long roomId : roomIds) {
            keys.add(LiveCacheNames.LIVE_ROOM_PROD + CacheNames.UNION + roomId);
        }
        RedisUtil.del(keys);
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<Void> endLiveRoom(List<Long> shopIds) {
        List<Long> roomIds = liveRoomService.listRoomIdsByShopId(shopIds);
        if (CollUtil.isEmpty(roomIds)) {
            return ServerResponseEntity.success();
        }
        liveRoomService.updateLiveRoomStatus(LiveRoomStatusType.FINISHED.value(), roomIds);
        return ServerResponseEntity.success();
    }
}
