package data

import (
	"encoding/json"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/services/alarm_msg"
	"eta/eta_mobile/utils"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

// 嘉悦桥接服务接口
var (
	BridgeApiJiaYueIndexUrl         = "/api/index_data/jiayue/index"          // 获取指标信息
	BridgeApiJiaYueIndexDataUrl     = "/api/index_data/jiayue/index_data"     // 获取指标数据
	BridgeApiJiaYuePageIndexUrl     = "/api/index_data/jiayue/page_index"     // 获取指标列表-分页
	BridgeApiJiaYueFrequencyListUrl = "/api/index_data/jiayue/frequency_list" // 获取指标频度列表
)

type EdbBridgeJiaYue struct{}

// GetIndex 获取指标信息
func (brg *EdbBridgeJiaYue) GetIndex(req GetIndexFromBridgeReq) (item BridgeIndexItem, err error) {
	var params data_manage.BridgeJiaYueIndexParams
	params.IndexCode = req.IndexCode
	params.SourceExtend = req.SourceExtend
	params.IndexCodeRequired = req.IndexCodeRequired
	indexData, e := GetJiaYueIndexFromBridge(params)
	if e != nil {
		err = fmt.Errorf("GetJiaYueIndexDataFromBridge err: %s", e.Error())
		return
	}
	if indexData.Id <= 0 {
		return
	}
	item.Id = indexData.Id
	item.IndexCode = indexData.IndexCode
	item.IndexName = indexData.IndexName
	item.Unit = indexData.Unit
	item.Frequency = brg.TransFrequency(indexData.Frequency)
	return
}

// GetIndexAndData 获取指标和数据
//func (brg *EdbBridgeJiaYue) GetIndexAndData(req GetIndexAndDataFromBridgeReq) (item BridgeIndexItem, err error) {
//	var params data_manage.BridgeJiaYueIndexDataParams
//	params.IndexCode = req.IndexCode
//	params.SourceExtend = req.SourceExtend
//	params.StartDate = req.StartDate
//	params.EndDate = req.EndDate
//	indexData, e := GetJiaYueIndexDataFromBridge(params)
//	if e != nil {
//		err = fmt.Errorf("GetJiaYueIndexDataFromBridge err: %s", e.Error())
//		return
//	}
//	if indexData.Id <= 0 {
//		return
//	}
//	item.Id = indexData.Id
//	item.IndexCode = indexData.IndexCode
//	item.IndexName = indexData.IndexName
//	item.Unit = indexData.Unit
//	item.Frequency = brg.TransFrequency(indexData.Frequency)
//	var dataList []BridgeIndexDataItem
//	for _, v := range indexData.IndexData {
//		dataList = append(dataList, BridgeIndexDataItem{
//			Val:        v.Val,
//			DataTime:   v.DataTime,
//			UpdateTime: v.UpdateTime,
//		})
//	}
//	item.Data = dataList
//	return
//}

// TransFrequency 嘉悦指标频度转换
func (brg *EdbBridgeJiaYue) TransFrequency(origin string) string {
	mapping := map[string]string{
		"日":  "日度",
		"周":  "周度",
		"旬":  "旬度",
		"半月": "旬度",
		"月":  "月度",
		"季":  "季度",
		"半年": "半年度",
		"年":  "年度",
	}
	return mapping[origin]
}

// GetJiaYueIndexFromBridge 从桥接服务获取指标信息
func GetJiaYueIndexFromBridge(param data_manage.BridgeJiaYueIndexParams) (indexData data_manage.BridgeJiaYueIndexAndData, err error) {
	defer func() {
		if err != nil {
			b, _ := json.Marshal(param)
			tips := fmt.Sprintf("桥接服务-获取嘉悦指标信息, err: %s, params: %s", err.Error(), string(b))
			go alarm_msg.SendAlarmMsg(tips, 3)
		}
	}()

	url := fmt.Sprint(utils.EtaBridgeUrl, BridgeApiJiaYueIndexUrl)
	data, e := json.Marshal(param)
	if e != nil {
		err = fmt.Errorf("data json marshal err: %s", e.Error())
		return
	}
	body := ioutil.NopCloser(strings.NewReader(string(data)))
	client := &http.Client{}
	req, e := http.NewRequest("POST", url, body)
	if e != nil {
		err = fmt.Errorf("http create request err: %s", e.Error())
		return
	}

	checkToken := utils.MD5(utils.EtaBridgeAppNameEn + utils.EtaBridgeMd5Key)
	contentType := "application/json;charset=utf-8"
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("Authorization", checkToken)
	resp, e := client.Do(req)
	if e != nil {
		err = fmt.Errorf("http client do err: %s", e.Error())
		return
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	b, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		err = fmt.Errorf("resp body read err: %s", e.Error())
		return
	}
	if len(b) == 0 {
		err = fmt.Errorf("resp body is empty")
		return
	}
	// 生产环境解密
	if utils.RunMode == "release" {
		str := string(b)
		str = strings.Trim(str, `"`)
		b = utils.DesBase64Decrypt([]byte(str), utils.EtaBridgeDesKey)
	}

	result := new(data_manage.BridgeJiaYueResultIndexData)
	if e = json.Unmarshal(b, &result); e != nil {
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	if result.Code != 200 {
		err = fmt.Errorf("result: %s", string(b))
		return
	}
	indexData = result.Data
	return
}

// GetJiaYueIndexDataFromBridge 从桥接服务获取指标数据
//func GetJiaYueIndexDataFromBridge(param data_manage.BridgeJiaYueIndexDataParams) (indexData data_manage.BridgeJiaYueIndexAndData, err error) {
//	defer func() {
//		if err != nil {
//			b, _ := json.Marshal(param)
//			tips := fmt.Sprintf("桥接服务-获取嘉悦指标数据, err: %s, params: %s", err.Error(), string(b))
//			go alarm_msg.SendAlarmMsg(tips, 3)
//		}
//	}()
//
//	url := fmt.Sprint(utils.EtaBridgeUrl, BridgeApiJiaYueIndexDataUrl)
//	data, e := json.Marshal(param)
//	if e != nil {
//		err = fmt.Errorf("data json marshal err: %s", e.Error())
//		return
//	}
//	body := ioutil.NopCloser(strings.NewReader(string(data)))
//	client := &http.Client{}
//	req, e := http.NewRequest("POST", url, body)
//	if e != nil {
//		err = fmt.Errorf("http create request err: %s", e.Error())
//		return
//	}
//
//	checkToken := utils.MD5(utils.EtaBridgeAppNameEn + utils.EtaBridgeMd5Key)
//	contentType := "application/json;charset=utf-8"
//	req.Header.Set("Content-Type", contentType)
//	req.Header.Set("Authorization", checkToken)
//	resp, e := client.Do(req)
//	if e != nil {
//		err = fmt.Errorf("http client do err: %s", e.Error())
//		return
//	}
//	defer func() {
//		_ = resp.Body.Close()
//	}()
//	b, e := ioutil.ReadAll(resp.Body)
//	if e != nil {
//		err = fmt.Errorf("resp body read err: %s", e.Error())
//		return
//	}
//	if len(b) == 0 {
//		err = fmt.Errorf("resp body is empty")
//		return
//	}
//	// 生产环境解密
//	if utils.RunMode == "release" {
//		str := string(b)
//		str = strings.Trim(str, `"`)
//		b = utils.DesBase64Decrypt([]byte(str), utils.EtaBridgeDesKey)
//	}
//
//	result := new(data_manage.BridgeJiaYueResultIndexData)
//	if e = json.Unmarshal(b, &result); e != nil {
//		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
//		return
//	}
//	if result.Code != 200 {
//		err = fmt.Errorf("result: %s", string(b))
//		return
//	}
//	indexData = result.Data
//	return
//}

// GetJiaYueFrequencyListFromBridge 获取指标频度列表
func GetJiaYueFrequencyListFromBridge() (frequencies []string, err error) {
	url := fmt.Sprint(utils.EtaBridgeUrl, BridgeApiJiaYueFrequencyListUrl)
	body := ioutil.NopCloser(strings.NewReader(""))
	client := &http.Client{}
	req, e := http.NewRequest("POST", url, body)
	if e != nil {
		err = fmt.Errorf("http create request err: %s", e.Error())
		return
	}

	checkToken := utils.MD5(utils.EtaBridgeAppNameEn + utils.EtaBridgeMd5Key)
	contentType := "application/json;charset=utf-8"
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("Authorization", checkToken)
	resp, e := client.Do(req)
	if e != nil {
		err = fmt.Errorf("http client do err: %s", e.Error())
		return
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	b, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		err = fmt.Errorf("resp body read err: %s", e.Error())
		return
	}
	if len(b) == 0 {
		err = fmt.Errorf("resp body is empty")
		return
	}
	// 生产环境解密
	if utils.RunMode == "release" {
		str := string(b)
		str = strings.Trim(str, `"`)
		b = utils.DesBase64Decrypt([]byte(str), utils.EtaBridgeDesKey)
	}

	result := new(data_manage.BridgeJiaYueResultFrequencyList)
	if e = json.Unmarshal(b, &result); e != nil {
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	if result.Code != 200 {
		err = fmt.Errorf("result: %s", string(b))
		return
	}
	frequencies = result.Data
	return
}

// GetJiaYueIndexPageListFromBridge 获取指标分页列表
func GetJiaYueIndexPageListFromBridge(param data_manage.BridgeJiaYuePageIndexReq) (total int, items []data_manage.DictIndex, err error) {
	url := fmt.Sprint(utils.EtaBridgeUrl, BridgeApiJiaYuePageIndexUrl)
	data, e := json.Marshal(param)
	if e != nil {
		err = fmt.Errorf("data json marshal err: %s", e.Error())
		return
	}
	body := ioutil.NopCloser(strings.NewReader(string(data)))
	client := &http.Client{}
	req, e := http.NewRequest("POST", url, body)
	if e != nil {
		err = fmt.Errorf("http create request err: %s", e.Error())
		return
	}

	checkToken := utils.MD5(utils.EtaBridgeAppNameEn + utils.EtaBridgeMd5Key)
	contentType := "application/json;charset=utf-8"
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("Authorization", checkToken)
	resp, e := client.Do(req)
	if e != nil {
		err = fmt.Errorf("http client do err: %s", e.Error())
		return
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	b, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		err = fmt.Errorf("resp body read err: %s", e.Error())
		return
	}
	if len(b) == 0 {
		err = fmt.Errorf("resp body is empty")
		return
	}
	// 生产环境解密
	if utils.RunMode == "release" {
		str := string(b)
		str = strings.Trim(str, `"`)
		b = utils.DesBase64Decrypt([]byte(str), utils.EtaBridgeDesKey)
	}

	result := new(data_manage.BridgeJiaYueResultIndexPageList)
	if e = json.Unmarshal(b, &result); e != nil {
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	if result.Code != 200 {
		err = fmt.Errorf("result: %s", string(b))
		return
	}
	total = result.Data.Total
	items = result.Data.List
	return
}
