package test

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"go-admin/app/admin/models"
	"go-admin/app/admin/models/kuaidi"
	orm "go-admin/common/global"
	"go-admin/logger"
	"golang.org/x/crypto/bcrypt"
	"net/url"

	//"go-admin/models/tools"
	//"os"
	"testing"
	"time"
	//"text/template"
)

func TestGoModelTemplate(t *testing.T) {
	//t1, err := template.ParseFiles("model.go.template")
	//if err != nil {
	//	t.Error(err)
	//}
	//table := tools.SysTables{}
	//table.TBName = "sys_tables"
	//tab, err := table.Get()
	//if err != nil {
	//	t.Error(err)
	//}
	//file, err := os.Create("models/" + table.PackageName + ".go")
	//if err != nil {
	//	t.Error(err)
	//}
	//defer file.Close()
	//
	//_ = t1.Execute(file, tab)
	t.Log("")

	//t1, err := template.ParseFiles("api.go.template")
	//if err != nil {
	//	t.Error(err)
	//}
	//table := tools.SysTables{}
	//table.TBName = "sys_tables"
	//tab, _ := table.Get()
	//file, err := os.Create("apis/" + table.PackageName + ".go")
	//if err != nil {
	//	t.Error(err)
	//}
	//defer file.Close()
	//
	//_ = t1.Execute(file, tab)
	//t.Log("")
}

func TestGoApiTemplate(t *testing.T) {

	GoodsStoke()
}

const storeId = 15

func GoodsStoke() {
	InitDBTest()
	//models.GameCardGoodsStock{}
	//models.GameCardGoods{}

	var goods []models.GameCardGoods
	err := DBTest.Table("game_card_goods").Where("store_id=?", storeId).Find(&goods).Error
	if err != nil {
		fmt.Println("err:", err)
	}
	goodsMap := make(map[uint64]uint32)
	goodsRentMap := make(map[uint64]uint32)
	for i, _ := range goods {
		goodsMap[goods[i].GameCardId] += 1
		if goods[i].Status == 1 {
			goodsRentMap[goods[i].GameCardId] += 1
		}
	}

	var goodsStock []models.GameCardGoodsStock
	err = DBTest.Table("game_card_goods_stock").Where("store_id=?", storeId).Find(&goodsStock).Error
	if err != nil {
		fmt.Println("err:", err)
	}
	for i, _ := range goodsStock {
		storeStock, ok := goodsMap[goodsStock[i].GameCardId]
		if !ok {
			//fmt.Println("游戏Id:")
		}
		rentStock, ok := goodsRentMap[goodsStock[i].GameCardId]

		//if goodsStock[i].StoreStock != storeStock || goodsStock[i].RentStock != rentStock {
		if goodsStock[i].RentStock != rentStock {
			fmt.Println("游戏Id:", goodsStock[i].GameCardId, goodsStock[i].StoreStock, goodsStock[i].RentStock)
			fmt.Println("游戏Id:", goodsStock[i].GameCardId, storeStock, rentStock, "真实库存")
			fmt.Println("游戏Id:库存不对", goodsStock[i].GameCardId)

			//sql := fmt.Sprintf("UPDATE game_card_goods_stock SET rent_stock=%d WHERE store_id=%d AND game_card_id=%d", rentStock, storeId, goodsStock[i].GameCardId)
			//fmt.Println("sql:", sql)
			//err := DBTest.Exec(sql).Error
			//if err != nil {
			//	fmt.Println("err:", err)
			//}
		} else {
			//fmt.Println("游戏Id:库存正确", goodsStock[i].GameCardId)
		}
	}

}

var DBTest *gorm.DB

func InitDBTest() {
	var err error
	//dialect := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
	//	"mh_pro", "fLeytnBFCRB553ab", "39.108.188.218", "3306",
	//	"mh_pro")
	dialect := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		"mh_dev", "d9qy46ONI0ZTF9eH", "112.33.14.191", "3306",
		"mh_dev")

	DBTest, err = gorm.Open("mysql", dialect)
	if err != nil {
		fmt.Println("Connect Database Error, error = ", err)
		panic(err)
	}
	DBTest.DB().SetMaxOpenConns(1000)
	DBTest.DB().SetMaxIdleConns(500)
	DBTest.DB().SetConnMaxLifetime(time.Second * 10)
	DBTest.LogMode(true)
	DBTest.SingularTable(true)
	DBTest.AutoMigrate(
		//&models.Article{},
		//&models.ArticleCollect{},
		//&models.CannibalizeStockTask{},
		//&models.CannibalizeGameCardGoods{},

		models.SysUser{},
		models.ExpireMemberSmsSend{},
	)

	if err := DBTest.DB().Ping(); err != nil {
		fmt.Println("Ping Database Fail, error = ", err)
		panic(err)
	}
	fmt.Println("DB init success")
}

func TestInitDBTest(t *testing.T) {
	InitDBTest()
}

var DBProd *gorm.DB

func InitDBProd() {
	var err error
	dialect := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		"mh_pro", "fLeytnBFCRB553ab", "39.108.188.218", "3306",
		"mh_pro")

	DBProd, err = gorm.Open("mysql", dialect)
	if err != nil {
		fmt.Println("Connect Database Error, error = ", err)
		panic(err)
	}
	DBProd.DB().SetMaxOpenConns(1000)
	DBProd.DB().SetMaxIdleConns(500)
	DBProd.DB().SetConnMaxLifetime(time.Second * 10)
	DBProd.LogMode(true)
	DBProd.SingularTable(true)
	DBProd.AutoMigrate(
		models.SysUser{},
		models.ExpireMemberSmsSend{},
	)

	if err := DBProd.DB().Ping(); err != nil {
		fmt.Println("Ping Database Fail, error = ", err)
		panic(err)
	}
	fmt.Println("DB init success")
}

func TestInitDBProd(t *testing.T) {
	InitDBProd()
}

func TestUserAddName(t *testing.T) {
	UserAddName()
}

func UserAddName() {
	InitDBProd()
	nameMap := map[uint32]string{
		5151411:  "钟林",
		59834104: "张露丹",
		32742391: "罗鹰翔",
		10548743: "罗笑谦",
		96944919: "唐朝霞",
		51846105: "蒲键发",
		5850964:  "代小艳",
		31197378: "李鑫凯",
		96658713: "杨淳",
		14680227: "赵鹏",
		65610369: "陈吉平",
		13673929: "马盛豪",
		71615842: "詹若慧",
		26580935: "刘凡瑛",
		21785997: "杨权南",
		28610013: "黎一才",
		91733893: "蔡显荣",
		22465825: "陶德源",
		25354617: "黄子健",
		44114412: "王迈",
		86443412: "张彬",
		44005620: "冯子豪",
		13541666: "吴逸欣",
		45886563: "苟浩川",
		42522553: "刘威",
		35064958: "毕杨阳",
		19324196: "胡阳",
		79850633: "何林月",
		61415201: "赵潘",
		91659241: "卢宇休",
		15243331: "刘恭德",
		97074634: "林浩斌",
		40370226: "陈剑鹏",
		49468994: "杨俊海",
		92004706: "方泽玲",
		73391379: "周靖文",
		51858559: "连志弘",
		34075903: "廖伟",
		41584397: "杨铭",
		69438798: "罗可人",
		60320897: "官西湖",
		51850341: "李锐",
		56228118: "王于滔",
		18396180: "潘梦妮",
		48739259: "张鑫淼",
		45507685: "邹骐骏",
	}
	//ids := []uint32{25257310,5151411,59834104,32742391,10548743,96944919,51846105,5850964,31197378,96658713,14680227,65610369,13673929,71615842,26580935,21785997,28610013,91733893,22465825,25354617,44114412,86443412,44005620,13541666,45886563,42522553,35064958,19324196,61415201,91659241,15243331,97074634,40370226,49468994,92004706,73391379,
	//}
	fmt.Println("nameMap:", nameMap)

	//sql := fmt.Sprintln("SELECT * FROM `user` WHERE uid IN (25257310,5151411,59834104,32742391,10548743,96944919,51846105,5850964,31197378,96658713,14680227,65610369,13673929,71615842,26580935,21785997,28610013,91733893,22465825,25354617,44114412,86443412,44005620,13541666,45886563,42522553,35064958,19324196,61415201,91659241,15243331,97074634,40370226,49468994,92004706,73391379)")
	sql := fmt.Sprintln("SELECT * FROM `user` WHERE uid IN (25257310,5151411,59834104,32742391,10548743,96944919,51846105,5850964,31197378,96658713,14680227,65610369,13673929,71615842,26580935,21785997,28610013,91733893,22465825,25354617,44114412,86443412,44005620,13541666,45886563,42522553,35064958,19324196,79850633,61415201,91659241,15243331,97074634,40370226,49468994,92004706,73391379,51858559,34075903,41584397,69438798,60320897,51850341,56228118)")
	var users []models.UserInfo
	err := DBProd.Raw(sql).Scan(&users).Error
	if err != nil {
		fmt.Println("err:", err.Error())
	}

	for i, _ := range users {
		name, ok := nameMap[users[i].Uid]
		if ok && users[i].ShopAssistantName == "" {

			sql := fmt.Sprintf("UPDATE `user` SET shop_assistant_name = '%s' WHERE uid = %d", name, users[i].Uid)
			err := DBProd.Exec(sql).Error
			if err != nil {
				fmt.Println("err:", err.Error())
			}
			fmt.Println("Name:", name)
		}
		//fmt.Println("Uid:", users[i].Uid)
		fmt.Println("Name:", users[i].ShopAssistantName)
	}
}

// 收益生效
func TestShareCardProfitEffectShareCard(t *testing.T) {
	ShareCardProfitEffectShareCard()
}

func ShareCardProfitEffectShareCard() {
	InitIODBTest()
	orm.Eloquent = IODBTest
	models.ShareCardProfitEffectCard()
}

// 发放游戏积分
func TestShareCardProvideVmUser(t *testing.T) {
	ShareCardProvideVmUser()
}

func ShareCardProvideVmUser() {
	//InitDBTest()
	InitIODBTest()
	orm.Eloquent = IODBTest

	models.ShareCardProfitEffectCard()
	models.ShareCardProvideVm()
}

// 发放用户积分
func TestShareCardUserVmRecordCreate(t *testing.T) {
	ShareCardUserVmRecordCreate()
}

func ShareCardUserVmRecordCreate() {
	InitIODBTest()
	orm.Eloquent = IODBTest

	models.ShareCardUserVmRecord()
}

// 分配用户收回卡
func TestShareCardRetrieveCardSetCard(t *testing.T) {
	//ShareCardRetrieveCardSetCard()

	InitIODBTest()
	orm.Eloquent = IODBTest
	models.ShareCardRetrieveCardSetStockCardCron()
}

// 订阅 推送物流状态
func TestSubscribeExpressState(t *testing.T) {
	//kuaidi.SubscribeExpressState("shentong", "777081382580032")
	kuaidi.SubscribeExpressState("yunda", "462325443141899")
}

func TestKuaiDiStatePush(t *testing.T) {

	body := "param=%7B%22status%22%3A%22polling%22%2C%22message%22%3A%22%22%2C%22lastResult%22%3A%7B%22message%22%3A%22ok%22%2C%22nu%22%3A%22YT6074326614455%22%2C%22ischeck%22%3A%220%22%2C%22com%22%3A%22yuantong%22%2C%22status%22%3A%22200%22%2C%22state%22%3A0%2C%22data%22%3A%5B%7B%22time%22%3A%222022-01-25+15%3A19%3A10%22%2C%22context%22%3A%22%E3%80%90%E8%B4%B5%E9%98%B3%E5%B8%82%E3%80%91%E5%B7%B2%E5%88%B0%E8%BE%BE+%E8%B4%B5%E5%B7%9E%E8%B4%B5%E9%98%B3%E5%88%86%E6%8B%A8%E4%BA%A4%E4%BB%98%E4%B8%AD%E5%BF%83%22%2C%22ftime%22%3A%222022-01-25+15%3A19%3A10%22%2C%22areaCode%22%3A%22CN520100000000%22%2C%22areaName%22%3A%22%E8%B4%B5%E5%B7%9E%2C%E8%B4%B5%E9%98%B3%E5%B8%82%22%2C%22status%22%3A%22%E5%9C%A8%E9%80%94%22%2C%22location%22%3Anull%2C%22areaCenter%22%3Anull%2C%22areaPinYin%22%3Anull%2C%22statusCode%22%3Anull%7D%2C%7B%22time%22%3A%222022-01-24+03%3A27%3A18%22%2C%22context%22%3A%22%E3%80%90%E6%88%90%E9%83%BD%E5%B8%82%E3%80%91%E5%B7%B2%E7%A6%BB%E5%BC%80+%E5%9B%9B%E5%B7%9D%E6%88%90%E9%83%BD%E5%88%86%E6%8B%A8%E4%BA%A4%E4%BB%98%E4%B8%AD%E5%BF%83%EF%BC%9B%E5%8F%91%E5%BE%80+%E8%B4%B5%E9%98%B3%E5%8C%97%E5%9C%B0%E5%8C%BA%E5%8C%85%22%2C%22ftime%22%3A%222022-01-24+03%3A27%3A18%22%2C%22areaCode%22%3A%22CN510100000000%22%2C%22areaName%22%3A%22%E5%9B%9B%E5%B7%9D%2C%E6%88%90%E9%83%BD%E5%B8%82%22%2C%22status%22%3A%22%E5%9C%A8%E9%80%94%22%2C%22location%22%3Anull%2C%22areaCenter%22%3Anull%2C%22areaPinYin%22%3Anull%2C%22statusCode%22%3Anull%7D%2C%7B%22time%22%3A%222022-01-24+03%3A23%3A02%22%2C%22context%22%3A%22%E3%80%90%E6%88%90%E9%83%BD%E5%B8%82%E3%80%91%E5%B7%B2%E5%88%B0%E8%BE%BE+%E5%9B%9B%E5%B7%9D%E6%88%90%E9%83%BD%E5%88%86%E6%8B%A8%E4%BA%A4%E4%BB%98%E4%B8%AD%E5%BF%83%22%2C%22ftime%22%3A%222022-01-24+03%3A23%3A02%22%2C%22areaCode%22%3A%22CN510100000000%22%2C%22areaName%22%3A%22%E5%9B%9B%E5%B7%9D%2C%E6%88%90%E9%83%BD%E5%B8%82%22%2C%22status%22%3A%22%E5%9C%A8%E9%80%94%22%2C%22location%22%3Anull%2C%22areaCenter%22%3Anull%2C%22areaPinYin%22%3Anull%2C%22statusCode%22%3Anull%7D%2C%7B%22time%22%3A%222022-01-23+15%3A46%3A17%22%2C%22context%22%3A%22%E3%80%90%E6%88%90%E9%83%BD%E5%B8%82%E3%80%91%E5%9B%9B%E5%B7%9D%E6%88%90%E9%83%BD%E6%96%B0%E9%83%BD%E5%8C%BA%E5%A4%A9%E6%96%B0%E5%85%AC%E5%8F%B8-%E6%93%8D%E4%BD%9C%E9%83%A8%EF%BC%88135****1234%EF%BC%89+%E5%B7%B2%E6%8F%BD%E6%94%B6%22%2C%22ftime%22%3A%222022-01-23+15%3A46%3A17%22%2C%22areaCode%22%3A%22CN510114000000%22%2C%22areaName%22%3A%22%E5%9B%9B%E5%B7%9D%2C%E6%88%90%E9%83%BD%E5%B8%82%2C%E6%96%B0%E9%83%BD%E5%8C%BA%22%2C%22status%22%3A%22%E6%8F%BD%E6%94%B6%22%2C%22location%22%3Anull%2C%22areaCenter%22%3Anull%2C%22areaPinYin%22%3Anull%2C%22statusCode%22%3Anull%7D%5D%2C%22loop%22%3Afalse%7D%7D"

	//allReq := new(url.Values)

	//url.Parse(body)

	//unescape, err := url.QueryUnescape(body)
	//if err != nil {
	//	logger.Error("err:", err)
	//}

	unescape, err := url.ParseQuery(body)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
	}
	//unescapeJson, _ := json.Marshal(unescape)

	paramJson := unescape.Get("param")

	fmt.Println("unescape:", unescape)
	//fmt.Println("state:", unescape.Get("state"))

	fmt.Println("unescapeJson:", string(paramJson))
}

func TestMapCount(t *testing.T) {

	countMap := make(map[uint32]uint32)
	countMap[100] = 100
	countMap[101] = 101
	AddMap(&countMap)

	for k, v := range countMap {
		fmt.Println("k:", k, v)
	}
}

func AddMap(count *map[uint32]uint32) {
	for k, v := range *count {
		if k == 100 {
			(*count)[k] = v - 17
		}
	}

}

func TestTimeZeroData(t *testing.T) {
	InitIODBTest()
	orm.Eloquent = IODBTest
	//models.ShareCardRetrieveCard{}
	err := orm.Eloquent.Table("share_card_retrieve_card").Where("id=?", 204).Updates(map[string]interface{}{
		//"state": RetrieveStateSentCard,
		//"state": retrieveState,
		"receipt_time": time.Time{},
	}).Error
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
	}
	//NewShareCardRetrieveCardQuerySet(DB).IDEq(189).GetUpdater().SetStoreId()

}

func TestGoodsPutDownAway(t *testing.T) {
	InitDBTest()
	orm.Eloquent = IODBTest
	models.GoodsPutDownAway()
}

type SysCasbinRule struct {
	PType string `json:"p_type" gorm:"size:100;"`
	V0    string `json:"v0" gorm:"size:100;"`
	V1    string `json:"v1" gorm:"size:100;"`
	V2    string `json:"v2" gorm:"size:100;"`
	V3    string `json:"v3" gorm:"size:100;"`
	V4    string `json:"v4" gorm:"size:100;"`
	V5    string `json:"v5" gorm:"size:100;"`
}

func TestUpdateSysMute(t *testing.T) {
	InitDBTest()
	var mus []models.Menu
	err := DBTest.Table("sys_menu").Where("menu_id>?", 714).Where("path!=''").Find(&mus).Error
	if err != nil {
		fmt.Println("err:", err)
	}
	for i, _ := range mus {
		rule := &SysCasbinRule{
			PType: "p",
			V0:    "admin",
			V1:    mus[i].Path,
			V2:    "POST",
			V3:    "",
			V4:    "",
			V5:    "",
		}
		err = DBTest.Create(rule).Error
		if err != nil {
			fmt.Println("err:", err)
		}
	}
}

func TestUpdateDe(t *testing.T) {
	InitDBTest()
}

func TestUpdateStorePassWd(t *testing.T) {
	InitIODBPro()
	orm.Eloquent = IODBPro
	list := []string{"super-admin", "super-admin-2",
		"admin", "admin-2", "cw-deovo", "dz-swt", "dy-swt", "dz-spw", "dy-spw", "dz-sgd", "dy-sgd", "dz-shb", "dy-shb",
		"dz-cyt", "dy-cyt", "dz-cut", "dy-cut", "dz-cbt", "dy-cbt", "dz-cjt", "dy-cjt", "dz-ckw", "dy-ckw", "dz-cst",
		"dy-cst", "dz-slw", "dy-slw"}

	//passes := []string{"uM4rUKdm0i", "R4l9zrQC2n", "r0rSOWezr8", "McA2ydvGnT", "je3KvHkSCI", "vVLMc0nR3m", "lUfhGmP10G", "GTybJ7tMyR", "VQpGubl5pO", "Ev2N50vFrF", "0KNpLHxoi1", "WdO1Rv8FId", "oGRNkv98Vt", "73N0v2jKaJ", "2EAaYoJ7JB", "1ttf3yHpqE", "oo4JfwHtPi", "G4ca7aePHP", "sG9Yc4BzTS", "92mUaxtk0S", "nhZ7ri6JCx", "Ap53rjKH4x", "zei1NlyyP1", "TKoaciae49", "NeB1BxkxGN", "oNeOaetr3G", "W6Eg1095jP"}
	passes := []string{"o5wl76ogps", "9041rqb2sl", "fhn07rxz1n", "3ytu0o9nx3", "r2n6lgukoc", "5k2js8zz3k", "1z0vivh5kh", "oi8jolwx7q", "7evejzqecf", "kj2myxxshm", "m2vvyuwuzf", "s3abpjb5q2", "jw6wauitze", "80ansm6p72", "2ek34nmjf1", "fd3xqrtl36", "qubxi495tn", "tny44szjy7", "zwfra32edd", "3ekv24oo1n", "90al6cqwox", "bv67e4pmr6", "hslcf2iqlq", "kgyh5hssqq", "3r6fsoe5gl", "rb7bjktirg", "w1crto37r6"}
	for i, _ := range list {
		var sysUsers models.SysUser
		err := orm.Eloquent.Table("sys_user").Where("username=?", list[i]).Find(&sysUsers).Error
		if err != nil {
			logger.Error("find sys users err:", logger.Field("err", err))
		}

		fmt.Println("list:", list[i], " ", passes[i])
		var hash []byte
		if hash, err = bcrypt.GenerateFromPassword([]byte(passes[i]), bcrypt.DefaultCost); err != nil {
			return
		}

		fmt.Println("sysUsers:", sysUsers.PassWord.Password)
		fmt.Println("hash:", string(hash))
		//err = orm.Eloquent.Table("sys_user").Where("user_id=?", sysUsers[i].UserId).Update("password", string(hash)).Error
		//if err != nil {
		//	logger.Error("update err:", err)
		//}
	}
}

func TestUpdateStorePassWdTest(t *testing.T) {
	InitIODBTest()
	orm.Eloquent = IODBTest
	var sysUsers []models.SysUser
	err := orm.Eloquent.Debug().Table("sys_user").Where("username IN (?)", []string{"wxjm"}).Find(&sysUsers).Error
	if err != nil {
		logger.Error("find sys users err:", logger.Field("err", err))
	}
	passes := []string{"JlPP2ZnAT1"}
	for i, _ := range sysUsers {
		//pwd := models.SysUserPwd{
		//	OldPassword: sysUsers[i].Password,
		//	NewPassword: passes[i],
		//}

		//sysuser := models.SysUser{}
		//sysuser.UserId = sysUsers[i].UserId
		//sysuser.SetPwd(pwd)
		var hash []byte
		if hash, err = bcrypt.GenerateFromPassword([]byte(passes[i]), bcrypt.DefaultCost); err != nil {
			return
		}

		fmt.Println("sysUsers:", sysUsers[i].PassWord.Password)
		fmt.Println("hash:", string(hash))

		err = orm.Eloquent.Table("sys_user").Where("user_id=?", sysUsers[i].UserId).Update("password", string(hash)).Error
		if err != nil {
			logger.Error("update err:", logger.Field("err", err))
		}
	}
}

func TestUpdateExpireMemberLevel(t *testing.T) {
	fmt.Println("test UpdateExpireMemberLevel start")
	InitIODBTest()
	orm.Eloquent = IODBTest
	models.UpdateExpireMemberLevel()
	fmt.Println("test UpdateExpireMemberLevel end")
}

func TestUpdateExpireUserVm(t *testing.T) {
	fmt.Println("test UpdateExpireMemberLevel start")
	InitIODBTest()
	orm.Eloquent = IODBTest
	models.UpdateExpireUserVm()
	fmt.Println("test UpdateExpireMemberLevel end")
}
