package mobile

import (
	"fmt"
	"gin-vue-admin/global"
	"gin-vue-admin/model/response"
	"gin-vue-admin/service"
	"gin-vue-admin/utils"
	"gin-vue-admin/utils/wx"
	"github.com/gin-gonic/gin"
)

type GetUnlimitedReq struct {
	HospitalCode string `json:"hospitalCode"`
	DoctorPhone  string `json:"doctorPhone"`
	OtherNo      string `json:"otherNo"`
	QrType       string `json:"qrType"`
}

type GetUnlimitedForSurveyReply struct {
	QrData   string `json:"qrData"`
	OpenLink string `json:"openLink"`
}
type GetUnlimitedData struct {
	Scene  string `json:"scene"`   //最大32个可见字符，只支持数字，大小写英文以及部分特殊字符：!#$&'()*+,/:;=?@-._~，其它字符请自行编码为合法字符（因不支持%，中文无法使用 urlencode 处理，请使用其他编码方式）
	Page   string `json:"page"`    //必须是已经发布的小程序存在的页面（否则报错），例如 pages/index/index, 根路径前不要填加 /,不能携带参数（参数请放在scene字段里），如果不填写这个字段，默认跳主页面
	Width  int    `json:"width"`   //二维码的宽度，单位 px，最小 280px，最大 1280px
	ColorR string `json:"color_r"` //设置颜色
	ColorG string `json:"color_g"` //设置颜色
	ColorB string `json:"color_b"` //设置颜色
}

type GetSchemeReq struct {
	Path  string `json:"path"`
	Query string `json:"query"`
}

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

func GetUnlimitedForOther(c *gin.Context) {
	var req GetUnlimitedReq
	_ = c.ShouldBindJSON(&req)

	token := getToken()

	data := GetUnlimitedData{}
	data.Scene = req.HospitalCode + ";" + req.DoctorPhone + ";" + req.OtherNo + ";" + req.QrType
	data.Page = ""

	errcode, reply := getUnlimited(token, data)

	if errcode != 200 {
		response.FailWithDetailedCode(411, "", "accesstoken获取失败", c)
	} else {
		response.OkWithData(reply, c)
		return
	}
}

func GetUnlimited(c *gin.Context) {
	var req GetUnlimitedReq
	_ = c.ShouldBindJSON(&req)

	token := getToken()

	data := GetUnlimitedData{}
	data.Scene = req.HospitalCode + ";" + req.DoctorPhone + ";" + req.OtherNo + ";1"
	data.Page = ""

	errcode, reply := getUnlimited(token, data)

	if errcode != 200 {
		response.FailWithDetailedCode(411, "", "accesstoken获取失败", c)
	} else {
		response.OkWithData(reply, c)
		return
	}
}

func GetUnlimitedForReport(c *gin.Context) {
	var req GetUnlimitedReq
	_ = c.ShouldBindJSON(&req)

	token := getToken()

	data := GetUnlimitedData{}
	data.Scene = req.HospitalCode + ";" + req.DoctorPhone + ";" + req.OtherNo + ";4"
	data.Page = "pages/casesDetail/casesDetail"

	errcode, reply := getUnlimited(token, data)

	if errcode != 200 {
		response.FailWithDetailedCode(411, "", "accesstoken获取失败", c)
	} else {
		response.OkWithData(reply, c)
		return
	}
}

func GetUnlimitedForSurvey(c *gin.Context) {
	var req GetUnlimitedReq
	_ = c.ShouldBindJSON(&req)

	token := getToken()

	data := GetUnlimitedData{}
	data.Scene = req.HospitalCode + ";" + req.DoctorPhone + ";" + req.OtherNo + ";2"
	//data.Page = ""
	data.Page = "doctor/questionnaire/q1"

	errcode, qrData := getUnlimited(token, data)

	if errcode != 200 {
		response.FailWithDetailedCode(411, "", "accesstoken获取失败", c)
	}

	schemeReq := GetSchemeReq{}
	schemeReq.Path = data.Page
	schemeReq.Query = data.Scene
	errcode, openLink := getScheme(token, schemeReq)

	reply := GetUnlimitedForSurveyReply{}
	reply.QrData = qrData.(string)
	reply.OpenLink = openLink

	if errcode != 200 {
		response.FailWithDetailedCode(411, "", "accesstoken获取失败", c)
	} else {
		response.OkWithData(reply, c)
		return
	}
}

func getToken() string {
	if global.GVA_CONFIG.Common.Type == "2" {
		url := "https://medical.pet-dbc.cn/mobile/getTokenForLines"

		postData := make(map[string]string)

		resp := utils.Post(url, &postData, "", 1)

		fmt.Println(resp)
		reply := new(GetTokenData)

		utils.UnserislizeJson(resp, reply)

		return reply.Data
		//return "reply.Data"
	} else {
		token := service.GetWxToken()
		if token != "" {
			return token
		}
	}

	tokenRes, err := wx.GetAccessToken(global.GVA_CONFIG.Wx.Appid, global.GVA_CONFIG.Wx.Appsecret)

	if tokenRes == nil {
		//response.FailWithDetailedCode(411, "", "accesstoken获取失败", c)
		return ""
	}
	if err != nil {
		fmt.Println("GetAccessToken", err)
		//response.FailWithDetailedCode(412, "", "accesstoken获取失败", c)
		return ""
	}

	service.CreateWxToken(tokenRes.AccessToken)

	return tokenRes.AccessToken
}

func delToken() string {
	if global.GVA_CONFIG.Common.Type == "2" {
		url := "https://medical.pet-dbc.cn/mobile/delTokenForLines"

		postData := make(map[string]string)

		resp := utils.Post(url, &postData, "", 1)

		fmt.Println(resp)
		reply := new(GetTokenData)

		utils.UnserislizeJson(resp, reply)

		return reply.Data
		//return "reply.Data"
	} else {
		service.DelWxToken()
	}

	return getToken()
}

// @Description  小程序二维码
// @Param   body     body   GetUnlimitedReq   true	 "输入项"
// @Success 200 {object} utils.ResponseData
// @router /api/v1/wxapp/get-unlimited [post]
func getUnlimited(token string, req GetUnlimitedData) (int, interface{}) {

	reply, err := wx.GetUnlimited(token, req.Scene, req.Page, 280, "0", "0", "0")

	if err != nil {
		fmt.Println("获取二维码报错：", err)
		token := delToken()
		return getUnlimited(token, req)
	}

	return 200, reply
}

func getScheme(token string, req GetSchemeReq) (int, string) {

	reply := wx.GetScheme(token, req.Path, req.Query)

	return 200, reply
}

func GetTokenForLines(c *gin.Context) {
	response.OkWithData(getToken(), c)
	return
}

func DelTokenForLines(c *gin.Context) {
	response.OkWithData(delToken(), c)
	return
}
