package com.platform.modules.trtc.controller;

import com.platform.common.annotation.SysLog;
import com.platform.common.utils.R;
import com.platform.common.validator.ValidatorUtils;
import com.platform.modules.app.controller.AppAbstractController;
import com.platform.modules.app.form.LoginForm;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysUserService;
import com.platform.modules.trtc.service.TrtcService;
import com.tls.tls_sigature.tls_sigature;
import com.tls.tls_sigature.tls_sigature.GenTLSSignatureResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/trtc")
@Api(value = "视频连线", tags = "视频连线")
public class TrtcController extends AppAbstractController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TrtcService trtcService;

    @Value("${materia.basePath}")
    private String DOMAIN;
    @Value("${zkdx.trtc.appid}")
    private Integer skdAppid;
    @Value("${zkdx.trtc.privateKey}")
    private String privateKey;

    @SysLog("用户登录")
    @PostMapping("/login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form) {

        // 表单校验
        ValidatorUtils.validateEntity(form);

        // 用户登录
        // long userId = userService.login(form);
        SysUserEntity user = null;

        String regex = "^1\\d{10}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(form.getMobile());
        if (form.getMobile().length() == 11 && m.matches()) {
            user = sysUserService.queryByMobile(form.getMobile());
        } else {
            user = sysUserService.queryByUserName(form.getMobile());
        }

        if (user == null || user.getUserId() == null) {
            return R.error(70001, "账号不存在");
        }

        // 账号不存在、密码错误
        if (!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error(70001, "账号或密码不正确");
        }

        String identifier = user.getUsername() + "_" + user.getUserId();
        GenTLSSignatureResult result = tls_sigature.genSig(skdAppid, identifier, privateKey);

        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getUserId());
        map.put("username", user.getUsername());
        map.put("userImg", DOMAIN + user.getUserImg());
        map.put("realname", user.getRealname());
        map.put("mobile", user.getMobile());
        map.put("email", user.getEmail());
        map.put("userSig", result.urlSig);
        map.put("identifier", identifier);
        map.put("state", trtcService.getReporterOnLineRedisById(user.getUserId()));
        // 20200528_wy 记者推流状态
        map.put("isPush", null != trtcService.getReporterPushState(user.getUserId()) ? trtcService.getReporterPushState(user.getUserId()) : 0);

        //System.out.println(user.getUserId()+"---------------------登录成功-------------"+DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        return R.ok().put("userInfo", map);
    }

    @SysLog("用户退出登录")
    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public R logout() {
        trtcService.deleteReporterStatusRedisById(getUserId());
        //System.out.println(getUserId()+"---------------------退出登录-------------"+DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        return R.ok();
    }

    @GetMapping("/reporter/list")
    @ApiOperation("记者列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "记者Id", paramType = "query", dataType = "Long")})
    public R getReporterList(Long userId) {
        return R.ok().put("reporterList", trtcService.getReporterList(userId));
    }

    @GetMapping("/reporter/info")
    @ApiOperation("记者详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "记者Id", paramType = "query", dataType = "Long")})
    public R getReporterInfo(Long userId) {
        return R.ok().put("reporterInfo", trtcService.getReporterInfo(userId));
    }

    @GetMapping("/reporter/update/status")
    @ApiOperation("记者状态变更")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "记者Id", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "status", value = "状态 0离线 1在线 2通话中", allowableValues = "0,1,2,3", paramType = "query", dataType = "int")
    })
    public R updateReporterStatus(Long userId, Integer status) {
        //System.out.println(userId+"---------记者状态变更----------"+status+"------------"+DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        return R.ok().put("reporterList", trtcService.getReporterStatusList(userId, status));
    }

    @GetMapping("/app/getUserSig")
    @ApiOperation("(APP)根据记者ID获取userSig")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "记者Id", paramType = "query", dataType = "Long")
    })
    public R getUserSig(Long userId) {
        if (userId == null) {
            return R.error(70001, "userId不能为空");
        }
        SysUserEntity user = sysUserService.selectBaseById(userId);
        if ((user == null) || (user.getUserId() == null)) {
            return R.error(70001, "账号不存在");
        }
        Map<String, Object> map = new HashMap();
        map.put("userId", user.getUserId());
        String identifier = user.getUsername() + "_" + user.getUserId();
        tls_sigature.GenTLSSignatureResult result = tls_sigature.genSig(this.skdAppid.intValue(), identifier, this.privateKey);
        map.put("userSig", result.urlSig);
        map.put("identifier", identifier);
        map.put("state", trtcService.getReporterOnLineRedisById(user.getUserId()));
        return R.ok().put("sigInfo", map);
    }

    @GetMapping("/pad/control/call")
    @ApiOperation("pad发起或者终止通话")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "记者Id", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "status", value = "状态 20001发起 20002终止", allowableValues = "20001,20002", paramType = "query", dataType = "int")
    })
    public R padControlCall(Long userId, Integer status) {

        if (userId == null) {
            return R.error(70001, "userId不能为空");
        }
        SysUserEntity user = sysUserService.selectBaseById(userId);
        if ((user == null) || (user.getUserId() == null)) {
            return R.error(70001, "该记者不存在，无法进行视频连线");
        }
//        if(trtcService.getReporterPushState(userId)!=0){
//            return R.error(70001, "该记者正在推流，不能进行视频连线");
//        }
//        if(trtcService.getReporterOnLineRedisById(userId)!=1){
//            return R.error(70001, "该记者不在线或正式连线中，不能进行视频连线");
//        }
        try{
            trtcService.padControlCall(userId, status);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }
}
