package edge_service

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"iot_manager_service/config"
	"iot_manager_service/util/common"
	"iot_manager_service/util/logger"
	"net/http"
	"strconv"
	"strings"
)

// IpCastControlService ip音柱连续控制接口
type IpCastControlService struct{}

type IpCastControlReq struct {
	Action   string                 `json:"action"`
	PostData map[string]interface{} `json:"postData"`
}

type TermInfo struct {
	AreaID int    `json:"AreaID"`
	From   string `json:"From"`
	ID     int    `json:"ID"`
	IP     string `json:"IP"`
	Name   string `json:"Name"`
	Online int    `json:"Online"`
	State  int    `json:"State"`
	Tasks  int    `json:"Tasks"`
	Vol    int    `json:"Vol"`
}

// GetTermIds 取设备列表和状态
func (f IpCastControlService) GetTermIds() (terminfos map[string]TermInfo, err error) {
	var reqData IpCastControlReq
	reqData.Action = "GetTermIds"
	m := make(map[string]interface{})
	reqData.PostData = m
	mapStr, err := f.RequestApi(reqData)
	if err != nil {
		return terminfos, err
	}
	terms, ok := mapStr["Terms"]
	if ok {
		marshal, _ := json.Marshal(terms)
		var terminfosList []TermInfo
		err := json.Unmarshal(marshal, &terminfosList)
		terms := make(map[string]TermInfo)
		for _, info := range terminfosList {
			info.Vol = int(common.MapRange(float64(info.Vol), 1, 16, 1, 100))
			terms[info.Name] = info
		}
		terminfos = terms
		if err != nil {
			return nil, err
		}
		return terminfos, nil
	}
	return terminfos, err
}

// SetVol 设置音量
func (f IpCastControlService) SetVol(sn string, vol int) error {
	terminfos, err2 := f.GetTermIds()
	if err2 != nil {
		return err2
	}
	term, ok := terminfos[sn]
	if !ok {
		return errors.New("devices not found\tsn=" + sn)
	}
	var reqData IpCastControlReq
	reqData.Action = "TermVolSet"
	m := make(map[string]interface{})
	m["TermIds"] = []int{term.ID}
	m["Volume"] = int(common.MapRange(float64(vol), 1, 100, 1, 16))
	reqData.PostData = m
	_, err := f.RequestApi(reqData)
	if err != nil {
		return err
	}
	return nil
}

// RequestApi 公共请求
func (f IpCastControlService) RequestApi(reqData IpCastControlReq) (map[string]interface{}, error) {
	cfg := config.Instance()
	url := fmt.Sprintf("%v/%v", cfg.Foreign.IpCastEdgeUrl, reqData.Action)
	method := "POST"
	client := &http.Client{}
	marshal, _ := json.Marshal(reqData.PostData)
	//fmt.Printf("playJson = %v \n", string(marshal))
	req, err := http.NewRequest(method, url, strings.NewReader(string(marshal)))
	if err != nil {
		logger.Logger.Errorf("IpCastControlService NewRequest %v", err.Error())
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		logger.Logger.Errorf("IpCastControlService Do %v", err.Error())
		return nil, err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		logger.Logger.Errorf("IpCastControlService ReadAll %v", err.Error())
		return nil, err
	}

	var IpCastControlRes map[string]interface{}
	err = json.Unmarshal(body, &IpCastControlRes)
	if err != nil {
		logger.Logger.Errorf("IpCastControlService Unmarshal %v", err.Error())
		return nil, err
	}
	//fmt.Printf("IpCastControlRes = %v \n", IpCastControlRes)
	if IpCastControlRes["Ret"] == 1000 {
		fmt.Printf("RequestApi url = %v \n", url)
		fmt.Printf("reqData = %v \n", reqData)
		logger.Logger.Errorf("IpCastControlService  %v", IpCastControlRes)
		return nil, err
	}
	return IpCastControlRes, nil
}

type uploadMp3Data struct {
	Remark   string `json:"Remark"`
	Ret      int    `json:"Ret"`
	NSeconds int    `json:"nSeconds"`
}

// UploadMp3GetFileId 上传素材 到ip音柱服务端
func (f IpCastControlService) UploadMp3GetFileId(imgUrl string, fileName string) (string, error) {
	cfg := config.Instance()
	url := fmt.Sprintf("%v/UploadFile:%v", cfg.Foreign.IpCastEdgeUrl, fileName)
	method := "POST"

	response, err := http.Get(imgUrl)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	client := &http.Client{}
	req, err := http.NewRequest(method, url, response.Body)
	if err != nil {
		fmt.Println(err)
		logger.Logger.Errorf("IpCastControlService UploadMp3GetFileId 1 %v", err.Error())
		return "", err
	}
	req.Header.Add("Content-Type", "audio/mpeg")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		logger.Logger.Errorf("IpCastControlService UploadMp3GetFileId 2 %v", err.Error())
		return "", err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		logger.Logger.Errorf("IpCastControlService UploadMp3GetFileId 3 %v", err.Error())
		return "", err
	}
	var resData uploadMp3Data
	err = json.Unmarshal(body, &resData)
	if err != nil {
		return "", err
	}
	if resData.Ret > 0 {
		return strconv.Itoa(resData.Ret), nil
	}
	return "", errors.New("上传失败啦")
}

func (f IpCastControlService) SetStop() error {
	var reqData IpCastControlReq
	reqData.Action = "StopMp3ByID"
	m := make(map[string]interface{})
	m["ID"] = 0
	reqData.PostData = m
	_, err := f.RequestApi(reqData)
	return err
}

// 发布节目
func (f IpCastControlService) PushPlay(playJson string, ptype int) error {
	var reqData IpCastControlReq
	if ptype == 1 {
		reqData.Action = "PlayMp3ByID"
	} else {
		reqData.Action = "PlayText"
	}
	m := make(map[string]interface{})
	fmt.Printf("playJson = %v \n", playJson)
	err := json.Unmarshal([]byte(playJson), &m)
	reqData.PostData = m
	if err != nil {
		return err
	}
	_, err = f.RequestApi(reqData)
	return err
}
