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.stereotype.Controller;
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.List;

/**
 * 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;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = {"/live/getLiveUrlList"})
    public AjaxJson getLiveUrlList() {
        JSONObject postData = new JSONObject();
        postData.put("key", liveKey);
        JSONObject json = restTemplate.postForObject(numberUrl, postData, JSONObject.class);
        logger.info("接口数据：" + json.toString());

        List<String> urlList = new ArrayList<>();
        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());
                }
            }
        }
        return AjaxJson.success(urlList);
    }
}
