package services

import (
	"encoding/json"
	"fmt"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/response/chart_info"
	"hongze/hongze_yb/utils"
	"io/ioutil"
	"net/http"
	"strings"
)

// ChartCommonDetailReq 请求图表详情接口
type ChartCommonDetailReq struct {
	UniqueCode string `description:"图表唯一编码"`
}

type ChartCommonDetailResp struct {
	Ret         int
	Msg         string
	ErrMsg      string
	ErrCode     string
	Success     bool `description:"true 执行成功，false 执行失败"`
	IsSendEmail bool `description:"true 发送邮件，false 不发送邮件"`
	Data        *chart_info.ChartLibChartInfoDetailResp
}

// GetBalanceChartDetail 获取平衡表详情接口
func GetBalanceChartDetail(uniqueCode string) (respData *chart_info.ChartLibChartInfoDetailResp, err error) {
	// https://charttest.hzinsights.com/v1/chart/common/detail?UniqueCode=3a2823954a505710b37689df3b063d68
	postUrl := fmt.Sprintf("%s/chart_auth/detail?UniqueCode=%s", global.CONFIG.EtaChartLib.ServerUrl, uniqueCode)
	/*	param := &ChartCommonDetailReq{
			UniqueCode: uniqueCode,
		}
		postData, err := json.Marshal(param)
		if err != nil {
			return
		}*/
	result, err := httpGet(postUrl)
	if err != nil {
		return
	}
	//result := []byte(`{"Ret":200,"Msg":"获取成功","ErrMsg":"","ErrCode":"","Data":{"ChartInfo":{"ChartName":"平衡表图表1 1 1en","ChartNameEn":"平衡表图表1 1 1en","UniqueCode":"3a2823954a505710b37689df3b063d68","DateType":3,"StartDate":"","EndDate":"","IsSetName":0,"EdbInfoIds":"81,82","ChartType":1,"Calendar":"公历","SeasonStartDate":"","SeasonEndDate":"","ChartImage":"https://hzstatic.hzinsights.com/static/images/202405/20240529/DQE2jdBQImw01c3sn6wIoDXBde2W.png","XMin":"","XMax":"","LeftMin":"13","LeftMax":"65.12","RightMin":"Infinity","RightMax":"-Infinity","Right2Min":"Infinity","Right2Max":"-Infinity","MinMaxSave":1,"Source":11,"Unit":"","UnitEn":"","ChartSource":"平衡表,弘则研究","ChartSourceEn":"平衡表,弘则研究","SeasonExtraConfig":"","StartYear":0,"ChartThemeId":1,"ChartThemeStyle":"{\"colorsOptions\":[\"rgba(179, 237, 21, 1)\",\"rgba(187, 255, 0, 1)\",\"#999\",\"#000\",\"#7cb5ec\",\"#90ed7d\",\"#f7a35c\",\"#8085e9\",\"#f15c80\",\"#e4d354\"],\"lineOptions\":{\"dashStyle\":\"Solid\",\"lineWidth\":1,\"lineType\":\"line\",\"radius\":5},\"legendOptions\":{\"verticalAlign\":\"top\",\"itemStyle\":{\"color\":\"rgba(255, 98, 0, 1)\",\"fontSize\":12,\"cursor\":\"pointer\",\"fontWeight\":\"bold\",\"textOverflow\":\"ellipsis\"}},\"titleOptions\":{\"align\":\"right\",\"style\":{\"color\":\"rgba(208, 193, 20, 1)\",\"fontSize\":12}},\"markerOptions\":{\"style\":{\"color\":\"rgba(87, 205, 37, 1)\",\"fontSize\":12}},\"xAxisOptions\":{\"style\":{\"color\":\"rgba(255, 225, 0, 1)\",\"fontSize\":12}},\"yAxisOptions\":{\"style\":{\"color\":\"rgba(230, 69, 37, 1)\",\"fontSize\":12}},\"drawOption\":{\"plotBackgroundColor\":\"rgba(7, 24, 210, 0.22)\"}}","SourcesFrom":"{\"text\":\"平衡表\",\"isShow\":false}","Instructions":"","MarkersLines":"","MarkersAreas":""},"EdbInfoList":[{"EdbInfoId":81,"SourceName":"平衡表","Source":0,"EdbCode":"T240527094501_6274","EdbName":"指标1en","EdbAliasName":"指标1en","EdbAliasNameEn":"","EdbNameEn":"","Frequency":"","FrequencyEn":"","Unit":"","UnitEn":"","StartDate":"2024-01-01","EndDate":"2024-01-03","ModifyTime":"2024-05-29 17:22:42","ChartInfoId":1930,"MaxData":65.12,"MinData":13,"IsOrder":false,"IsAxis":1,"EdbInfoType":1,"EdbType":0,"LeadValue":0,"LeadUnit":"","LeadUnitEn":"","ChartStyle":"","ChartColor":"","ChartWidth":1,"DataList":[{"DataTime":"2024-01-01","DataTimestamp":1704038400000,"Value":23.11},{"DataTime":"2024-01-02","DataTimestamp":1704124800000,"Value":65.12},{"DataTime":"2024-01-12","DataTimestamp":1704211200000,"Value":13}],"EdbInfoCategoryType":0,"PredictChartColor":"","ChartType":0,"LatestDate":"2024-01-31","LatestValue":13,"MoveLatestDate":"2024-01-23","UniqueCode":"","MappingSource":0,"SubSource":0,"SubSourceName":"","IndicatorCode":"","StockCode":"","IsConvert":0,"ConvertType":0,"ConvertValue":0,"ConvertUnit":"","ConvertEnUnit":""},{"EdbInfoId":82,"SourceName":"平衡表","Source":0,"EdbCode":"T240527094501_1952","EdbName":"指标22en","EdbAliasName":"指标22en","EdbAliasNameEn":"","EdbNameEn":"","Frequency":"","FrequencyEn":"","Unit":"","UnitEn":"","StartDate":"2024-01-04","EndDate":"2024-01-05","ModifyTime":"2024-05-29 17:22:42","ChartInfoId":1930,"MaxData":15,"MinData":14,"IsOrder":false,"IsAxis":1,"EdbInfoType":1,"EdbType":0,"LeadValue":0,"LeadUnit":"","LeadUnitEn":"","ChartStyle":"","ChartColor":"","ChartWidth":1,"DataList":[{"DataTime":"2024-01-04","DataTimestamp":1704297600000,"Value":14},{"DataTime":"2024-01-05","DataTimestamp":1704384000000,"Value":15}],"EdbInfoCategoryType":0,"PredictChartColor":"","ChartType":0,"LatestDate":"2024-01-05","LatestValue":15,"MoveLatestDate":"2024-01-05","UniqueCode":"","MappingSource":0,"SubSource":0,"SubSourceName":"","IndicatorCode":"","StockCode":"","IsConvert":0,"ConvertType":0,"ConvertValue":0,"ConvertUnit":"","ConvertEnUnit":""}],"XEdbIdValue":[],"YDataList":[],"XDataList":null,"CorrelationChartInfo":null,"DataResp":null,"WaterMark":""},"Success":true,"IsSendEmail":true}`)
	var resp ChartCommonDetailResp
	if err = json.Unmarshal(result, &resp); err != nil {
		return
	}
	if resp.Ret != 200 {
		err = fmt.Errorf("%s,%s", resp.Msg, resp.ErrMsg)
		return
	}
	respData = resp.Data
	return
}

// GetRangeChartChartDetail 获取区间计算图表详情接口
func GetRangeChartChartDetail(uniqueCode string) (respData *chart_info.ChartLibChartInfoDetailResp, err error) {
	postUrl := fmt.Sprintf("%s/chart_auth/detail?UniqueCode=%s", global.CONFIG.EtaChartLib.ServerUrl, uniqueCode)
	result, err := httpGet(postUrl)
	if err != nil {
		return
	}
	var resp ChartCommonDetailResp
	if err = json.Unmarshal(result, &resp); err != nil {
		return
	}
	if resp.Ret != 200 {
		err = fmt.Errorf("%s,%s", resp.Msg, resp.ErrMsg)
		return
	}
	respData = resp.Data
	return
}

// post请求
func httpPost(url, postData string, params ...string) ([]byte, error) {
	body := ioutil.NopCloser(strings.NewReader(postData))
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	contentType := "application/x-www-form-urlencoded;charset=utf-8"
	if len(params) > 0 && params[0] != "" {
		contentType = params[0]
	}
	req.Header.Set("Content-Type", contentType)
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	fmt.Println("HttpPost:" + string(b))
	return b, err
}

// post请求
func httpGet(url string) ([]byte, error) {
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("authorization", utils.MD5(global.CONFIG.EtaChartLib.AppNameEn+global.CONFIG.EtaChartLib.Md5Key))
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	fmt.Println("httpGet:" + string(b))
	return b, err
}
