package cygx

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

var (
	ServerUrl                = "http://127.0.0.1:5008/"
	Cygx_activity_sigin_html = "cygx_activity_sigin_html"
	Cygx_mp3_html            = "cygx_mp3_html"
	Cygx_mp4_html            = "cygx_mp4_html"
	Cygx_mp3_yx_html         = "cygx_mp3_yx_html"
	Cygx_mp4_yx_html         = "cygx_mp4_yx_html"
)

type Html2ImgResp struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data string `json:"data"`
}

// postHtml2Img 请求htm2img接口
func postHtml2Img(param map[string]interface{}) (resp *Html2ImgResp, err error) {
	// 目前仅此处调用该接口，暂不加授权、校验等
	postUrl := ServerUrl + "htm2img"
	postData, err := json.Marshal(param)
	if err != nil {
		return
	}
	result, err := Html2ImgHttpPost(postUrl, string(postData), "application/json")
	if err != nil {
		return
	}
	if err = json.Unmarshal(result, &resp); err != nil {
		return
	}
	return resp, nil
}

// Html2ImgHttpPost post请求
func Html2ImgHttpPost(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
}

//func init() {
//	MakeActivitySigninImg(2161)
//}

// MakeActivitySigninImg 生成太阳码并上传OSS
func MakeActivitySigninImg(activityId int) (imgUrl string, err error) {
	var msg string
	defer func() {
		if err != nil || msg != "" {
			fmt.Println(err)
			utils.FileLog.Info("MakeActivitySigninImg Err:", err.Error())
			go alarm_msg.SendAlarmMsg("扫码签到日志记录，失败,活动ID："+strconv.Itoa(activityId)+err.Error()+";msg:"+msg, 3)
		}
	}()
	activityInfo, e := cygx.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("活动不存在, Err: " + e.Error())
		return
	}
	if activityInfo == nil {
		return
	}
	if activityInfo.ActivityTypeId != 5 && activityInfo.ActivityTypeId != 6 && activityInfo.ActivityTypeId != 8 {
		return
	}
	itemToken, err := models.GetWxToken(utils.WxCygxAppId, utils.WxCygxAppSecret)
	if err != nil {
		return
	}
	if itemToken.AccessToken == "" {
		msg = "accessToken is empty"
		return
	}
	var envVersion string
	var resourceUrl string
	if utils.RunMode == "release" {
		envVersion = "release"
	} else {
		envVersion = "trial"
	}
	url := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + itemToken.AccessToken
	method := "POST"
	payload := strings.NewReader(`{
		"page":"` + utils.WX_MSG_PATH_ACTIVITY_SIGNIN + `",
		"scene":"` + strconv.Itoa(activityId) + `",
		"env_version":"` + envVersion + `",
		"check_path":false,
		"auto_color":true
				}`)
	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)
	if err != nil {
		msg = "获取微信二维码失败,Err:" + err.Error()
		return
	}
	req.Header.Add("Content-Type", "application/json")
	postBody, err := client.Do(req)
	if err != nil {
		msg = "获取微信二维码失败,Err:" + err.Error()
		return
	}
	defer postBody.Body.Close()
	uploadDir := "static/img/share/"
	uuid := utils.GetRandStringNoSpecialChar(28)
	if !utils.FileIsExist(uploadDir) {
		err = os.MkdirAll(uploadDir, 0755)
		if err != nil {
			msg = "生成文件夹失败,Err:" + err.Error()
			return
		}
	}
	imagePath := uploadDir + uuid + ".jpg"
	switch header := postBody.Header.Get("Content-Type"); {
	case strings.HasPrefix(header, "application/json"):
		tokenResp := ReturnBodyRule{}
		decoder := json.NewDecoder(postBody.Body)
		if decodeErr := decoder.Decode(&tokenResp); decodeErr != nil {
			msg = "获取微信二维码失败,Err:" + decodeErr.Error()
			return
		}
	case strings.HasPrefix(header, "image"):
		reply, e := ioutil.ReadAll(postBody.Body)
		if e != nil {
			err = e
			msg = "获取微信二维码失败,Err:" + err.Error()
			return
		}
		imageContent, e := os.Create(imagePath)
		if e != nil {
			err = e
			msg = "获取微信二维码失败,Err:" + err.Error()
			return
		}
		writeStringRes, e := io.WriteString(imageContent, string(reply))
		if e != nil {
			err = e
			fmt.Println(writeStringRes)
			return
		}
		closeErr := imageContent.Close()
		if closeErr != nil {
			err = closeErr
			return
		}
		randStr := utils.GetRandStringNoSpecialChar(28)
		fileName := randStr + ".jpg"
		savePath := uploadDir + time.Now().Format("200601/20060102/")
		savePath += fileName
		//上传到阿里云
		err = services.UploadFileToAliyun(fileName, imagePath, savePath)
		if err != nil {
			fmt.Println("文件上传失败，Err:" + err.Error())
			return
		}
		fileHost := "https://hzstatic.hzinsights.com/"
		resourceUrl = fileHost + savePath
		defer func() {
			os.Remove(imagePath)
		}()
	default:
		msg = "生成二维码失败"
		return
	}

	detailConfig, e := cygx.GetCygxConfigDetailByCode(Cygx_activity_sigin_html)
	if e != nil {
		err = errors.New("GetCygxConfigDetailByCode 获取配置签到码格式信息失败, Err: " + e.Error())
		return
	}
	configValue := detailConfig.ConfigValue
	configValue = strings.Replace(configValue, "{{TITLE}}", activityInfo.ActivityName, -1)
	configValue = strings.Replace(configValue, "{{IMG}}", resourceUrl, -1)
	configValue = strings.Replace(configValue, "{{PLEASE}}", "请扫码确认签到", -1)
	configValue = strings.Replace(configValue, "{{SHOWTEXT}}", "将签到成功页面出示给接待人员", -1)
	htm2ImgReq := make(map[string]interface{})
	htm2ImgReq["html_content"] = configValue
	htm2ImgReq["width"] = 1364
	htm2ImgReq["height"] = 2060
	res, err := postHtml2Img(htm2ImgReq)
	if err != nil || res == nil {
		msg = "html转图片请求失败"
		return
	}
	if res.Code != 200 {
		msg = "html转图片请求失败"
		err = errors.New("html转图片失败: " + res.Msg)
		return
	}
	imgUrl = res.Data
	// 记录海报信息

	err = cygx.UpdateCygxActivitySigninImg(imgUrl, activityId)
	if err != nil {
		return
	}
	item := new(cygx.CygxActivityPoster)
	item.ActivityId = activityId
	item.ImgXcx = resourceUrl
	item.ImgPoster = imgUrl
	item.CreateTime = time.Now()
	err = cygx.AddCygxActivityPoster(item)
	return
}

// 生成音视频分享封面图
func MakeCygxMp3HtmlImg(videoDuration string, chartPermissionId int) (imgUrl string, err error) {
	var msg string
	defer func() {
		if err != nil || msg != "" {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("生成音视频分享封面图，失败 MakeCygxMp3HtmlImg："+err.Error()+";msg:"+msg, 3)
		}
	}()

	var configCode string
	if chartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
		configCode = Cygx_mp3_yx_html
	} else {
		configCode = Cygx_mp3_html
	}
	detailConfig, e := cygx.GetCygxConfigDetailByCode(configCode)
	if e != nil {
		err = errors.New("GetCygxConfigDetailByCode 获取配置生成音视频分享封面图格式信息失败, Err: " + e.Error())
		return
	}
	// 处理时长带有小数点的字符串
	slice := strings.Split(videoDuration, ".")
	for k, v := range slice {
		if k != 0 {
			continue
		}
		videoDuration = v
	}
	//先转换时长展示样式再替换
	secondNum, _ := strconv.Atoi(videoDuration)
	videoDuration = utils.HideSecondsToMs(secondNum)

	configValue := detailConfig.ConfigValue
	configValue = strings.Replace(configValue, "{{TIME}}", videoDuration, -1)
	htm2ImgReq := make(map[string]interface{})
	htm2ImgReq["html_content"] = configValue
	htm2ImgReq["width"] = 1364
	htm2ImgReq["height"] = 2060
	res, err := postHtml2Img(htm2ImgReq)
	if err != nil || res == nil {
		msg = "html转图片请求失败"
		return
	}
	if res.Code != 200 {
		msg = "html转图片请求失败"
		err = errors.New("html转图片失败: " + res.Msg)
		return
	}
	imgUrl = res.Data
	return
}

// 生成音视频分享封面图
func MakeCygxMp4HtmlImg(videoDuration string, chartPermissionId int) (imgUrl string, err error) {
	var msg string
	defer func() {
		if err != nil || msg != "" {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("生成音视频分享封面图，失败 MakeCygxMp4HtmlImg："+err.Error()+";msg:"+msg, 3)
		}
	}()

	var configCode string
	if chartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
		configCode = Cygx_mp4_yx_html
	} else {
		configCode = Cygx_mp4_html
	}

	detailConfig, e := cygx.GetCygxConfigDetailByCode(configCode)
	if e != nil {
		err = errors.New("GetCygxConfigDetailByCode 获取配置生成音视频分享封面图格式信息失败, Err: " + e.Error())
		return
	}

	// 处理时长带有小数点的字符串
	slice := strings.Split(videoDuration, ".")
	for k, v := range slice {
		if k != 0 {
			continue
		}
		videoDuration = v
	}
	//先转换时长展示样式再替换
	secondNum, _ := strconv.Atoi(videoDuration)
	videoDuration = utils.HideSecondsToMs(secondNum)

	configValue := detailConfig.ConfigValue
	configValue = strings.Replace(configValue, "{{TIME}}", videoDuration, -1)
	htm2ImgReq := make(map[string]interface{})
	htm2ImgReq["html_content"] = configValue
	htm2ImgReq["width"] = 1364
	htm2ImgReq["height"] = 2060
	res, err := postHtml2Img(htm2ImgReq)
	if err != nil || res == nil {
		msg = "html转图片请求失败"
		return
	}
	if res.Code != 200 {
		msg = "html转图片请求失败"
		err = errors.New("html转图片失败: " + res.Msg)
		return
	}
	imgUrl = res.Data
	return
}

//func init() {
//	//MakeActivityMomentsImg(2850)
//	var condition string
//	var pars []interface{}
//	condition = " AND   chart_permission_id  = 31  AND  publish_status   = 1   AND active_state  = 1  ORDER BY  activity_id DESC   "
//	list, errList := cygx.GetActivityListAll(condition, pars, 0, 9999)
//	if errList != nil {
//		fmt.Println(errList)
//		return
//	}
//	fmt.Println("list", len(list))
//
//	//return
//	for _, v := range list {
//		MakeActivityMomentsImg(v.ActivityId)
//	}
//
//}

// 生成活动分享到朋友圈的图片
func MakeActivityMomentsImg(activityId int) {
	var err error
	//time.Sleep(3*time.Second) // 有时候同时添加多个活动，延迟三秒
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("生成活动分享到朋友圈的图片失败，MakeActivityMomentsImg Err："+err.Error()+"活动ID"+strconv.Itoa(activityId), 3)
		}
	}()
	detail, e := cygx.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("GetCygxReportSelectionInfoById, Err: " + e.Error())
		return
	}

	// 不是研选活动不生成图片
	if detail.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN {
		return
	}
	var configCode string
	if detail.IsResearchPoints == 1 {
		configCode = "activity_moments_img_points_html" // 扣点活动
	} else {
		configCode = "activity_moments_img_html" // 非扣点活动
	}

	detailConfig, e := cygx.GetCygxConfigDetailByCode(configCode)
	if e != nil {
		err = errors.New("GetCygxConfigDetailByCode 获取生成活动分享到朋友圈的图片格式信息失败, Err: " + e.Error())
		return
	}
	configValue := detailConfig.ConfigValue
	configValue = strings.Replace(configValue, "{{Title}}", detail.ActivityName, -1)
	configValue = strings.Replace(configValue, "{{ActivityTypeName}}", detail.ActivityTypeName, -1)
	configValue = strings.Replace(configValue, "{{Label}}", detail.Label, -1)
	configValue = strings.Replace(configValue, "{{ActivityTimeText}}", detail.ActivityTimeText, -1)
	htm2ImgReq := make(map[string]interface{})
	htm2ImgReq["html_content"] = configValue
	htm2ImgReq["width"] = 2250
	htm2ImgReq["height"] = 3813
	res, err := postHtml2Img(htm2ImgReq)
	if err != nil || res == nil {
		err = errors.New("html转图片失败: ")
		return
	}
	if res.Code != 200 {
		err = errors.New("html转图片失败: " + res.Msg)
		return
	}
	imgUrl := res.Data
	// 记录海报信息
	err = cygx.UpdateCygxActivityMomentsImg(imgUrl, activityId)
	if err != nil {
		return
	}
}

// MakeMfyxActivitySigninImg 生成mfyx太阳码并上传OSS
//func MakeMfyxActivitySigninImg(activityId int) (imgUrl string, err error) {
//	var msg string
//	defer func() {
//		if err != nil || msg != "" {
//			fmt.Println(err)
//			utils.FileLog.Info("MakeMfyxActivitySigninImg Err:", err.Error())
//			go alarm_msg.SendAlarmMsg("扫码签到日志记录，失败,活动ID："+strconv.Itoa(activityId)+err.Error()+";msg:"+msg, 3)
//		}
//	}()
//	activityInfo, e := cygx.GetAddActivityInfoById(activityId)
//	if e != nil {
//		err = errors.New("活动不存在, Err: " + e.Error())
//		return
//	}
//	if activityInfo == nil {
//		return
//	}
//	if activityInfo.ActivityTypeId != 5 && activityInfo.ActivityTypeId != 6 && activityInfo.ActivityTypeId != 8 {
//		return
//	}
//	itemToken, err := models.GetWxToken(utils.WxMfyxAppId, utils.WxMfyxAppSecret)
//	if err != nil {
//		return
//	}
//	if itemToken.AccessToken == "" {
//		msg = "accessToken is empty"
//		return
//	}
//	var envVersion string
//	var resourceUrl string
//	if utils.RunMode == "release" {
//		envVersion = "release"
//	} else {
//		envVersion = "trial"
//	}
//	url := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + itemToken.AccessToken
//	method := "POST"
//	payload := strings.NewReader(`{
//		"page":"` + utils.WX_MSG_PATH_ACTIVITY_SIGNIN + `",
//		"scene":"` + strconv.Itoa(activityId) + `",
//		"env_version":"` + envVersion + `",
//		"check_path":false,
//		"auto_color":true
//				}`)
//	client := &http.Client{}
//	req, err := http.NewRequest(method, url, payload)
//	if err != nil {
//		msg = "获取微信二维码失败,Err:" + err.Error()
//		return
//	}
//	req.Header.Add("Content-Type", "application/json")
//	postBody, err := client.Do(req)
//	if err != nil {
//		msg = "获取微信二维码失败,Err:" + err.Error()
//		return
//	}
//	defer postBody.Body.Close()
//	uploadDir := "static/img/share/"
//	uuid := utils.GetRandStringNoSpecialChar(28)
//	if !utils.FileIsExist(uploadDir) {
//		err = os.MkdirAll(uploadDir, 0755)
//		if err != nil {
//			msg = "生成文件夹失败,Err:" + err.Error()
//			return
//		}
//	}
//	imagePath := uploadDir + uuid + ".jpg"
//	switch header := postBody.Header.Get("Content-Type"); {
//	case strings.HasPrefix(header, "application/json"):
//		tokenResp := ReturnBodyRule{}
//		decoder := json.NewDecoder(postBody.Body)
//		if decodeErr := decoder.Decode(&tokenResp); decodeErr != nil {
//			msg = "获取微信二维码失败,Err:" + decodeErr.Error()
//			return
//		}
//	case strings.HasPrefix(header, "image"):
//		reply, e := ioutil.ReadAll(postBody.Body)
//		if e != nil {
//			err = e
//			msg = "获取微信二维码失败,Err:" + err.Error()
//			return
//		}
//		imageContent, e := os.Create(imagePath)
//		if e != nil {
//			err = e
//			msg = "获取微信二维码失败,Err:" + err.Error()
//			return
//		}
//		writeStringRes, e := io.WriteString(imageContent, string(reply))
//		if e != nil {
//			err = e
//			fmt.Println(writeStringRes)
//			return
//		}
//		closeErr := imageContent.Close()
//		if closeErr != nil {
//			err = closeErr
//			return
//		}
//		randStr := utils.GetRandStringNoSpecialChar(28)
//		fileName := randStr + ".jpg"
//		savePath := uploadDir + time.Now().Format("200601/20060102/")
//		savePath += fileName
//		//上传到阿里云
//		err = services.UploadFileToAliyun(fileName, imagePath, savePath)
//		if err != nil {
//			fmt.Println("文件上传失败，Err:" + err.Error())
//			return
//		}
//		fileHost := "https://hzstatic.hzinsights.com/"
//		resourceUrl = fileHost + savePath
//		defer func() {
//			os.Remove(imagePath)
//		}()
//	default:
//		msg = "生成二维码失败"
//		return
//	}
//
//	detailConfig, e := cygx.GetCygxConfigDetailByCode(Cygx_activity_sigin_html)
//	if e != nil {
//		err = errors.New("GetCygxConfigDetailByCode 获取配置签到码格式信息失败, Err: " + e.Error())
//		return
//	}
//	configValue := detailConfig.ConfigValue
//	configValue = strings.Replace(configValue, "{{TITLE}}", activityInfo.ActivityName, -1)
//	configValue = strings.Replace(configValue, "{{IMG}}", resourceUrl, -1)
//	configValue = strings.Replace(configValue, "{{PLEASE}}", "请扫码确认签到", -1)
//	configValue = strings.Replace(configValue, "{{SHOWTEXT}}", "将签到成功页面出示给接待人员", -1)
//	htm2ImgReq := make(map[string]interface{})
//	htm2ImgReq["html_content"] = configValue
//	htm2ImgReq["width"] = 1364
//	htm2ImgReq["height"] = 2060
//	res, err := postHtml2Img(htm2ImgReq)
//	if err != nil || res == nil {
//		msg = "html转图片请求失败"
//		return
//	}
//	if res.Code != 200 {
//		msg = "html转图片请求失败"
//		err = errors.New("html转图片失败: " + res.Msg)
//		return
//	}
//	imgUrl = res.Data
//	// 记录海报信息
//
//	err = cygx.UpdateCygxActivitySigninImg(imgUrl, activityId)
//	if err != nil {
//		return
//	}
//	item := new(cygx.CygxActivityPoster)
//	item.ActivityId = activityId
//	item.ImgXcx = resourceUrl
//	item.ImgPoster = imgUrl
//	item.CreateTime = time.Now()
//	err = cygx.AddCygxActivityPoster(item)
//	return
//}
