package com.yizhi.application.course.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.application.course.utils.EncryptionUtils;
import com.yizhi.application.course.utils.HttpClientUtils;
import com.yizhi.application.course.vo.PolyVO;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @description: 保利威视相关的视频
 * @author: lly
 * @date: 2019-01-18 12:46
 **/
@Api(tags = "保利威视接口")
@RestController
@RequestMapping("/poly")
public class PolyVideoController {

    public static final Logger LOGGER = LoggerFactory.getLogger(PolyVideoController.class);
    @Value("${polyv.secretkey}")
    private String secretkey;

    @Value("${polyv.url}")
    private String url;

    @Value("${polyv.viewerId}")
    private String viewerId;

    @GetMapping(value = "/token")
    public Response<String> getPolyToken(@ApiParam(name = "vid",value = "保利威视vid") @RequestParam(value = "vid",required = true) String vid,
                                         @ApiParam(name = "viewerIp",value = "用户IP") @RequestParam(value="viewerIp",defaultValue = "10.10.12.97",required = false) String viewerIP){
        return getPolyResponse(vid);
    }

    /**
     * 任务1018 ，配合前端新增视频播放获取token公开化。该接口针对营销课程
     * @param vid
     * @return
     */
    @GetMapping(value = "/public/token")
    public Response<String> getPolyToken(@ApiParam(name = "vid",value = "保利威视vid",required = true) @RequestParam(value = "vid") String vid){
        return getPolyResponse(vid);
    }

    private Response<String> getPolyResponse( String vid) {
        //获取HTML5点播token
        //视频vid
        // polyv 提供的服务器间的通讯验证
        if (StringUtils.isEmpty(vid)){
            return Response.fail("vid is empty!");
        } else if (vid.length() < 10) {//vid长度小于10位，返回非法
            return Response.fail("vid is illegal!");
        }
        String polyvUserId = vid.substring(0, 10);
        // polyv 提供的接口调用签名访问的key
//        String secretkey = "oj0LfU5fwB";
        // 视频对应vid
        String videoId = vid;
        // 时间戳
        Long ts = System.currentTimeMillis();
        // 用户 ip
        String viewerIp = "10.10.12.97";
        // 自定义用户 id
//        String viewerId = viewerId;
        // 用户昵称
        String viewerName = "username";
        Random random = new Random();
        // 自定义参数
        String extraParams = String.valueOf(random.nextInt());
        LOGGER.info("====="+extraParams);

		/* 将参数 $userId、$secretkey、$videoId、$ts、$viewerIp、$viewerIp、$viewerId、$viewerName、$extraParams
		    按照ASCKII升序 key + value + key + value ... +value 拼接
		*/
        //编码处理
        try {
            viewerName =  URLEncoder.encode(viewerName, "utf8");
        } catch (UnsupportedEncodingException e) {
            LOGGER.warn("异常信息{}",e);
        }
        String concated =  "extraParams" + extraParams + "ts" + ts + "userId" + polyvUserId + "videoId"
                + videoId + "viewerId" + viewerId + "viewerIp" + viewerIp + "viewerName" + viewerName;

        // 再首尾加上 secretkey
        String plain = secretkey + concated + secretkey;
        // 取大写MD5
        String sign = EncryptionUtils.md5Hex(plain).toUpperCase();

        // 然后将下列参数用post请求  https://hls.videocc.net/service/v1/token 获取 token
        Map<String, String> params = new HashMap<String, String>();
        params.put("userId", polyvUserId);
        params.put("videoId", videoId);
        params.put("ts", ts+"");
        params.put("viewerIp", viewerIp);
        params.put("viewerName", viewerName);
        params.put("extraParams", extraParams);
        params.put("viewerId", viewerId);
        params.put("sign", sign);
        LOGGER.info("{}", url + "?" + params);

        return Response.ok(getPolyVO(params));
    }

    public PolyVO getPolyVO(Map<String, String> params){

        String result = null;
        String token = null;
        PolyVO polyVO = null;
        try {
            HttpClientUtils httpClientUtils = new HttpClientUtils();
            result = httpClientUtils.httpPost(url,params);

            JSONObject data = JSON.parseObject(result);

        // 获取返回结果的 token, 再传入 playsafe 中播放加密视频
            if ("200".equals(data.get("code").toString())){
                token = ((Map<?, ?>) data.get("data")).get("token").toString();
                String ts = params.get("ts");
                String sign = params.get("sign");
                polyVO = new PolyVO();
                polyVO.setToken(token);
                polyVO.setTs(ts);
                polyVO.setSign(sign);
                polyVO.setVid(((Map<?, ?>) data.get("data")).get("videoId").toString());
            }
        } catch (Exception e) {
            LOGGER.info("{}",e);
        }
        return polyVO;
    }
}
