package com.wecloud.im.service.impl;

import com.alibaba.fastjson.JSON;
import com.wecloud.im.entity.ImClient;
import com.wecloud.im.entity.ImRtcRecord;
import com.wecloud.im.mapper.ImRtcRecordMapper;
import com.wecloud.im.param.rtc.CreateRtcChannelParam;
import com.wecloud.im.sdk.enums.RtcStateEnum;
import com.wecloud.im.service.ImClientService;
import com.wecloud.im.service.ImRtcRecordService;
import com.wecloud.utils.SnowflakeUtil;
import io.geekidea.springbootplus.framework.common.service.impl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * @Author Future
 * @Date 2022/5/22 23:50
 * @Description 单人音视频记录服务实现
 */
@Slf4j
@Service
public class ImRtcRecordServiceImpl extends BaseServiceImpl<ImRtcRecordMapper, ImRtcRecord> implements ImRtcRecordService {

    @Autowired
    private ImClientService imClientService;


    @Override
    public void createRtcRecord(CreateRtcChannelParam param, Long channelId) {
        try {
            ImClient currentClient = imClientService.getCurrentClient();
            ImRtcRecord rtcRecord = new ImRtcRecord();
            rtcRecord.setId(SnowflakeUtil.getId());
            rtcRecord.setFkAppid(currentClient.getFkAppid());
            rtcRecord.setChannelId(channelId);
            rtcRecord.setFromClientId(currentClient.getClientId());
            rtcRecord.setToClientId(param.getToClient());
            rtcRecord.setCallType(param.getCallType());
            rtcRecord.setState(RtcStateEnum.CREATED.getCode());
            rtcRecord.setCreateTime(new Date());
            this.save(rtcRecord);
        } catch (Exception e) {
            log.info("创建rtc通话记录异常 param {} channelId {} 异常 ", JSON.toJSONString(param), channelId, e);
        }
    }

    /**
     * 更新音视频记录
     *
     * @param channelId
     * @param type      1-同意进入频道  2-拒接进入频道  3-主动挂断(离开频道)
     */
    @Override
    public void updateRtcRecord(Long channelId, Integer type) {
        try {
            ImRtcRecord rtcRecord = this.getById(channelId);
            if (rtcRecord == null) {
                return;
            }
            if (type == 1) {
                // 同意进入频道
                rtcRecord.setState(RtcStateEnum.ING.getCode());
                rtcRecord.setStartTime(new Date());
            } else if (type == 2) {
                // 拒接进入频道
                rtcRecord.setState(RtcStateEnum.END.getCode());
            } else {
                // 主动挂断(离开频道)
                rtcRecord.setState(RtcStateEnum.END.getCode());
                rtcRecord.setEndTime(new Date());
            }
            this.updateById(rtcRecord);
        } catch (Exception e) {
            log.info("更新rtc通话记录异常, channelId {}, type {} 异常 ", channelId, type, e);
        }
    }


}
