package routers

import (
	"WorldEpcho/src/controllers"
	"WorldEpcho/src/service"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"net/http"
	"strings"

	//"WorldEpcho/src/wxnativepay"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http/httputil"
	"net/url"
)

func InitRouter() *gin.Engine {

	router := gin.Default()

	// 将本地路径映射到URL
	router.Static("/static", "static/HuaSoul")
	router.Static("/userFile", "static/user")
	router.Static("/worlds", "static/Worlds")
	router.Static("/Mass", "static/Mass")

	//设置session middleware
	store := cookie.NewStore([]byte("loginuser"))
	//web引擎router调用Use方法,将生成的Session存放到Cookie里
	//store.Options(sessions.Options{
	//	MaxAge: 3600 * 3, // 设置 Cookie 的最大存活时间为 3 小时
	//	//Path:     "/",                  // Cookie 的路径
	//	HttpOnly: true,  // 仅通过 HTTP(S) 传递，防止 XSS 攻击
	//	Secure:   false, // 在生产环境中设置为 true (需要 HTTPS)
	//	//SameSite: http.SameSiteLaxMode, // SameSite 属性
	//})
	router.Use(sessions.Sessions("WorldSession", store))

	//跨域,中间件
	router.Use(Cors())

	//Authenticatied := router.Group("/")
	//Authenticatied.Use(AuthRequired)
	//{
	//	Authenticatied.GET("/test")
	//}
	/*
	   咪咕相关的路由
	*/
	//咪咕jwt,用户登陆鉴权
	router.POST("/MiGuLoginJWT", controllers.LoginJWT)
	// 服务商创建用户接口
	router.POST("/MiGuRegisterUser", controllers.MiGuServiceProviderRegister)
	// 咪咕服务商刷新token
	router.POST("/MiGuRefreshJwtToken", controllers.RefreshJwtToken)
	//咪咕重置世界意识流2
	router.POST("/MiGuWorldResetNeuralFile", controllers.MiGuWorldResetNeuralFile)
	//查询业务经理考核世界信息
	router.POST("/MiGuQueryBusinessManagerWorldInfo", controllers.MiGuQueryBusinessManagerWorldInfo)
	//语音识别
	router.POST("/MiGuSpeechConvertor", service.MiGuTranscribeAudio)

	//======================================================================//
	//语音识别路由
	router.POST("/speechConvertor", service.TranscribeAudio)
	//AI接口绘制漫画头像
	router.POST("/GenerateAvatarHandler", service.GenerateAvatarHandler)

	// 登陆鉴权检测
	router.POST("/LoginTest", controllers.LoginTest)
	// 心跳包路由2
	router.GET("/Heartbeat2", controllers.Heartbeat2)

	{
		/*
			邀请码
		*/
		//获取邀请码
		router.GET("/getInviteCode", controllers.GetInviteCode)
		//创建一次性激活码
		router.POST("/CreateActiveCode", controllers.CreateActiveCode)

		//批量创建激活码
		router.POST("BatchCreateActiveCode", controllers.BatchCreateActiveCode)

		router.GET("/GetActivationCode", controllers.GetActivationCode)
		//为激活码续时间，小时为单位
		router.POST("/ExtendActivationCodeTime", controllers.ExtendActivationCodeTime)
		// 修改激活码的备注信息
		router.POST("/UpdateActiveCode", controllers.UpdateActiveCode)

		//用户查询月限额和绑定的激活码的过期时间
		router.POST("/GetUserAvailableMonthlyLimit", controllers.GetUserAvailableMonthlyLimit)

		//重置邀请码
		router.POST("/resetInviteCode", controllers.ResetUserInviteCode)
		//获取当前用户的所有直接邀请人
		router.POST("/queryDirectInviter", controllers.QueryDirectInviter)
		//获取当前用户的所有间接邀请的人
		router.POST("/queryIndirectInvitees", controllers.QueryIndirectInvitees)

		//上传多个模型文件夹
		//router.POST("/digitalPerson/modeFile", controllers.UploadModelFolder)
		//router.POST("/digitalPerson/modeFile", controllers.UploadFolderHandler)

		//注册：
		router.GET("/register", controllers.RegisterGet)
		router.POST("/register", controllers.RegisterPost)
		router.POST("/ServiceProviderUserRegister", controllers.ServiceProviderRegisterPost)

		router.POST("/ServiceProviderBatchAccount", controllers.ServiceProviderBatchAccount)
		// 用户注销
		router.POST("/UnregisterUser", controllers.UnregisterPost)
		//登录
		//router.GET("/login", controllers.LoginGet)
		router.POST("/login", controllers.LoginPost)
		//模拟登录接口
		router.POST("/SimulateLogin", controllers.SimulateLogin)

		// 心跳包路由
		router.GET("/heartbeat", controllers.Heartbeat)

		//获取用户信息
		router.GET("/user/userInfo", controllers.SearchUserGetById)
		//获取用户详情信息
		router.POST("/user/GetUserDetailInfo", controllers.GetUserDetailInfo)

		router.GET("/user/userAndUserDetailInfo", controllers.GetUserAndUserDetailInfo)
		//修改用户信息
		router.POST("/user/updateInfo", controllers.UpdateUserInfoPost)
		//通过手机号修改用户密码
		router.POST("/user/resetPassword", controllers.ResetUserPassword)

		//获取用户已经聊天的数字人信息
		router.GET("/user/userDpConversation", controllers.QueryUserToDpConversation)
		//获取用户与数字人的历史聊天记录
		router.POST("/chat-history", controllers.QueryUserAndDigitalPersonHistoryChatById)

		/*
		  世界推演相关接口
		*/
		//查询激活码，模拟登陆
		router.POST("/GetActivationCodeAndSimulatedLogin", controllers.GetActivationCodeAndSimulatedLogin)
		//创建世界信息
		router.POST("/worldInfo/CreateWorldInfo", controllers.CreateWorldInfo)
		//业务经理考核系统
		router.POST("/worldInfo/CreateBusinessManagerAssessmentSystem", controllers.CreateBusinessManagerAssessmentSystem)

		// 咪咕创建业务经理考核系统
		router.POST("/worldInfo/MiGuCreateBusinessManagerAssessmentSystem", controllers.MiGuCreateBusinessManagerAssessmentSystem)
		//编辑业务经理考核系统面板信息
		router.POST("/worldInfo/EditBusinessManagerAssessmentSystem", controllers.EditBusinessManagerAssessmentSystem)
		//查询业务经理考核系统的面板配置信息
		router.POST("/worldInfo/QueryBusinessManagerAssessmentSystem", controllers.QueryBusinessManagerAssessmentSystemConfigData)
		//查询业务经理考核世界信息
		router.POST("/QueryBusinessManagerWorldInfo", controllers.QueryBusinessManagerWorldInfo)

		//查询最近一次世界推演结局信息
		router.POST("/QueryWorldDeductionResultsByWorldAndUserLastTime", controllers.QueryWorldDeductionResultsByWorldAndUserLastTime)

		//查询所有的推演结果
		router.POST("/QueryWorldDeductionResults", controllers.QueryWorldDeductionResults)

		//获取用户已经聊天的世界信息
		router.GET("/user/userWorldConversation", controllers.QueryUserToWorldConversation)
		//获取用户已经聊天过的世界信息接口
		router.POST("/QueryUserIsWorldConversation", controllers.QueryUserIsWorldConversation)
		//获取用户是否与某世界进行过会话
		router.POST("/QueryUserToWorldIsExistConversation", controllers.QueryUserToWorldIsExistConversation)

		// 道具名称翻译接口
		router.POST("/translateProp", service.TranslateProp1)
		// 调用AI绘图接口
		router.POST("/AiDraw", service.AiDraw)

		//调用AI生成动漫头像接口
		router.POST("/GenerateHeadPortraitHandler", service.GenerateAvatarHandler)

		// 编辑世界信息
		router.POST("/EditWorldInfo", controllers.EditWorldInfo)

		//获取用户与世界 的历史聊天记录
		router.POST("/worldChat-history", controllers.QueryUserAndWorldHistoryChatById)
		//根据指定的时间戳获取用户与世界的历史聊天记录
		router.POST("/worldChatHistoryByIdAndChatTime", controllers.QueryUserAndWorldHistoryChatByIdAndChatTime)
		//重置世界意识流1
		router.POST("/SoulNeuralFileWorldReset", controllers.SoulNeuralFileWorldReset)

		router.POST("/QueryWorldsByLikeName", controllers.QueryWorldsByLikeName)

		//查询世界信息和世界资产
		router.POST("/QueryWorldInfoAndAsset", controllers.QueryWorldInfoAndAssetById)

		/* EMBU 测量 */
		router.POST("/EmbuEvaluation", controllers.HandleEmbuEvaluation)

		//webSocketChat控制器
		router.GET("/chat/ws", service.WsHandler)
		//多数字人聊天的websocket控制器
		router.GET("/DpChats/ws", service.DpsWsHandler)
		//世界推演
		router.GET("/WorldChats/ws", service.WorldWsHandler)

		//首页
		//routers.GET("/", controllers.HomeGet)

		//退出
		//routers.GET("/exit", controllers.ExitGet)

		/*
		   JWT鉴权
		*/
		//路由组

		v1 := router.Group("/jwt")

		v1.GET("/nextHuman", controllers.GetJwtToken)

		/*
			短信验证码
		*/
		/*
			router.POST("/get-code", func(context *gin.Context) {
						controllers.GetCode(context)
						context.JSON(http.StatusOK, gin.H{"code": 1, "message": "验证码已发送"})
					})
		*/
		//done

		//生成图形验证码
		router.POST("/ImagCode", controllers.CreateImg)
		// 图形验证码校验
		router.POST("/CheckImagCode", controllers.CheckImg)

	}
	digitalPersonGroup := router.Group("/digitalpersons")
	{
		digitalPersonGroup.POST("/add", controllers.AddDigitalPerson)
		digitalPersonGroup.POST("/id", controllers.QueryDigitalPersonByID)
		digitalPersonGroup.POST("/edit", controllers.EditDigitalPerson)
		digitalPersonGroup.POST("/delete", controllers.DropDigitalPersonByID)
		digitalPersonGroup.POST("/search", controllers.QueryLikeNameDigitalPerson)
		digitalPersonGroup.POST("/reset", controllers.SoulNeuralFileReset)

		//清除多数字人记忆文件
		digitalPersonGroup.POST("/dpsReset", controllers.SoulNeuralFileResetDps)
	}
	userInfo_appGroup := router.Group("/userInfo_app")
	{
		userInfo_appGroup.POST("/createApp", controllers.CreateApplication)
		userInfo_appGroup.POST("/getAppById", controllers.QueryApplication)
		userInfo_appGroup.POST("/updateApp", controllers.EditApplication)
		userInfo_appGroup.POST("/deleteApp", controllers.DropApplication)
		userInfo_appGroup.POST("/queryAppsByParticipatorId", controllers.QueryApplicationsByParticipatorId)
		userInfo_appGroup.POST("/addAppParticipatorId", controllers.AddApplicationParticipator)
		userInfo_appGroup.POST("/queryParticipantsByAppId", controllers.QueryParticipantsByAppID)
		userInfo_appGroup.POST("/queryApplicationLikeAppName", controllers.QueryApplicationLikeAppName)
		userInfo_appGroup.GET("/QueryAppIdNames", controllers.QueryAppIdNames)

		//从聊天记录里面获取AI的MHT测评结果，进行加强平均
		//userInfo_appGroup.POST("/CalculateMHTAvgEvaluateFromHistoryChat", controllers.CalculateMHTAvgEvaluateFromHistoryChat)
	}
	//用户应用数据的路由组
	uappdata := router.Group("/userAppData")
	{
		uappdata.POST("/queryUserAppDataByUserId", controllers.QueryUserAppDataByUserId)
		uappdata.POST("/dropUserAppDataByUidAndAppId", controllers.DropUserAppDataByUidAndAppId)
	}
	//应用组群路由
	appGroup := router.Group("/appGroup")
	{
		// 查询亲子应用组群中父母的账号和孩子的账号, QueryParentAndChildUserID
		//appGroup.POST("/QueryParentAndChildUserId", controllers.QueryParentAndChildUserID)
		appGroup.POST("/createAppGroup", controllers.CreateApplicationGroup)
		appGroup.POST("/AddUserToAppGroup", controllers.AddUserToAppGroup)
		appGroup.POST("/QueryAppGroupsByMemberID", controllers.QueryAppGroupsByMemberID)
		appGroup.POST("/DeleteMemberFromGroup", controllers.DeleteMemberFromGroup)
		appGroup.POST("/GetUserAppDataWithPermission", controllers.GetUserAppDataWithPermission)

		// 教师查询班级指定学生的MHT的AI无感测评
		//appGroup.POST("/TeacherGetStudentAIWithHistoryChatMHT", controllers.TeacherGetStudentAIWithHistoryChatMHT)

		// 根据组群编号查询组群信息 GetAppGroupByID
		//appGroup.POST("/QueryAppGroupByNo", controllers.QueryAppGroupByNo)
	}

	//用户心理咨询诊疗路由组
	//脑机端接口请求
	router.POST("/selectAiMentalClinicList", service.PostSelectAiMentalClinicList)
	//MHT快速录入接口
	router.POST("/evaluateMHTMentalClinic", service.EvaluateMHTMentalClinic)
	//获取用户MHT量表测量结果
	router.POST("/QueryUserAppDataMHTAnswer", controllers.QueryUserAppDataMHTAnswer)
	// 教师获取班级指定学生的MHT量表测量结果
	//router.POST("/TeacherGetClassStudentMHTAnswer", controllers.TeacherGetClassStudentMHTAnswer)

	// 导出学生MHT心理测评结果接口
	//router.POST("/ExportStudentMHTEvaluateToExcel", controllers.ExportStudentMHTEvaluateToExcel)
	// 教师导出MHT测评结果为Excel的接口2
	//router.POST("/TeacherExportMHTResult2Excel", controllers.ExportStudentMHTEvaluateToExcel2)

	// 学校负责人导出MHT心理咨询测评结果为Excel的接口
	//router.POST("/SchoolLeaderExportMHTResult2Excel", controllers.SchoolLeaderExportMHTResult2Excel)

	//学校负责人导出MHT心理咨询测评结果为Excel的接口2
	//router.POST("/SchoolLeaderExportMHTResult2Excel_LatestChat", controllers.SchoolLeaderExportMHTResult2Excel_LatestChat)

	//创建套餐的接口
	//router.POST("/CreateActiveCodeCombo", controllers.CreateActiveCodeCombo)
	//获取所有套餐信息接口
	//router.GET("/GetAllActiveCodeCombos", controllers.GetAllActiveCodeCombos)
	//获取激活码套餐支付二维码
	//router.POST("/WechatPrePay2Code", wxnativepay.WechatPrePay2Code)
	// 获取激活码续费套餐支付二维码
	//router.POST("/ComboRenewalFeePrePay2Code", wxnativepay.ComboRenewalFeePrePay2Code)

	// 支付通知
	// router.POST("/payNotify", wxnativepay.PayNotify)
	// 查询用户购买的激活码接口
	// router.POST("/QueryGenerateActiveCodeByWxPaySuccess", wxnativepay.QueryGenerateActiveCodeByWxPaySuccess)
	// 查询用户购买的激活码续费套餐接口
	// router.POST("/QueryComboRenewalFeeByWxPaySuccess", wxnativepay.QueryComboRenewalFeeByWxPaySuccess)
	//查询所有交易订单信息
	// router.POST("/QueryAllComboOrders", controllers.QueryAllOrders)
	//根据查询个人的订单信息
	// router.POST("/GetComboOrderByUserID", controllers.GetComboOrderByUserID)

	mentalClinic := router.Group("/MentalClinic")
	{
		//脑机回调,用户快速录入接口
		mentalClinic.POST("/data", service.ProcessData)
		mentalClinic.POST("/quickMHTMentalClinic", service.QuickMHTMentalClinic)
		//mentalClinic.POST("/evaluateMHTMentalClinic", service.EvaluateMHTMentalClinic)
	}
	//学校和班级录入
	schoolClass_group := router.Group("/SchoolAndClass")
	//学校和班级录入接口
	{
		// 查询所有学校信息
		//schoolClass_group.POST("/QueryAllSchoolInfo", controllers.QueryAllSchoolInfo)
		// 查询所有学校信息
		//schoolClass_group.POST("/QueryAllSchools", controllers.QueryAllSchools)

		//查询所有学校和班级信息
		//schoolClass_group.POST("/QueryAllSchoolInfoAndClassInfo", controllers.QueryAllSchoolInfoAndClassInfo)
		// 根据学校编号查询学校信息
		//schoolClass_group.POST("/QuerySchoolBySchoolNo", controllers.QuerySchoolBySchoolNo)
		// 根据学校名称查询学校信息
		//schoolClass_group.POST("/QuerySchoolBySchoolName", controllers.QuerySchoolBySchoolName)
		// 修改学校信息
		//schoolClass_group.POST("/UpdateSchoolInfo", controllers.UpdateSchoolInfo)
		// 根据学校编号查询所有班级信息
		//schoolClass_group.POST("/QueryClassByUserId", controllers.QueryClassByUserId)
		// 修改班级信息
		//schoolClass_group.POST("/UpdateClassInfo", controllers.UpdateClassInfo)
		// 删除学校和班级信息
		//schoolClass_group.POST("/DropSchoolAndClassInfo", controllers.DropSchoolAndClassInfo)
		// 根据班级号删除某个班级信息
		//schoolClass_group.POST("/DropClassByClassNo", controllers.DropClassByClassNo)
		// 为某学校添加班级信息操作
		//schoolClass_group.POST("/AddClassToSchool", controllers.AddClassToSchool)

		// 根据学校名称，班级编号，班级名称和应用id，查询MHT应用对应的班级群信息
		//schoolClass_group.POST("/GetClassGroupBySchoolNameAndClassNo", controllers.GetClassGroupBySchoolNameAndClassNo)

		/* ============================ 学校负责人注册接口   ==========================*/
		//schoolClass_group.POST("/RegisterSchoolLeader", controllers.RegisterSchoolLeader)

		/* ============================   ==========================*/
		schoolClass_group.POST("/QuickSchoolRegisterStuAndPatriarch", controllers.QuickSchoolRegisterStuAndPatriarch)
		// 亲子账号注册接口
		//schoolClass_group.POST("/RegisterStuAndPatriarch", controllers.RegisterStuAndPatriarch)
		// 亲子咨询
		//schoolClass_group.POST("/ParentChildConsult", controllers.ParentChildConsult)
		// 获取子女的EMBU测量结果
		//schoolClass_group.POST("/QueryChildEMBUEvaluateResult", controllers.QueryChildEMBUEvaluateResult)
		// 获取指定子女的EMBU测量结果
		//schoolClass_group.POST("/QueryChildEMBUEvaluateResultByChildUID", controllers.QueryChildEMBUEvaluateResultByChildUID)

		// 获取自己EMBU测量结果
		//schoolClass_group.POST("/GetLatestEMBUEvaluateResult", controllers.QueryLatestEMBUEvaluateResult)
		//学生注册接口
		schoolClass_group.POST("/QuickSchoolRegisterStudent", controllers.QuickSchoolRegisterStudent)
		//班级负责人和创建班级应用组群的注册接口
		schoolClass_group.POST("/QuickRegisterClassLeaderAndCreateAppGroup", controllers.QuickRegisterClassLeaderAndCreateAppGroup)
		schoolClass_group.POST("/create_school_classes", controllers.CreateSchoolAndClasses)
		schoolClass_group.POST("/QueryClassesBySchool", controllers.QueryClassesBySchool)

	}

	// 服务商接口
	ServiceProvider := router.Group("ServiceProvider")
	{
		ServiceProvider.POST("/CreateServiceProvider", controllers.CreateServiceProvider)
	}

	//创建展商信息
	//router.POST("/CreateExhibitorInfo", controllers.CreateExhibitorInfo)
	//心灵小屋和展商注册接口
	//router.POST("/ExhibitorOrMindHouseRegister", controllers.ExhibitorOrMindHouseRegister)

	// 音色克隆模型接口
	VoiceMode := router.Group("VoiceMode")
	{
		VoiceMode.POST("/GetVoiceEcho", service.GetVoiceEcho)
		VoiceMode.POST("/QueryAllModelPeopleNames", service.QueryAllModelPeopleNames)
	}
	// 微信小程序登录接口
	wechat := router.Group("wechat")
	{
		wechat.POST("/AppletWeChatRegisterOrLogin", controllers.AppletWeChatRegisterOrLogin)
		//wechat.POST("/GetWeixinAccessToken", service.GetWeixinAccessToken)
		wechat.POST("/LoginOrBindWXUserPhone", controllers.LoginOrBindWXUserPhone)
		//校验用户是否已经注册，是否已经绑定手机号
		wechat.POST("/CheckWxUserIsRegisterAndBindPhone", controllers.CheckWxUserIsRegisterAndBindPhone)
		/*
		   wechat.POST("/CreateVirtualWorldHandler", controllers.CreateVirtualWorldHandler)
		   wechat.POST("/FindWorldHandler", controllers.FindWorldHandler)
		*/

	}

	// 设置反向代理
	router.Any("/say/*name", func(c *gin.Context) {
		proxyURL, err := url.Parse("http://127.0.0.1:1233")
		if err != nil {
			log.Printf("Failed to parse proxy URL: %v", err)
		}
		c.Request.URL.Path = c.Param("name")
		proxy := httputil.NewSingleHostReverseProxy(proxyURL)
		proxy.ServeHTTP(c.Writer, c.Request)
	})
	// 角色声线分类模型接口,设置反向代理
	router.Any("/ai/*name", func(c *gin.Context) {
		proxyURL, err := url.Parse("http://127.0.0.1:19999")
		if err != nil {
			log.Printf("Failed to parse proxy URL: %v", err)
		}
		c.Request.URL.Path = c.Param("name")
		proxy := httputil.NewSingleHostReverseProxy(proxyURL)
		proxy.ServeHTTP(c.Writer, c.Request)
	})

	return router
}

func AuthRequired(c *gin.Context) {
	ip := c.GetHeader("X-Forward-For")
	fmt.Println("当前ip为", string(ip))
	ip = c.GetHeader("X-Real-Ip")
	fmt.Println("当前ip为", string(ip))
	ip = c.ClientIP()
	fmt.Println("当前ip为", string(ip))
	fmt.Println(c.String)
	//origin := c.Request.Header.Get("origin")
	//亚皮//if origin != "http://52.83.116.11:9999"
	//c.JSON(401,gin.H{"status": "Failed !"})
	c.Next()
}

//开启跨越的操作
func Cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		origin := context.Request.Header.Get("Origin")
		var headerKeys []string
		for k, _ := range context.Request.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ",")
		if headerStr != "" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}

		if origin != "" {
			context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
			context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
			context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
			context.Header("Access-Control-Max-Age", "172800")
			context.Header("Access-Control-Allow-Credentials", "false")
			context.Set("content-type", "application/json") //// 设置返回格式是json
		}

		if method == "OPTIONS" {
			context.JSON(http.StatusOK, "Options Request!")
		}
		//处理请求
		context.Next()
	}
}
