package cygx

import (
	"encoding/json"
	"fmt"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"io/ioutil"
	nhttp "net/http"
	"strconv"
	"strings"
	"time"
)

// get公共请求方法
func PublicGetDate(url, authorization string) (body []byte, err error) {
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", url+"Get ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	method := "GET"
	client := &nhttp.Client{}
	req, err := nhttp.NewRequest(method, url, nil)
	if err != nil {
		return
	}
	req.Header.Add("Authorization", authorization)
	res, err := client.Do(req)
	if err != nil {
		return
	}
	defer res.Body.Close()
	body, err = ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}
	return
}

// 获取用户的Token
func GetUserTokenByMobile(mobile string) (token string, err error) {
	//缓存校验
	cacheKey := fmt.Sprint("xygx_chart:chart_token:add:", "Mobile", mobile)
	ttlTime := utils.Rc.GetRedisTTL(cacheKey)
	if ttlTime > 0 {
		token, _ = utils.Rc.RedisString(cacheKey)
	}
	if token == "" {
		url := utils.HZ_CELUE_API_Url + "auth/login"
		method := "POST"
		payload := strings.NewReader(`{
    "phone_number":"` + mobile + `",
    "password":"hz123456"}`)
		client := &nhttp.Client{}
		req, errReq := nhttp.NewRequest(method, url, payload)
		if errReq != nil {
			err = errReq
			return
		}
		req.Header.Add("Content-Type", "application/json")
		req.Header.Add("Cookie", "sessionid=naj5j5kl1jjynh7og1rsaxkl1vrsl829")
		res, errReq := client.Do(req)
		if errReq != nil {
			err = errReq
			return
		}
		defer res.Body.Close()
		body, errReq := ioutil.ReadAll(res.Body)
		if errReq != nil {
			err = errReq
			return
		}
		var chartResult cygx.ChartUserTokenResultApi
		errReq = json.Unmarshal(body, &chartResult)
		if errReq != nil {
			err = errReq
			return
		}
		token = chartResult.Data.AccessToken
		utils.Rc.Put(cacheKey, token, time.Hour*24)
	}
	return
}

// 获取图表收藏
func GetChartCollectionByApi(mobile string, take, skip int) (items []*cygx.HomeChartListResp, err error, total int) {
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "GetChartPtagByApi ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	url := utils.HZ_CELUE_API_Url + "charts/favorites?take=" + strconv.Itoa(take) + "&skip=" + strconv.Itoa(skip)
	authorization, err := GetUserTokenByMobile(mobile)
	if err != nil {
		return
	}
	authorization = "bearer " + authorization
	body, err := PublicGetDate(url, authorization)
	if err != nil {
		return
	}
	var chartResult cygx.ChartFavoritesResultApi
	err = json.Unmarshal(body, &chartResult)
	if err != nil {
		return
	}
	for _, v := range chartResult.Data {
		item := new(cygx.HomeChartListResp)
		item.ChartId = v.ChartId
		item.Title = v.ChartInfo.Title
		item.TitleEn = v.ChartInfo.TitleEn
		t1, _ := time.Parse("2006-01-02T15:04:05Z", v.CreateDate)
		item.CreateDate = t1.Add(+time.Hour * 8).Format(utils.FormatDateTime)
		item.PtagName = v.ChartInfo.Ptag.Name
		item.CtagName = v.ChartInfo.Ctag.Name
		item.BodyHtml = v.ChartInfo.Cover
		item.HttpUrl = "https://vmp.hzinsights.com/v2/charts/" + strconv.Itoa(v.ChartId)
		item.IsNeedJump = true
		items = append(items, item)
	}
	total = chartResult.Pagination.Total
	return
}

// 判断策略平台是否已经添加过收藏
func GetIsCollectionChart(mobile string, chartId int) (isCollection bool, err error) {
	//获取所有的收藏列表，进行比对看看是否收藏，调用三方接口详情没有是否收藏的字段
	list, err, _ := GetChartCollectionByApi(mobile, 9999, 0)
	if err != nil {
		return
	}
	for _, v := range list {
		if v.ChartId == chartId {
			isCollection = true
		}
	}
	return
}

// GetChartTitleMapByid 通过图表ID获取文章标题 map
func GetChartTitleMapByid(chartIds []int) (mapResp map[int]string) {
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(" 通过图表ID获取文章标题 map，信息失败，Err："+err.Error(), 3)
		}
	}()
	lenchartIds := len(chartIds)
	if lenchartIds == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = `  AND chart_id IN (` + utils.GetOrmInReplace(lenchartIds) + `)  `
	pars = append(pars, chartIds)
	chartList, err := cygx.GetChartList(condition, pars, 0, lenchartIds)
	if err != nil {
		return
	}
	mapResp = make(map[int]string, 0)
	for _, v := range chartList {
		mapResp[v.ChartId] = v.Title
	}
	return
}
