package models

import (
	"encoding/json"
	"fmt"
	"hongze/hongze_task/utils"
	"rdluck_tools/http"
	"rdluck_tools/orm"
	"strings"
	"time"
)

type WxToken struct {
	AccessToken string
	ExpiresIn int64
	Id int64
}

func GetWxAccessToken() (accessTokenStr string,err error) {
	o:=orm.NewOrm()
	sql:=`SELECT * FROM wx_token LIMIT 1`
	wxToken:=new(WxToken)
	err=o.Raw(sql).QueryRow(&wxToken)
	if err!=nil && err.Error()!=utils.ErrNoRow(){
		utils.FileLog.Info("Get wxToken Err:",err.Error())
		return
	}
	//Token不存在
	if wxToken == nil {
		accessToken,err:=GetWxToken()
		if err!=nil {
			return "",err
		}
		if accessToken.AccessToken!="" {
			expiresIn:=time.Now().Add(time.Duration(accessToken.ExpiresIn)*time.Second).Unix()
			addSql:="insert into wx_token (access_token,expires_in) values (?,?)"
			_,err=o.Raw(addSql,accessToken.AccessToken,expiresIn).Exec()
			accessTokenStr=accessToken.AccessToken
		}
		return accessTokenStr,err
	}else{
		//判断token是否过期
		if time.Now().Unix() > wxToken.ExpiresIn {
			accessToken,err:=GetWxToken()
			if err!=nil {
				return "",err
			}
			if accessToken.AccessToken!="" {
				expiresIn:=time.Now().Add(time.Duration(accessToken.ExpiresIn)*time.Second).Unix()
				updateSql:="update wx_token set access_token = ?,expires_in = ? "
				_,err=o.Raw(updateSql,accessToken.AccessToken,expiresIn).Exec()
				accessTokenStr=accessToken.AccessToken
			}
			return accessTokenStr,err
		}else{
			return wxToken.AccessToken,nil
		}
	}
	return
}

type WxAccessToken struct {
	AccessToken string
	ExpiresIn int
	Errcode int
	Errmsg string
}

func GetWxToken() (item *WxAccessToken,err error) {
	getUrl:="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+utils.WxAppId+"&secret="+utils.WxAppSecret
	result,err:=http.Get(getUrl)
	if err!=nil {
		utils.FileLog.Info("GetWxToken Err:",err.Error())
		return
	}
	fmt.Println("result",string(result))
	err=json.Unmarshal(result,item)
	if err!=nil {
		return
	}
	if item.Errmsg!="" {
		utils.FileLog.Info("GetWxToken fail result:%s",string(result))
	}
	return
}

type WxUsers struct {
	Total int
	Count int
	Data struct{
		Openid []string
	}
	NextOpenid string
}


func WxUsersGet() (openIdStr string) {
	accessToken,err:=GetWxAccessToken()
	if err!=nil {
		utils.FileLog.Info("GetWxAccessToken Err:%s",err.Error())
		return
	}
	url:="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken
	result,err:=http.Get(url)
	if err!=nil {
		utils.FileLog.Info("GetUser Err:",err.Error())
		return
	}
	item:=new(WxUsers)
	err=json.Unmarshal(result,&item)
	if err!=nil {
		fmt.Println("Unmarshal Err:",err.Error())
		return
	}
	openIdStr=strings.Join(item.Data.Openid,"','")
	openIdStr="'"+openIdStr+"'"
	utils.FileLog.Info("openIdStr:%s",openIdStr)
	return
}