package com.wsm.admin.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wsm.common.util.AjaxJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Hb_zzZ on 2019/3/29.
 */
@RestController
public class LiveController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${live.key}")
    private String liveKey;

    @Value("${live.number.url}")
    private String numberUrl;

    @Value("${live.info.url}")
    private String infoUrl;

    @Value("${yingshi.live.key}")
    private String key;

    @Value("${yingshi.live.secret}")
    private String secret;

    @Value("${yingshi.token.url}")
    private String tokenUrl;

    @Value("${yingshi.info.url}")
    private String infoList;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = {"/live/getLiveUrlList"})
    public AjaxJson getLiveUrlList() {

        List<String> urlList = new ArrayList<>();

        JSONObject postData = new JSONObject();
        postData.put("key", liveKey);
        JSONObject json = restTemplate.postForObject(numberUrl, postData, JSONObject.class);
        logger.info("接口数据：" + json.toString());

        if(json.containsKey("sessions")){
            JSONArray numberArray = json.getJSONArray("sessions");
            for(int i = 0; i < numberArray.size(); i++){
                JSONObject job = numberArray.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                if(job.containsKey("serial_number")){
                    postData.put("serial_number", job.get("serial_number"));
                    JSONObject jsonObj = restTemplate.postForObject(infoUrl, postData, JSONObject.class);
                    logger.info("直播url数据：" + jsonObj.get("hlsUrl").toString());
                    urlList.add(jsonObj.get("hlsUrl").toString());
                }
            }
        }

        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        //  也支持中文
        params.add("appKey", key);
        params.add("appSecret", secret);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = restTemplate.postForEntity(tokenUrl, params, String.class);

        JSONObject yingShiToken = JSONObject.parseObject(response.getBody());
        if("200".equals(yingShiToken.get("code").toString())){
            String token = yingShiToken.getJSONObject("data").get("accessToken").toString();

            params= new LinkedMultiValueMap<String, String>();
            params.add("accessToken", token);
            response = restTemplate.postForEntity(infoList, params, String.class);
            JSONObject yingShiList = JSONObject.parseObject(response.getBody());
            if("200".equals(yingShiList.get("code").toString())){
                JSONArray list = yingShiList.getJSONArray("data");
                for(int i = 0; i < list.size(); i++){
                    JSONObject job = list.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    urlList.add(job.get("hdAddress").toString());
                }
            }
        }
        return AjaxJson.success(urlList);
    }
}
