package services

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/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
}

// 同步图表列表
func GetChartListByApi(cont context.Context) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("发送邮件：同步用户到策略平台信息失败", 2)
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "GetArticleListByApi ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	mapChartid := make(map[int]int)
	chartList, err := models.GetChartListAll()
	if err != nil {
		return
	}
	for _, v := range chartList {
		mapChartid[v.ChartId] = v.ChartId
	}

	mapAllChartid := make(map[int]int)
	chartAllList, err := models.GetChartAllListAll()
	if err != nil {
		return
	}
	for _, v := range chartAllList {
		mapAllChartid[v.ChartId] = v.ChartId
	}
	var chartIdsDelete []int
	url := utils.ApiUrl + "charts/mp?take=100&skip=0"
	authorization := utils.ApiAuthorization
	body, err := PublicGetDate(url, authorization)
	if err != nil {
		return
	}
	var chartResult models.ChartResultApi
	err = json.Unmarshal(body, &chartResult)
	if err != nil {
		return err
	}
	for _, v := range chartResult.Data {
		item := new(models.CygxChart)
		item.ChartId = v.ChartId
		item.PtagId = v.PtagId
		item.CtagId = v.CtagId
		item.Title = v.Title
		item.TitleEn = v.TitleEn
		item.CreateDateApi = time.Now()
		item.CreateDate = v.CreateDate
		item.PublishStatus = v.PublishStatus
		item.PtagName = v.Ptag.Name
		item.CtagName = v.Ctag.Name

		item.PtagNameTwo = v.PtagTwo.Name
		item.CtagNameTwo = v.CtagTwo.Name
		item.PtagIdTwo = v.PtagTwo.Id
		item.CtagIdTwo = v.CtagTwo.Id
		item.Cover = v.Cover
		item.Iframe = v.Iframe

		//如果没有就新增 有就更新
		if mapChartid[v.ChartId] == 0 {
			_, err := models.AddCygxChart(item)
			if item.PublishStatus == 1 {
				go UpdateResourceData(item.ChartId, "newchart", "add", time.Now().Format(utils.FormatDateTime))
			}
			if err != nil {
				return err
			}
		} else {
			if item.PublishStatus == 0 {
				chartIdsDelete = append(chartIdsDelete, item.ChartId)
			}
			updateParams := make(map[string]interface{})
			updateParams["Title"] = v.Title
			updateParams["PtagId"] = v.PtagId
			updateParams["CtagId"] = v.CtagId
			updateParams["TitleEn"] = v.TitleEn
			updateParams["CreateDate"] = v.CreateDate
			updateParams["PublishStatus"] = v.PublishStatus
			updateParams["PtagName"] = v.Ptag.Name
			updateParams["CtagName"] = v.Ctag.Name
			updateParams["PtagNameTwo"] = v.PtagTwo.Name
			updateParams["CtagNameTwo"] = v.CtagTwo.Name
			updateParams["PtagIdTwo"] = v.PtagTwo.Id
			updateParams["CtagIdTwo"] = v.CtagTwo.Id
			updateParams["Cover"] = v.Cover
			updateParams["Iframe"] = v.Iframe
			whereParam := map[string]interface{}{"chart_id": v.ChartId}
			err = models.UpdateByExpr(models.CygxChart{}, whereParam, updateParams)
			if err != nil {
				return err
			}
		}

	}

	fmt.Println("删除的", chartIdsDelete)
	if len(chartIdsDelete) > 0 {
		go Deletenewchart(chartIdsDelete)
	}

	//策略平台图表，记录所有，的显示用户收藏使用
	url = utils.ApiUrl + "charts?take=100&skip=0" // 获取所有的图表链接
	body, err = PublicGetDate(url, authorization)
	if err != nil {
		return
	}

	err = json.Unmarshal(body, &chartResult)
	if err != nil {
		return err
	}
	for _, v := range chartResult.Data {
		item := new(models.CygxChartAll)
		item.ChartId = v.ChartId
		item.PtagId = v.PtagId
		item.CtagId = v.CtagId
		item.Title = v.Title
		item.TitleEn = v.TitleEn
		item.CreateDateApi = time.Now()
		item.CreateDate = v.CreateDate
		item.PublishStatus = v.PublishStatus
		item.PtagName = v.Ptag.Name
		item.CtagName = v.Ctag.Name

		item.PtagNameTwo = v.PtagTwo.Name
		item.CtagNameTwo = v.CtagTwo.Name
		item.PtagIdTwo = v.PtagTwo.Id
		item.CtagIdTwo = v.CtagTwo.Id
		item.Cover = v.Cover
		item.Iframe = v.Iframe

		//如果没有就新增 有就更新
		if mapAllChartid[v.ChartId] == 0 {
			_, err := models.AddCygxChartAll(item)
			if err != nil {
				return err
			}
		} else {
			updateParams := make(map[string]interface{})
			updateParams["Title"] = v.Title
			updateParams["PtagId"] = v.PtagId
			updateParams["CtagId"] = v.CtagId
			updateParams["TitleEn"] = v.TitleEn
			updateParams["CreateDate"] = v.CreateDate
			updateParams["PublishStatus"] = v.PublishStatus
			updateParams["PtagName"] = v.Ptag.Name
			updateParams["CtagName"] = v.Ctag.Name
			updateParams["PtagNameTwo"] = v.PtagTwo.Name
			updateParams["CtagNameTwo"] = v.CtagTwo.Name
			updateParams["PtagIdTwo"] = v.PtagTwo.Id
			updateParams["CtagIdTwo"] = v.CtagTwo.Id
			updateParams["Cover"] = v.Cover
			updateParams["Iframe"] = v.Iframe
			whereParam := map[string]interface{}{"chart_id": v.ChartId}
			err = models.UpdateByExpr(models.CygxChartAll{}, whereParam, updateParams)
			if err != nil {
				return err
			}
		}
	}
	return

}

// 获取图表分类
func GetChartPtagByApi() (items []*models.ChartPtagResp, err error) {
	defer func() {
		if err != nil {
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "GetChartPtagByApi ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	url := utils.ApiUrl + "charts/ptag"
	authorization := utils.ApiAuthorization
	body, err := PublicGetDate(url, authorization)
	if err != nil {
		return
	}
	var chartResult models.ChartPtagResultApi
	err = json.Unmarshal(body, &chartResult)
	if err != nil {
		return
	}
	for _, v := range chartResult.Data {
		item := new(models.ChartPtagResp)
		item.PermissionName = v.ChartPermissionName
		item.ChartPermissionId = v.ChartPermissionId
		if len(v.Ctag) > 0 {
			for _, v2 := range v.Ctag {
				itemCtag := new(models.CtagResp)
				itemCtag.CtagId = v2.Id
				itemCtag.Name = v2.Name
				item.List = append(item.List, itemCtag)
			}
		}
		items = append(items, item)
	}
	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.ApiUrl + "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 models.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 []*models.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.ApiUrl + "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 models.ChartFavoritesResultApi
	err = json.Unmarshal(body, &chartResult)
	if err != nil {
		return
	}
	for _, v := range chartResult.Data {
		item := new(models.HomeChartListResp)
		item.ChartId = v.ChartId
		item.Title = v.ChartInfo.Title
		item.TitleEn = v.ChartInfo.TitleEn
		item.CreateDate = v.CreateDate
		item.PtagName = v.ChartInfo.Ptag.Name
		item.CtagName = v.ChartInfo.Ctag.Name
		item.BodyHtml = v.ChartInfo.Cover
		item.HttpUrl = utils.CHART_INFO_HTTP_URL + 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
}

// 添加收藏
func AddCollectionChart(mobile string, chartId int) (err error) {
	authorization, err := GetUserTokenByMobile(mobile)
	if err != nil {
		return
	}
	authorization = "bearer " + authorization
	url := utils.ApiUrl + "charts/favorites"
	method := "POST"
	payload := strings.NewReader(`{
    "chart_id":` + strconv.Itoa(chartId) + `
}`)
	client := &nhttp.Client{}
	req, err := nhttp.NewRequest(method, url, payload)
	if err != nil {
		return
	}
	req.Header.Add("Authorization", authorization)
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Cookie", "sessionid=naj5j5kl1jjynh7og1rsaxkl1vrsl829")
	res, err := client.Do(req)
	if err != nil {
		return
	}
	defer res.Body.Close()
	_, err = ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}
	return
}

// 移除收藏
func DeleteCollectionChart(mobile string, chartId int) (err error) {
	authorization, err := GetUserTokenByMobile(mobile)
	if err != nil {
		return
	}
	authorization = "bearer " + authorization
	url := utils.ApiUrl + "charts/favorites/" + strconv.Itoa(chartId)
	method := "DELETE"
	client := &nhttp.Client{}
	req, err := nhttp.NewRequest(method, url, nil)
	if err != nil {
		return
	}
	req.Header.Add("Authorization", authorization)
	req.Header.Add("Cookie", "sessionid=naj5j5kl1jjynh7og1rsaxkl1vrsl829")
	res, err := client.Do(req)
	if err != nil {
		return
	}
	defer res.Body.Close()
	_, err = ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}
	return
}

func GetChartDetailByChartId(cont context.Context) (err error) {
	listUpdate, err := models.GetChartCeluePushList()
	if err != nil && err.Error() != utils.ErrNoRow() {
		go utils.SendAlarmMsg("发送邮件：同步用户到策略平台信息失败，图表1ID："+err.Error(), 2)
	}
	//如果长度为零就不处理
	if len(listUpdate) == 0 {
		return err
	}
	for _, v := range listUpdate {
		err = GetChartDetailByApi(v.ChartId)
		if err != nil {
			go utils.SendAlarmMsg("发送邮件：同步用户到策略平台信息失败，图表2ID："+strconv.Itoa(v.ChartId)+err.Error(), 2)
		}
		err = models.UpdateCygxChartCeluePush(v.ChartId)
		if err != nil {
			go utils.SendAlarmMsg("发送邮件：同步用户到策略平台信息失败，图表3ID："+strconv.Itoa(v.ChartId)+err.Error(), 2)
		}
	}
	return
}

//func init() {
//	GetChartDetailByApi(6370)
//}

// 同步图表详情
func GetChartDetailByApi(chartId int) (err error) {
	defer func() {
		if err != nil {
			//fmt.Println(err)
			go utils.SendAlarmMsg("发送邮件：同步用户到策略平台信息失败，图表4ID："+strconv.Itoa(chartId)+err.Error(), 2)
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "GetArticleListByApi ，图表ID："+strconv.Itoa(chartId)+"ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	mapChartid := make(map[int]int)
	chartList, err := models.GetChartListAll()
	if err != nil {
		return
	}
	for _, v := range chartList {
		mapChartid[v.ChartId] = v.ChartId
	}
	mapAllChartid := make(map[int]int)
	chartAllList, err := models.GetChartAllListAll()
	if err != nil {
		return
	}
	for _, v := range chartAllList {
		mapAllChartid[v.ChartId] = v.ChartId
	}
	var chartIdsDelete []int
	url := utils.ApiUrl + "charts/" + strconv.Itoa(chartId)
	authorization := utils.ApiAuthorization
	body, err := PublicGetDate(url, authorization)
	if err != nil {
		return
	}
	var resultDate models.ChartResultDetailApi
	err = json.Unmarshal(body, &resultDate)
	if err != nil {
		return err
	}
	v := resultDate.Data

	if v.ChartId == 0 {
		err = models.DeleteCygxChart(chartId)
		return
	}
	item := new(models.CygxChart)
	item.ChartId = v.ChartId
	item.PtagId = v.PtagId
	item.CtagId = v.CtagId
	item.Title = v.Title
	item.TitleEn = v.TitleEn
	item.CreateDateApi = time.Now()
	item.CreateDate = v.CreateDate
	item.PublishStatus = v.PublishStatus
	item.PtagName = v.Ptag.Name
	item.CtagName = v.Ctag.Name

	item.PtagNameTwo = v.PtagTwo.Name
	item.CtagNameTwo = v.CtagTwo.Name
	item.PtagIdTwo = v.PtagTwo.Id
	item.CtagIdTwo = v.CtagTwo.Id
	item.Cover = v.Cover
	item.Iframe = v.Iframe

	//如果是软删除就做取消发布处理
	if !v.IsActive {
		item.PublishStatus = 0
	}

	//如果没有就新增 有就更新
	if mapChartid[chartId] == 0 {
		_, err := models.AddCygxChart(item)
		if item.PublishStatus == 1 && v.IsActive {
			//go UpdateResourceData(chartId, "newchart", "add", time.Now().Format(utils.FormatDateTime))
		}
		if err != nil {
			return err
		}
	} else {
		if item.PublishStatus == 0 {
			chartIdsDelete = append(chartIdsDelete, chartId)
		}
		updateParams := make(map[string]interface{})
		updateParams["Title"] = v.Title
		updateParams["PtagId"] = v.PtagId
		updateParams["CtagId"] = v.CtagId
		updateParams["TitleEn"] = v.TitleEn
		updateParams["CreateDate"] = v.CreateDate
		updateParams["PublishStatus"] = v.PublishStatus
		updateParams["PtagName"] = v.Ptag.Name
		updateParams["CtagName"] = v.Ctag.Name
		updateParams["PtagNameTwo"] = v.PtagTwo.Name
		updateParams["CtagNameTwo"] = v.CtagTwo.Name
		updateParams["PtagIdTwo"] = v.PtagTwo.Id
		updateParams["CtagIdTwo"] = v.CtagTwo.Id
		updateParams["Cover"] = v.Cover
		updateParams["Iframe"] = v.Iframe
		whereParam := map[string]interface{}{"chart_id": chartId}
		err = models.UpdateByExpr(models.CygxChart{}, whereParam, updateParams)
		if err != nil {
			return err
		}
		if item.PublishStatus == 0 {
			//go UpdateResourceData(chartId, "newchart", "delete", time.Now().Format(utils.FormatDateTime))
		}
	}
	//}
	fmt.Println("删除的", chartIdsDelete)
	//if len(chartIdsDelete) > 0 {
	//	go Deletenewchart(chartIdsDelete)
	//}

	//策略平台图表，记录所有，的显示用户收藏使用
	{
		item := new(models.CygxChartAll)
		item.ChartId = v.ChartId
		item.PtagId = v.PtagId
		item.CtagId = v.CtagId
		item.Title = v.Title
		item.TitleEn = v.TitleEn
		item.CreateDateApi = time.Now()
		item.CreateDate = v.CreateDate
		item.PublishStatus = v.PublishStatus
		item.PtagName = v.Ptag.Name
		item.CtagName = v.Ctag.Name

		item.PtagNameTwo = v.PtagTwo.Name
		item.CtagNameTwo = v.CtagTwo.Name
		item.PtagIdTwo = v.PtagTwo.Id
		item.CtagIdTwo = v.CtagTwo.Id
		item.Cover = v.Cover
		item.Iframe = v.Iframe

		//如果是软删除就做取消发布处理
		if !v.IsActive {
			item.PublishStatus = 0
		}

		//如果没有就新增 有就更新
		if mapAllChartid[chartId] == 0 {
			_, err := models.AddCygxChartAll(item)
			if err != nil {
				return err
			}
		} else {
			updateParams := make(map[string]interface{})
			updateParams["Title"] = v.Title
			updateParams["PtagId"] = v.PtagId
			updateParams["CtagId"] = v.CtagId
			updateParams["TitleEn"] = v.TitleEn
			updateParams["CreateDate"] = v.CreateDate
			updateParams["PublishStatus"] = v.PublishStatus
			updateParams["PtagName"] = v.Ptag.Name
			updateParams["CtagName"] = v.Ctag.Name
			updateParams["PtagNameTwo"] = v.PtagTwo.Name
			updateParams["CtagNameTwo"] = v.CtagTwo.Name
			updateParams["PtagIdTwo"] = v.PtagTwo.Id
			updateParams["CtagIdTwo"] = v.CtagTwo.Id
			updateParams["Cover"] = v.Cover
			updateParams["Iframe"] = v.Iframe
			whereParam := map[string]interface{}{"chart_id": chartId}
			err = models.UpdateByExpr(models.CygxChartAll{}, whereParam, updateParams)
			if err != nil {
				return err
			}
		}
	}

	go AddComprehensiveChart(chartId)      //同步图表到综合页面的搜索
	go UpdateNewchartResourceData(chartId) ////把数据写入 cygx_resource_data 表
	return

}

// 用户阅读图表，添加浏览记录
func ServerAddCygxChartRecord(wxUser *models.WxUserItem, ctagId int) {
	if wxUser.CompanyId < 1 {
		return
	}
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("用户阅读图表，添加浏览记录失败 ctagId", ctagId, "userId", wxUser.UserId, err.Error()), 2)
		}
	}()

	item := new(models.CygxChartRecord)
	item.ChartId = ctagId
	item.UserId = wxUser.UserId
	item.RealName = wxUser.RealName
	item.Mobile = wxUser.Mobile
	item.Email = wxUser.Email
	item.CompanyId = wxUser.CompanyId
	item.CompanyName = wxUser.CompanyName
	item.CreateTime = time.Now()
	item.RegisterPlatform = utils.REGISTER_PLATFORM
	_, e := models.AddCygxChartRecord(item)
	if e != nil {
		err = errors.New("AddCygxChartRecord" + e.Error())
		return
	}
	return
}
