package com.xhkjedu.slive.controller.agora;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.slive.service.agora.AgoralicenseService;
import com.xhkjedu.slive.utils.agora.TokenUtil;
import com.xhkjedu.slive.vo.agora.AgoraTLicenseVo;
import com.xhkjedu.slive.vo.agora.AgoraTokenVo;
import com.xhkjedu.slive.vo.agora.AgoralicenseVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author ywx
 * @className AgoraTokenController
 * @description
 * @date 2021/1/25 11:42
 **/
@RestController
@RequestMapping("/agora_token")
public class AgoraTokenController {
    @Resource
    private AgoralicenseService agoralicenseService;

    @PostMapping("/rtc_token")
    public ResultVo rtcToken(@RequestBody AgoraTokenVo token) {
        Integer uid = token.getUid();
        String channelName = token.getChannelName();
        N_Utils.validation(new Object[]{channelName,"频道名称",2});
        String rtcToken = TokenUtil.getRtcToken(uid, channelName);
        if (N_Utils.isEmptyInteger(token.getLicense())) {
            return new ResultVo(0,"生成rtcToken成功",rtcToken);
        } else {
            Integer userid = token.getUserid();
            String cloudcode = token.getCloudcode();
            N_Utils.validation(new Object[]{userid, "用户id", 1,cloudcode,"云平台码",2});
            ResultVo result = agoralicenseService.inLive2(userid,cloudcode);
            if (result.getCode() != 0) {
                return result;
            }
            AgoralicenseVo obj = JSON.parseObject(JSON.toJSONString(result.getObj()),AgoralicenseVo.class);
            AgoraTLicenseVo vo = new AgoraTLicenseVo();
            vo.setToken(rtcToken);
            vo.setCert(obj.getCert());
            vo.setCredential(obj.getCredential());
            return new ResultVo(0,"生成rtcToken成功",vo);
        }
    }
}
