package services

import (
	"errors"
	"fmt"
	"hongze/hongze_yb/models/tables/yb_config"
	"hongze/hongze_yb/models/tables/yb_pc_suncode"
	"hongze/hongze_yb/models/tables/yb_resource"
	"hongze/hongze_yb/models/tables/yb_suncode_pars"
	"hongze/hongze_yb/services/wx_app"
	"hongze/hongze_yb/utils"
	"os"
	"time"
)

// SunCodeReq 获取太阳码请求体
type SunCodeReq struct {
	CodePage  string `json:"CodePage" description:"太阳码page"`
	CodeScene string `json:"CodeScene" description:"太阳码scene"`
}

// PcCreateAndUploadSunCode 生成太阳码并上传OSS
func PcCreateAndUploadSunCode(scene, page string) (imgUrl string, err error) {
	defer func() {
		if err != nil {
			fmt.Println("PcCreateAndUploadSunCode Err:" + err.Error())
		}
	}()
	if page == "" {
		err = errors.New("page不能为空")
		return
	}

	// scene超过32位会生成失败，md5处理至32位
	sceneMD5 := "a=1"
	if scene != "" {
		sceneMD5 = utils.MD5(scene)
	}

	// 根据配置选择小程序
	conf, e := yb_config.GetConfigByCode(yb_config.KeyUseCopyYb)
	if e != nil {
		err = errors.New("获取小程序配置失败, Err: " + e.Error())
		return
	}

	picByte, err := wx_app.GetSunCode(page, sceneMD5, conf.ConfigValue)
	if err != nil {
		return
	}
	// 生成图片
	localPath := "./static/img"
	fileName := utils.GetRandStringNoSpecialChar(28) + ".png"
	fpath := fmt.Sprint(localPath, "/", fileName)
	f, err := os.Create(fpath)
	if err != nil {
		return
	}
	if _, err = f.Write(picByte); err != nil {
		return
	}
	defer func() {
		f.Close()
		os.Remove(fpath)
	}()
	// 上传OSS
	fileDir := "yb/suncode/"
	imgUrl, err = UploadAliyunToDir(fileName, fpath, fileDir)
	if err != nil {
		return
	}

	// 记录参数
	if scene != "" {
		newPars := &yb_pc_suncode.YbPcSuncode{
			Scene:      scene,
			SceneMd5:   sceneMD5,
			CodePage:   page,
			SuncodeURL: imgUrl,
			CreateTime: time.Now(),
		}
		err = newPars.Create()
	}
	// 记录参数md5
	if scene != "" {
		newPars := &yb_suncode_pars.YbSuncodePars{
			Scene:      scene,
			SceneKey:   sceneMD5,
			CreateTime: time.Now(),
		}
		err = newPars.Create()
	}

	// 记录文件
	go func() {
		re := new(yb_resource.YbResource)
		re.ResourceUrl = imgUrl
		re.ResourceType = yb_resource.ResourceTypeImg
		re.CreateTime = time.Now().Local()
		if e := re.Create(); e != nil {
			return
		}
	}()
	return
}
