package com.xhkjedu.slive.service.agora;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.slive.config.ConfigKey;
import com.xhkjedu.slive.mapper.agora.AgoralicenseMapper;
import com.xhkjedu.slive.mapper.system.UserMapper;
import com.xhkjedu.slive.model.agora.TAgoralicense;
import com.xhkjedu.slive.vo.agora.ALInUserVo;
import com.xhkjedu.slive.vo.agora.AgoralicenseVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author ywx
 * @classname AgoralicenseService
 * @description 
 * @date 2021/3/29 17:18
 **/
@Service
@Slf4j
public class AgoralicenseService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private AgoralicenseMapper agoralicenseMapper;

    //进入直播绑定license
    public ResultVo inLive(Integer userid, String cloudcode) {
        final ExecutorService exec = Executors.newFixedThreadPool(1);
        final ResultVo[] result = {null};
        try {
            Callable<String> call = new Callable() {
                @Override
                public String call() throws IOException {
                    Map user = userMapper.getObjById(userid);
                    ALInUserVo inUser = new ALInUserVo();
                    inUser.setCloudcode(cloudcode);
                    inUser.setUserid(userid);
                    inUser.setUsername(user.get("username").toString());
                    inUser.setLoginname(user.get("loginname").toString());
                    String param = JSON.toJSONString(inUser);
                    String str = N_Utils.sendJsonPost(ConfigKey.cloudapi + "license/in_live", param);
                    if (N_Utils.isEmpty(str)) {
                        ResultVo vo = new ResultVo();
                        vo.setCode(1);
                        vo.setMsg("执行超时");
                        result[0] = vo;
                    } else {
                        result[0] = JSON.parseObject(str, ResultVo.class);
                    }
                    return "执行成功";
                }
            };
            Future<String> future = exec.submit(call);
            future.get(20, TimeUnit.SECONDS); //任务处理超过20s关闭
        } catch (Exception e) {
            log.error("进入直播绑定license失败",e.getMessage());
            result[0] = new ResultVo(1,"进入直播失败");
        }
        // 关闭线程池
        exec.shutdown();
        return result[0];
    }

    //进入直播绑定license
    public ResultVo inLive2(Integer userid, String cloudcode) {
        final ExecutorService exec = Executors.newFixedThreadPool(1);
        final ResultVo[] result = {null};
        try {
            Callable<String> call = new Callable() {
                @Override
                public String call() throws IOException {
                    Map user = userMapper.getObjById(userid);
                    AgoralicenseVo vo = agoralicenseMapper.inLive(userid);
                    if (vo == null) {
                        vo = agoralicenseMapper.getActivatedLicense();//获取已激活license
                        if (vo == null) {
                            result[0] = new ResultVo(1, "暂无可用授权");
                            return "执行成功";
                        }
                    }
                    if (vo.getUsed() == 0) {
                        TAgoralicense license = new TAgoralicense();
                        license.setAgid(vo.getAgid());
                        license.setCloudcode(cloudcode);
                        license.setSchoolid((Integer) user.get("schoolid"));
                        license.setUserid(userid);
                        license.setUsername(user.get("username").toString());
                        license.setLoginname(user.get("loginname").toString());
                        license.setUsed(1);
                        agoralicenseMapper.updateByPrimaryKeySelective(license);
                    }
                    result[0] = new ResultVo(0,"进入直播成功",vo);
                    return "执行成功";
                }
            };
            Future<String> future = exec.submit(call);
            future.get(20, TimeUnit.SECONDS); //任务处理超过20s关闭
        } catch (Exception e) {
            log.error("进入直播绑定license失败",e.getMessage());
            result[0] = new ResultVo(1,"进入直播失败");
        }
        // 关闭线程池
        exec.shutdown();
        return result[0];
    }

    //学生退出直播解绑license
    public ResultVo outLive(Integer userid, String cloudcode) {
        agoralicenseMapper.outLive(userid);
        return new ResultVo(0,"学生退出直播成功");
    }

    //获取列表
    public List<AgoralicenseVo> listAll(TAgoralicense license) {
        return agoralicenseMapper.listAll(license);
    }

    //定时任务修改license状态
    public void updateLicenseState() {
        Integer nowtime = N_Utils.getSecondTimestamp();
        agoralicenseMapper.updateActivate(nowtime);//更新失效的license的激活状态
    }

    //处理未释放的授权
    public void updateLicense() {
        agoralicenseMapper.updateLicense();
    }
}
