package main

import (
	"context"
	"encoding/json"
	"fmt"
	_ "hello/routers"
	"log"
	"os"
	"strings"
	"time"

	_ "hello/grpc/gapi"
	pb "hello/grpc/gapi"

	"crypto/md5"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	jwt "github.com/dgrijalva/jwt-go"
	_ "github.com/go-sql-driver/mysql"
	"google.golang.org/grpc"
)

func init() {
	linkMysqlDataBase()
}

func linkMysqlDataBase() {
	dbuser := beego.AppConfig.String("dbuser")
	dbpassword := beego.AppConfig.String("dbpassword")
	dbhost := beego.AppConfig.String("dbhost")
	dbport := beego.AppConfig.String("dbport")
	dbname := beego.AppConfig.String("dbname")

	//注册mysql Driver
	orm.RegisterDriver("mysql", orm.DRMySQL)
	//构造conn连接
	conn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=utf8"
	//注册数据库连接
	orm.RegisterDataBase("default", "mysql", conn)

	// 注册第二个数据库
	dblogname := beego.AppConfig.String("dblogname")
	//构造conn连接
	conn2 := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dblogname + "?charset=utf8"
	//注册数据库连接
	orm.RegisterDataBase("ywt_log_db", "mysql", conn2)

	fmt.Printf("数据库ywt_center连接成功！%s\n", conn)
	fmt.Printf("数据库ywt_log连接成功！%s\n", conn2)
}

func main() {
	// linkGrpcServerTest()
	// mapTest()
	jwtTest()
	beego.Run()
}

// Claims custom token
type Claims struct {
	Appid    string `json:"appid"`    // appid
	Checksum string `json:"checksum"` // Checksum
	jwt.StandardClaims
}

func jwtTest() {
	// 创建 jwt
	body := "{\"invoice\":[{\"amount\":762.94,\"custName\":\"黎敏建\",\"invoiceCode\":\"044001600211\",\"invoiceInfo\":\"【国药控股大药房】尊敬的客户：您申请的电子发票已开具成功，请点击下载：http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=392e101b1170484f93ee6b5279f189b1\",\"invoiceNo\":\"93113800\",\"invoiceUrl\":\"http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=392e101b1170484f93ee6b5279f189b1\",\"matchId\":\"YWT-INVOICE1570672860040\",\"orderNo\":\"201910100914371503607\"},{\"amount\":410.27,\"custName\":\"杨勇彬\",\"invoiceCode\":\"044001600211\",\"invoiceInfo\":\"【国药控股大药房】尊敬的客户：您申请的电子发票已开具成功，请点击下载：http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=b55ee05232c748d1a94c616046f60825\",\"invoiceNo\":\"93113805\",\"invoiceUrl\":\"http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=b55ee05232c748d1a94c616046f60825\",\"matchId\":\"YWT-INVOICE1570677060040\",\"orderNo\":\"201910101042375134013\"},{\"amount\":492.12,\"custName\":\"丘婷\",\"invoiceCode\":\"044001600211\",\"invoiceInfo\":\"【国药控股大药房】尊敬的客户：您申请的电子发票已开具成功，请点击下载：http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=dbaa1c25e785443dbb76cb59efec2ca5\",\"invoiceNo\":\"93113799\",\"invoiceUrl\":\"http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=dbaa1c25e785443dbb76cb59efec2ca5\",\"matchId\":\"YWT-INVOICE1570672860040\",\"orderNo\":\"201910100937249333721\"},{\"amount\":227.82,\"custName\":\"卢桂珍\",\"invoiceCode\":\"044001600211\",\"invoiceInfo\":\"【国药控股大药房】尊敬的客户：您申请的电子发票已开具成功，请点击下载：http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=2f15feafd34249b78252c5f1eb847930\",\"invoiceNo\":\"93113797\",\"invoiceUrl\":\"http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=2f15feafd34249b78252c5f1eb847930\",\"matchId\":\"YWT-INVOICE1570672860040\",\"orderNo\":\"201910100845504303496\"},{\"amount\":53.5,\"custName\":\"张惠\",\"invoiceCode\":\"044001600211\",\"invoiceInfo\":\"【国药控股大药房】尊敬的客户：您申请的电子发票已开具成功，请点击下载：http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=1e906096430c477c87b80cdb53c7fbb8\",\"invoiceNo\":\"93113804\",\"invoiceUrl\":\"http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=1e906096430c477c87b80cdb53c7fbb8\",\"matchId\":\"YWT-INVOICE1570677060040\",\"orderNo\":\"201910101042226514011\"},{\"amount\":553.86,\"custName\":\"罗艳文\",\"invoiceCode\":\"044001600211\",\"invoiceInfo\":\"【国药控股大药房】尊敬的客户：您申请的电子发票已开具成功，请点击下载：http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=6522f231782e45a499a32717bd87dac4\",\"invoiceNo\":\"93113802\",\"invoiceUrl\":\"http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=6522f231782e45a499a32717bd87dac4\",\"matchId\":\"YWT-INVOICE1570677060040\",\"orderNo\":\"201910101048054304031\"},{\"amount\":2060.86,\"custName\":\"陈滋\",\"invoiceCode\":\"044001600211\",\"invoiceInfo\":\"【国药控股大药房】尊敬的客户：您申请的电子发票已开具成功，请点击下载：http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=167d23c3431843b5aa3227700d8039a1\",\"invoiceNo\":\"93113803\",\"invoiceUrl\":\"http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=167d23c3431843b5aa3227700d8039a1\",\"matchId\":\"YWT-INVOICE1570677060040\",\"orderNo\":\"201910101002385863841\"},{\"amount\":103.02,\"custName\":\"唐玲\",\"invoiceCode\":\"044001600211\",\"invoiceInfo\":\"【国药控股大药房】尊敬的客户：您申请的电子发票已开具成功，请点击下载：http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=e091ddec33824b0bbf6ccefd737686bc\",\"invoiceNo\":\"93113798\",\"invoiceUrl\":\"http://cs.ruizhi.com:8090/invoiceplatform/ruizhi/fiscal/esign/downloadPdf.do?id=e091ddec33824b0bbf6ccefd737686bc\",\"matchId\":\"YWT-INVOICE1570672860040\",\"orderNo\":\"201910091327038342613\"}]}"
	appid := "gk_druggist"
	appsecret := "gk_druggist_123456"
	token := createJwt(body, appid, appsecret)
	logs.Info("token:", token)

	result := validateToke(token, body, appid, appsecret)
	logs.Info("result:", result)

	token2 := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBpZCI6ImdrX2RydWdnaXN0IiwiY2hlY2tzdW0iOiI5OTU4MkQzMThEMURFMTRDMEQxOUU3OTFCRUI2NDU4OCIsImlhdCI6MTU3MDgwNjMyNn0.GAB_PDez1Z4uF4bb8sIoo_Br7TSgF5WH8u1d98927VY"
	result2 := validateToke(token2, body, appid, appsecret)
	logs.Info("result2:", result2)
}

// 签发token
func createJwt(body string, appid string, appsecret string) (returnToken string) {
	pl := make(jwt.MapClaims)
	pl["appid"] = appid
	md5str2 := checkSum(body)
	pl["checksum"] = md5str2

	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = pl
	tokenStr, err := token.SignedString([]byte(appsecret))
	if err != nil {
		return ""
	}
	return tokenStr
}

// 校验token
func validateToke(signedToken string, body string, appid string, appsecret string) (result bool) {
	token, err := jwt.ParseWithClaims(signedToken, &Claims{},
		func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("unexpected login method %v", token.Header["alg"])
			}
			return []byte(appsecret), nil
		})

	if err != nil {
		return false
	}

	claims, ok := token.Claims.(*Claims)
	logs.Info("Appid:", claims.Appid, "\tChecksum:", claims.Checksum, "\tValid:", token.Valid)
	if ok && token.Valid {
		return true
	}

	return false
}

// 将body进行md5计算，并转为大写，然后返回
func checkSum(body string) (sum string) {
	data := []byte(body)
	has := md5.Sum(data)
	md5str1 := fmt.Sprintf("%x", has) //将[]byte转成16进制
	md5str2 := strings.ToUpper(md5str1)
	logs.Info("----- checksum -----:", md5str2)
	return md5str2
}

func mapTest() {
	countryCapitalMap := make(map[string]string)
	/* map插入key - value对,各个国家对应的首都 */
	countryCapitalMap["France"] = "巴黎"
	countryCapitalMap["Italy"] = "罗马"
	countryCapitalMap["Japan"] = "东京"
	countryCapitalMap["India "] = "新德里"
	for k, v := range countryCapitalMap {
		fmt.Printf("%s -> %s\n", k, v)
	}
	value, err := json.Marshal(countryCapitalMap)
	if err != nil {
		fmt.Printf("err", err)
	}
	fmt.Println(string(value))
	logs.Info(string(value))
}

func sliceTest() {
	/* 创建切片 */
	numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 10}
	printSlice(numbers)
	// 遍历
	for index, num := range numbers {
		fmt.Println(index, "\t", num)
	}
	//range也可以用在map的键值对上。
	kvs := map[string]string{"a": "apple", "b": "banana"}
	for k, v := range kvs {
		fmt.Printf("%s -> %s\n", k, v)
	}
}

func printSlice(x []int) {
	fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x)
}

// ------------- grpc client start -----------------------------
// 连接grpc测试
func linkGrpcServerTest() {
	fmt.Println("-------I'm coming linkGrpcServerTest------")
	address := beego.AppConfig.String("service.agent.grpc.addr")
	// Set up a connection to the server.
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		fmt.Println("did not connect: %v", err)
	}
	defer conn.Close()
	c := pb.NewUserServiceClient(conn)

	// Contact the server and print out its response.
	userId := int32(4)
	mobile := ""
	if len(os.Args) > 1 {
		mobile = os.Args[1]
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	r, err := c.FindByUserId(ctx, &pb.UserRequest{Userid: userId,
		Phone: mobile,
	})
	if err != nil {
		fmt.Println("could not greet: %v", err)
	}
	log.Println("Greeting: %s", r.GetUser())
	userName := r.GetUser().Realname
	log.Println(userName)
}

// ------------- end grpc client -----------------------------
