ActiveCodeController.go 26.4 KB
Newer Older
Ford committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
package controllers

import (
	"WorldEpcho/src/config"
	database "WorldEpcho/src/datasource"
	"WorldEpcho/src/models"
	"WorldEpcho/src/service"
	"WorldEpcho/src/utils"
	"encoding/json"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// CreateActiveCode 创建一次性用户激活码
func CreateActiveCode(c *gin.Context) {
	/*
	   判断用户是否登录
	*/
	userID, isLogin := service.IsUserLoggedIn(c)
	if !isLogin {
		log.Println("用户未登录")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
		return
	}
	//判断用户的权限level是否小于5
	level, err1 := models.GetUserLevel(userID)
	if err1 != nil {
		log.Println("查询用户权限出错")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询用户权限出错"})
		return
	}
	if level > 5 {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户权限不足"})
		return
	}
	// 激活码信息备注
	remark := c.PostForm("remark")

	//设置时长,判断时长是否超过一个月
	durationHours := c.PostForm("duration_hours")
	durationH, err := strconv.Atoi(durationHours)
	if err != nil {
		log.Println("时长类型转换失败")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "时长类型转换失败"})
		return
	}
	// 定义一个月的时间间隔
	oneYear := time.Hour * 24 * 365

	// 判断时长是否超过一年
	if float64(durationH) > oneYear.Hours() {
		log.Println("时长超过一年")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "时长不能超过一年"})
		return
	}

	// 时长未超过一个月
	log.Println("时长未超过一年")

	apps := c.PostForm("apps")
	/*
	  AppsArr := []string{}
	  AppsArr = append(AppsArr, apps)
	*/

	AppsArr := []int64{}
	// 分割字符串,得到单独的数值字符串
	appsSplit := strings.Split(apps, ",")
	for _, appStr := range appsSplit {
		// 将字符串转换为 int64 类型
		appInt, err := strconv.ParseInt(appStr, 10, 64)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "应用id转换出错"})
			//continue
			return
		}
		// 将转换后的数值添加到数组
		AppsArr = append(AppsArr, appInt)
	}
	appData := c.PostForm("app_data")

	//开启事务
	session := database.Engine.NewSession()
	defer session.Close() //延迟关闭session
	err2 := session.Begin()
	if err2 != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "开启事务失败!"})
		fmt.Println("开启事务失败")
		return
	}

	//生成激活码
	var code string
	code = utils.GenerateActivationCode(userID)

	exist, _, err := models.GetActivationCode_Tx(session, code)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询激活码出错"})
		return
	}
	if exist {
		code = utils.GenerateActivationCode(userID)
	}
	acticeCode := &models.ActivationCode{
		ActiveCode:    code,
		CreatorId:     userID,
		ActivateTime:  0,
		ExpireTime:    0,
		DurationHours: durationH,
		DefaultApps:   AppsArr,
		AppData:       appData,
		Remark:        remark,
	}
	monthLimitAmount := c.PostForm("month_limit_amount")
	if monthLimitAmount != "" {
		month_limit_amount, err := strconv.ParseInt(monthLimitAmount, 10, 64)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "灵感月限度额类型转换出错"})
			//continue
			return
		}
		acticeCode.MonthLimitAmount = month_limit_amount
	}
	// 初始灵感额度
	initialInspiration := c.PostForm("initial_inspiration")
	if initialInspiration != "" {
		initial_inspiration, err := strconv.ParseInt(initialInspiration, 10, 64)

		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "初始灵感额度类型转换出错"})
			//continue
			return
		}
		acticeCode.InitialInspiration = initial_inspiration
	}

	err = models.InsertActivationCode(session, acticeCode)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "创建激活码失败"})
		return
	}

	//提交事务
	err = session.Commit()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "创建激活码失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 1, "message": "创建激活码成功"})

}

//查询激活码
func GetActivationCode(c *gin.Context) {
	/*
	   判断用户是否登录
	*/
	userID, isLogin := service.IsUserLoggedIn(c)
	if !isLogin {
		log.Println("用户未登录")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
		return
	}
	level, err1 := models.GetUserLevel(userID)
	if err1 != nil {
		log.Println("查询用户权限出错")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询用户权限出错"})
		return
	}
	if level > 5 {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户权限不足"})
		return
	}
	_, activationCodes, err := models.GetActivationCodesByCreator(userID)
	if err != nil {
		if err.Error() == "激活码不存在" {
			log.Println("根据创建者id,查询激活码不存在")
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "激活码不存在"})

		} else {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询激活码出错"})
			return
		}
	}

	response := gin.H{
		"code":        1,
		"message":     "激活码查询成功",
		"activeCodes": activationCodes,
	}
	// 序列化响应数据为 JSON 字符串
	/*	jsonData, err := json.Marshal(response)
		if err != nil {
			// 处理序列化错误
			fmt.Println("序列化 JSON 数据出错:", err)
			return
		}
		fmt.Println(config.ColorPurple, string(jsonData), config.ColorReset)*/

	c.JSON(http.StatusOK, response)

}

//为激活码续时间
func ExtendActivationCodeTime(c *gin.Context) {
	/*
	   判断用户是否登录
	*/
	_, isLogin := service.IsUserLoggedIn(c)
	if !isLogin {
		log.Println("用户未登录")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
		return
	}
	//激活码
	activeCode := c.PostForm("active_code")
	if activeCode == "" {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "激活码不能为空!"})
		return
	}
	durationHours := c.PostForm("duration_hours")
	durationH, err := strconv.Atoi(durationHours)
	if err != nil {
		log.Println("时长类型转换失败")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "时长类型转换失败"})
		return
	}

	//开启事务
	session := database.Engine.NewSession()
	defer session.Close() //延迟关闭session
	err1 := session.Begin()
	if err1 != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "开启事务失败!"})
		fmt.Println("开启事务失败")
		return
	}
	//查询激活码是否存在,存在续时间
	exist, activationCode, err := models.GetActivationCode_Tx(session, activeCode)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询激活码出错"})
		return
	}
	//设置时长,判断时长是否超过一个月
	// 定义一个月的时间间隔
	oneYear := time.Hour * 24 * 365
	// 判断时长是否超过一个月
	if float64(durationH) > oneYear.Hours() {
		log.Println("时长超过一年")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "时长不能超过一年"})
		return
	}

	if exist {

		// 判断激活码是否激活
		if activationCode.ActivateTime > 0 {
			activationCode.DurationHours = (activationCode.DurationHours + durationH)
			if activationCode.DurationHours <= 0 {
				activationCode.DurationHours = 1
				err = models.UpdateActivationCode(session, activationCode)
				if err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 0, "message": "更新激活码失败"})
					fmt.Println("更新激活码失败!")
					return
				}
			} else {
				// 判断时长是否超过一个月
				/*if float64(activationCode.DurationHours) > oneYear.Hours() {
					log.Println("时长超过一个月")
					c.JSON(http.StatusOK, gin.H{"code": 0, "message": "时长不能超过一个月"})
					return
				}
				*/
				durationSeconds := activationCode.DurationHours * 3600
				expireTimeUnix := activationCode.ActivateTime + int64(durationSeconds)
				//过期时间赋值
				activationCode.ExpireTime = expireTimeUnix
				err = models.UpdateActivationCode(session, activationCode)
				if err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 0, "message": "更新激活码失败"})
					fmt.Println("更新激活码失败!")
					return
				}
			}

		} else {
			// 未激活续时间
			activationCode.DurationHours = (activationCode.DurationHours + durationH)
			if activationCode.DurationHours <= 0 {
				activationCode.DurationHours = 1
				err = models.UpdateActivationCode(session, activationCode)
				if err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 0, "message": "更新激活码失败"})
					fmt.Println("更新激活码失败!")
					return
				}
			} else {
				// 判断时长是否超过一个月
				/*	if float64(activationCode.DurationHours) > oneYear.Hours() {
					log.Println("时长超过一个月")
					c.JSON(http.StatusOK, gin.H{"code": 0, "message": "时长不能超过一个月"})
					return
				}*/

				err = models.UpdateActivationCode(session, activationCode)
				if err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 0, "message": "更新激活码失败"})
					fmt.Println("更新激活码失败!")
					return
				}
			}

		}
	}
	//提交事务
	err = session.Commit()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "为激活码续时长失败"})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{"code": 1, "message": "为激活码续时长成功!"})
	}

}

// 修改激活码
func UpdateActiveCode(c *gin.Context) {
	/*
	   判断用户是否登录
	*/
	_, isLogin := service.IsUserLoggedIn(c)
	if !isLogin {
		log.Println("用户未登录")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
		return
	}
	//激活码
	activeCode := c.PostForm("active_code")
	if activeCode == "" {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "激活码不能为空!"})
		return
	}
	//获取激活码备注信息
	remark := c.PostForm("remark")

	//开启事务
	session := database.Engine.NewSession()
	defer session.Close() //延迟关闭session
	err := session.Begin()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "开启事务失败!"})
		fmt.Println("开启事务失败")
		return
	}
	//查询激活码是否存在,存在续时间
	exist, activationCode, err := models.GetActivationCode_Tx(session, activeCode)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询激活码出错"})
		return
	}
	if !exist {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "修改的激活码不存在!"})
		fmt.Println("修改的激活码不存在")
		return
	}
	apps := c.PostForm("apps")
	appData := c.PostForm("appData")
	AppsArr := []int64{}
	//existingApps := make(map[int64]bool) // 使用map来记录已存在的应用

	// 先将已存在的应用加入map中
	/*	for _, app := range activationCode.DefaultApps {
		existingApps[app] = true
	}*/

	// 分割字符串,得到单独的数值字符串
	appsSplit := strings.Split(apps, ",")
	fmt.Println("修改默认应用为: appsSplit => ", appsSplit)
	// 修改默认应用为, appsSplit =>  [1 6 9 11] ,激活码原来的默认应用是[1,6,9,11,12],修改后去掉了12

	for _, appStr := range appsSplit {
		// 将字符串转换为 int64 类型
		appInt, err := strconv.ParseInt(appStr, 10, 64)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "应用id转换出错"})
			return
		}
		// 检查应用是否已经在激活码的默认应用中
		/*	if _, exists := existingApps[appInt]; !exists {
				// 仅当应用ID不在现有的默认应用列表中时才添加
				AppsArr = append(AppsArr, appInt)
			}
		*/
		AppsArr = append(AppsArr, appInt)
	}

	fmt.Println("AppsArr =>", AppsArr)
	// 添加新的应用到激活码的默认应用数组
	/*	if len(AppsArr) > 0 {
			activationCode.DefaultApps = append(activationCode.DefaultApps, AppsArr...)
		}
	*/
	if len(AppsArr) > 0 {
		activationCode.DefaultApps = AppsArr
	}
	if appData != "" {
		activationCode.AppData = appData
		fmt.Println(config.ColorBlue, "修改激活码,用户应用数据, appData ==> ", appData, config.ColorReset)
	}

	// 月限额
	var initial_inspiration int64
	var month_limit_amount int64
	//var monthLimitAmountDiff int64
	var initialInspirationDiff int64

	monthLimitAmount := c.PostForm("month_limit_amount")
	if monthLimitAmount != "" {
		month_limit_amount, err = strconv.ParseInt(monthLimitAmount, 10, 64)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "灵感月限度额类型转换出错"})
			//continue
			return
		}
		//计算更新差额: 新值减去旧值
		//monthLimitAmountDiff = month_limit_amount - activationCode.MonthLimitAmount

		//更新值
		activationCode.MonthLimitAmount = month_limit_amount

	}
	// 初始灵感额度

	initialInspiration := c.PostForm("initial_inspiration")
	if initialInspiration != "" {
		initial_inspiration, err = strconv.ParseInt(initialInspiration, 10, 64)

		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "初始灵感额度类型转换出错"})
			//continue
			return
		}

		// 计算更新的差额:新值-旧值
		initialInspirationDiff = initial_inspiration - activationCode.InitialInspiration
		// 更新值
		activationCode.InitialInspiration = initial_inspiration
	}

	activationCode.Remark = remark
	fmt.Println(config.ColorYellow, "更新激活码操作: 新的激活码的默认应用apps: => ", activationCode.DefaultApps, "新的激活码的默认应用对应的应用数据: => ", activationCode.AppData, config.ColorReset)
	err = models.UpdateActivationCode(session, activationCode)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "修改激活码的备注信息出错!"})
		fmt.Println("修改激活码的备注信息出错")
		return
	}

	// 判断激活码是否已经有用户使用了
	if activationCode.UseingId != 0 { //激活码的使用者ID不等于0表示激活码已经激活,已经有用户在使用了
		/*  把新加的默认应用添加到应用的参与者数组中*/
		err = models.AddParticipants(session, AppsArr, activationCode.UseingId)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "添加新用户到应用参与者出错"})
			fmt.Println("添加新用户到应用参与者出错!")
			return
		}

		/* 根据应用id和userid,插入用户应用数据*/
		fmt.Println(config.ColorPurple, "默认应用activationCode ===> ", activationCode, config.ColorReset)
		err = CreateUserAppData(session, activationCode.DefaultApps, activationCode.UseingId, activationCode.ActiveCode)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "根据应用id和用户id,插入用户应用数据出错"})
			fmt.Println("err ===> ", err.Error())
			fmt.Println("根据应用id和用户id,插入用户应用数据出错!")
			return
		}

	}

	// 更新用户表里的灵感初始值,以及用户灵感消耗汇总表
	if activationCode.UseingId != 0 { //激活码已经有用户在使用了
		existUser, user, err := models.GetUserExistByID_Tx(session, activationCode.UseingId)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "根据激活码的使用者ID查询用户出错!"})
			fmt.Println("根据激活码的使用者ID查询用户出错")
			return
		}
		if existUser {
			if initial_inspiration != 0 {
				user.InitialInspiration = initial_inspiration
				_, err := models.UpdateUser_Tx(session, user)
				if err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 0, "message": "更新激活码的使用者灵感初始值出错!"})
					fmt.Println("更新激活码的使用者灵感初始值出错")
					return
				}
			}
		}
		//这里根据用户ID查询用户灵感消耗汇总记录
		usageLog, usageLogExist, err := models.GetUserSummaryInspirationUsageLog(activationCode.UseingId)
		if err != nil {
			log.Printf("获取用户灵感消耗汇总记录出错: %v", err)
			return
		}
		if usageLog != nil && usageLogExist {
			// 用户的月限额,加上更新的差额
			usageLog.MonthLimitAmount = month_limit_amount
			// 初始灵感值,加上更新的差额
			usageLog.InitialInspiration = usageLog.InitialInspiration + initialInspirationDiff
			_, err := models.UpdateLog_Tx(session, usageLog)
			if err != nil {
				log.Printf("更新用户灵感消耗汇总记录出错: %v", err)
				return

			}
		}
	}

	//提交事务
	err = session.Commit()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "修改激活码的备注信息失败"})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{"code": 1, "message": "修改激活码的备注信息成功"})
		fmt.Println("修改激活码的备注信息成功")
	}

}

// 批量创建激活码
func BatchCreateActiveCode(c *gin.Context) {
	/*
	   判断用户是否登录
	*/
	userID, isLogin := service.IsUserLoggedIn(c)
	if !isLogin {
		log.Println("用户未登录")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
		return
	}
	//判断用户的权限level是否小于5
	level, err1 := models.GetUserLevel(userID)
	if err1 != nil {
		log.Println("查询用户权限出错")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询用户权限出错"})
		return
	}
	if level > 5 {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户权限不足"})
		return
	}
	// 激活码信息备注
	remark := c.PostForm("remark")
	// 批量创建激活码的个数
	activeCodeNums := c.PostForm("activeCodeNums")
	// 将 activeCodeNums 转换为 int 类型
	activeCodeNumsInt, err := strconv.Atoi(activeCodeNums)
	if err != nil {
		// 转换失败,处理错误
		fmt.Println("转换失败:", err)
	} else {
		// 转换成功,activeCodeNumsInt 现在是 int 类型
		fmt.Println("转换成功:", activeCodeNumsInt)
	}

	//设置时长,判断时长是否超过一个月
	durationHours := c.PostForm("duration_hours")
	durationH, err := strconv.Atoi(durationHours)
	if err != nil {
		log.Println("时长类型转换失败")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "时长类型转换失败"})
		return
	}
	// 定义一个月的时间间隔
	oneYear := time.Hour * 24 * 365

	// 判断时长是否超过一年
	if float64(durationH) > oneYear.Hours() {
		log.Println("时长超过一年")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "时长不能超过一年"})
		return
	}

	// 时长未超过一个月
	log.Println("时长未超过一年")

	apps := c.PostForm("apps")
	/*
	  AppsArr := []string{}
	  AppsArr = append(AppsArr, apps)
	*/

	AppsArr := []int64{}
	// 分割字符串,得到单独的数值字符串
	appsSplit := strings.Split(apps, ",")
	for _, appStr := range appsSplit {
		// 将字符串转换为 int64 类型
		appInt, err := strconv.ParseInt(appStr, 10, 64)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "应用id转换出错"})
			//continue
			return
		}
		// 将转换后的数值添加到数组
		AppsArr = append(AppsArr, appInt)
	}
	appData := c.PostForm("app_data")

	//开启事务
	session := database.Engine.NewSession()
	defer session.Close() //延迟关闭session
	err2 := session.Begin()
	if err2 != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "开启事务失败!"})
		fmt.Println("开启事务失败")
		return
	}
	// 灵感月限额
	monthLimitAmount := c.PostForm("month_limit_amount")
	// 初始灵感额度
	initialInspiration := c.PostForm("initial_inspiration")

	// 循环生成激活码
	for i := 0; i < activeCodeNumsInt; i++ {

		var code string
		code = utils.GenerateActivationCode(userID)

		exist, _, err := models.GetActivationCode_Tx(session, code)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询激活码出错"})
			return
		}
		if exist {
			code = utils.GenerateActivationCode(userID)
		}

		activeCode := &models.ActivationCode{
			ActiveCode:    code,
			CreatorId:     userID,
			ActivateTime:  0,
			ExpireTime:    0,
			DurationHours: durationH,
			DefaultApps:   AppsArr,
			AppData:       appData,
			Remark:        remark,
		}
		if monthLimitAmount != "" {
			month_limit_amount, err := strconv.ParseInt(monthLimitAmount, 10, 64)
			if err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 0, "message": "灵感月限度额类型转换出错"})
				//continue
				return
			}
			activeCode.MonthLimitAmount = month_limit_amount
		}
		if initialInspiration != "" {
			initial_inspiration, err := strconv.ParseInt(initialInspiration, 10, 64)

			if err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 0, "message": "初始灵感额度类型转换出错"})
				//continue
				return
			}
			activeCode.InitialInspiration = initial_inspiration
		}

		err = models.InsertActivationCode(session, activeCode)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "创建激活码失败"})
			return
		}
	}

	//提交事务
	err = session.Commit()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "创建激活码失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 1, "message": "批量创建激活码成功! "})

}

// 用户查询月限额
func GetUserAvailableMonthlyLimit(c *gin.Context) {
	/*
	   判断用户是否登录
	*/
	uid, isLogin := service.IsUserLoggedIn(c)
	if !isLogin {
		log.Println("用户未登录")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
		return
	}
	// 定义一个字符串保存月限额字符串
	var availableMonthlyLimitAmountStr string
	availableMonthlyLimitAmount, exist_active, err := models.GetUserAvailableMonthlyLimit(uid)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "获取当前用户可用月限额数量出错"})
		fmt.Println("获取当前用户可用月限额数量出错")
		return
	}

	if !exist_active {
		availableMonthlyLimitAmountStr = "null"
		fmt.Println("无该用户月限额记录")
	} else {
		availableMonthlyLimitAmountStr = utils.Strval(availableMonthlyLimitAmount)
	}

	exist, code, err := models.GetActivationCodeByUserID(uid)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "根据用户ID查询该用户绑定的激活码出错!"})
		fmt.Println("根据用户ID查询该用户绑定的激活码出错")
	}

	//该用户绑定的激活码过期时间
	var expireTime string
	if exist {
		// 将秒时间戳转换为时间值
		t := time.Unix(code.ExpireTime, 0)
		expireTime = utils.GetNormalTimeString(t)
	} else {
		expireTime = "未绑定激活码"
	}
	c.JSON(http.StatusOK, gin.H{
		"code":                        1,
		"message":                     "获取当前用户可用月限额数和激活码过期时间成功!",
		"availableMonthlyLimitAmount": availableMonthlyLimitAmountStr,
		"ActivateCodeExpirationTime":  expireTime,
	})

}

// 定义路由处理函数
func UploadActivationCodes(c *gin.Context) {
	var jsonMap map[string]int64 // 创建一个map接收JSON数据
	if err := c.ShouldBindJSON(&jsonMap); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	var durationH int
	for code, expiryTime := range jsonMap {

		if expiryTime == 9999999999 {
			durationH = 0
		}
		var activeTime int64
		if expiryTime != 9999999999 {
			durationH = 6
			activeTime = expiryTime - (6 * 3600)

		}
		if expiryTime == 0 {
			durationH = 6
			activeTime = 0
		}
		activationCode := models.ActivationCode{
			ActiveCode:    code,
			CreatorId:     1,
			ActivateTime:  activeTime,
			ExpireTime:    expiryTime,
			DurationHours: durationH,
		}

		// 插入数据
		_, err := database.Engine.Insert(&activationCode)
		if err != nil {
			c.JSON(500, gin.H{"error": err.Error()})
			return
		}
	}

	c.JSON(200, gin.H{"message": "Activation codes successfully uploaded."})
}

func GetActivationCodeInfo(c *gin.Context) {
	/*
	   判断用户是否登录
	*/
	/*	_, isLogin := service.IsUserLoggedIn(c)
		if !isLogin {
			log.Println("用户未登录")
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
			return
		}*/
	//激活码
	activeCode := c.PostForm("active_code")
	if activeCode == "" {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "激活码不能为空!"})
		return
	}
	//开启事务
	session := database.Engine.NewSession()
	defer session.Close() //延迟关闭session
	err1 := session.Begin()
	if err1 != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "开启事务失败!"})
		fmt.Println("开启事务失败")
		return
	}

	_, code, err := models.GetActivationCode_Tx(session, activeCode)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询激活码出错!"})
		return
	}
	//提交事务
	err = session.Commit()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "为激活码续时长失败"})
		return
	}
	response := gin.H{
		"code":        1,
		"message":     "激活码查询成功",
		"activeCodes": code,
	}
	// 序列化响应数据为 JSON 字符串
	jsonData, err := json.Marshal(response)
	if err != nil {
		// 处理序列化错误
		fmt.Println("序列化 JSON 数据出错:", err)
		return
	}
	fmt.Println(config.ColorPurple, string(jsonData), config.ColorReset)

	c.JSON(http.StatusOK, response)

}

//查询激活码信息并模拟登陆
func GetActivationCodeAndSimulatedLogin(c *gin.Context) {

	//查询激活码
	activeCode := c.PostForm("activeCode")
	if activeCode == "" {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "激活码不能为空!"})
		return
	}
	//开启事务
	session := database.Engine.NewSession()
	defer session.Close() //延迟关闭session
	err1 := session.Begin()
	if err1 != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "开启事务失败!"})
		fmt.Println("开启事务失败")
		return
	}

	exist, code, err := models.GetActivationCode_Tx(session, activeCode)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询激活码出错!"})
		return
	}
	if !exist {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "非法的激活码,激活码不存在!"})
		return
	}
	/*
	  模拟用户登录,用户免密登录
	*/
	if code.UseingId == 0 {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "激活码未绑定用户!"})
		return
	}
	if code != nil && code.UseingId != 0 {
		session := sessions.Default(c)
		//在这里修改,有效时间为3个小时
		session.Options(sessions.Options{MaxAge: 3600 * 3})
		// 设置用户ID到会话中
		session.Set("WorldUserID", utils.Strval(code.UseingId))
		if err := session.Save(); err != nil {
			// 如果保存Session失败,处理错误
			c.JSON(http.StatusOK, gin.H{"code": 0, "message": "模拟登录失败"})
			return
		}
		var userId = session.Get("WorldUserID").(string)
		fmt.Println(config.ColorPurple, "从session中获取userId: ", userId, config.ColorReset)
		config.WorldLoginCacheCode.Set(userId, true, time.Hour)

	}

	//提交事务
	err = session.Commit()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "提交事务失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    1,
		"message": "用户模拟登录成功!",
		"userId":  code.UseingId,
	})

}