package com.fs.live.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.live.domain.LiveVideo;
import com.fs.live.mapper.LiveVideoMapper;
import com.fs.live.param.LiveFinishUParam;
import com.fs.live.param.LiveTrafficLogParam;
import com.fs.live.utils.redis.RedisBatchHandler;
import com.fs.live.vo.LiveTrafficLogListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.live.mapper.LiveTrafficLogMapper;
import com.fs.live.domain.LiveTrafficLog;
import com.fs.live.service.ILiveTrafficLogService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 直播流量记录Service业务层处理
 *
 * @author fs
 * @date 2025-10-13
 */
@Service
@Slf4j
public class LiveTrafficLogServiceImpl implements ILiveTrafficLogService
{
    @Autowired
    private LiveTrafficLogMapper liveTrafficLogMapper;
    @Autowired
    private LiveVideoMapper liveVideoMapper;
    @Autowired
    private RedisBatchHandler redisBatchHandler;

    /**
     * 查询直播流量记录
     *
     * @param logId 直播流量记录ID
     * @return 直播流量记录
     */
    @Override
    public LiveTrafficLog selectLiveTrafficLogById(Long logId)
    {
        return liveTrafficLogMapper.selectLiveTrafficLogById(logId);
    }

    /**
     * 查询直播流量记录列表
     *
     * @param liveTrafficLog 直播流量记录
     * @return 直播流量记录
     */
    @Override
    public List<LiveTrafficLog> selectLiveTrafficLogList(LiveTrafficLog liveTrafficLog)
    {
        return liveTrafficLogMapper.selectLiveTrafficLogList(liveTrafficLog);
    }

    /**
     * 新增直播流量记录
     *
     * @param liveTrafficLog 直播流量记录
     * @return 结果
     */
    @Override
    public int insertLiveTrafficLog(LiveTrafficLog liveTrafficLog)
    {
        liveTrafficLog.setCreateTime(DateUtils.getNowDate());
        return liveTrafficLogMapper.insertLiveTrafficLog(liveTrafficLog);
    }

    /**
     * 修改直播流量记录
     *
     * @param liveTrafficLog 直播流量记录
     * @return 结果
     */
    @Override
    public int updateLiveTrafficLog(LiveTrafficLog liveTrafficLog)
    {
        return liveTrafficLogMapper.updateLiveTrafficLog(liveTrafficLog);
    }

    /**
     * 批量删除直播流量记录
     *
     * @param logIds 需要删除的直播流量记录ID
     * @return 结果
     */
    @Override
    public int deleteLiveTrafficLogByIds(Long[] logIds)
    {
        return liveTrafficLogMapper.deleteLiveTrafficLogByIds(logIds);
    }

    /**
     * 删除直播流量记录信息
     *
     * @param logId 直播流量记录ID
     * @return 结果
     */
    @Override
    public int deleteLiveTrafficLogById(Long logId)
    {
        return liveTrafficLogMapper.deleteLiveTrafficLogById(logId);
    }

    @Override
    public List<LiveTrafficLogListVO> selectTrafficByCompany(LiveTrafficLogParam param) {
        return liveTrafficLogMapper.selectTrafficByCompany(param);
    }

    @Override
    @Transactional
    public R getInternetTraffic(LiveFinishUParam param) {
        try {
            LiveTrafficLog trafficLog = new LiveTrafficLog();
            trafficLog.setQwExternalContactId(param.getQwExternalId());
            trafficLog.setCreateTime(new Date());
            BeanUtils.copyProperties(param, trafficLog);

            List<LiveVideo> liveVideos = liveVideoMapper.selectByLiveIdAndType(param.getLiveId(),param.getVideoType());

            if(liveVideos == null || liveVideos.isEmpty()) return R.error("视频不存在");
            LiveVideo video = liveVideos.get(0);

            // 计算流量
            BigDecimal result = param.getBufferRate().divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP);
            BigDecimal longAsBigDecimal = BigDecimal.valueOf(video.getFileSize());
            long roundedResult = result.multiply(longAsBigDecimal).setScale(0, RoundingMode.HALF_UP).longValue();
            trafficLog.setInternetTraffic(roundedResult);

            // 处理 UUID 为空的情况
            if (StringUtils.isNotEmpty(trafficLog.getUuId())) {
                // 直接插入或更新
//                logger.error("zyp \n【插入或更新流量】：{}",trafficLog);
                redisBatchHandler.addDataToRedis(trafficLog);
//                liveTrafficLogMapper.insertOrUpdateLiveTrafficLog(trafficLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 打印参数param和异常信息
            log.error("zyp \n【插入或更新流量失败】参数: {}, 错误信息：{}", param, e.getMessage(), e);
            return R.error();
        }
        return R.ok();
    }

    @Override
    public R getLiveInternetTraffic(LiveFinishUParam param) {
        try {
            LiveTrafficLog trafficLog = new LiveTrafficLog();
            trafficLog.setQwExternalContactId(param.getQwExternalId());
            trafficLog.setCreateTime(new Date());
            BeanUtils.copyProperties(param, trafficLog);

            trafficLog.setInternetTraffic(param.getInternetTraffic());

            // 处理 UUID 为空的情况
            if (StringUtils.isNotEmpty(trafficLog.getUuId())) {
                // 直接插入或更新
//                logger.error("zyp \n【插入或更新流量】：{}",trafficLog);
                redisBatchHandler.addDataToRedis(trafficLog);
//                liveTrafficLogMapper.insertOrUpdateLiveTrafficLog(trafficLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 打印参数param和异常信息
            log.error("zyp \n【插入或更新流量失败】参数: {}, 错误信息：{}", param, e.getMessage(), e);
            return R.error();
        }
        return R.ok();
    }
}
