package controllers

import (
	"WorldEpcho/src/models"
	"WorldEpcho/src/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

//获取用户和详情信息
func GetUserAndUserDetailInfo(c *gin.Context) {
	/*
	   判断用户是否登录
	*/
	uid, isLogin := service.IsUserLoggedIn(c)
	if !isLogin {
		log.Println("用户未登录")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
		return
	}
	// 根据当前用户登录的id，查询用户注册信息和用户详情信息
	user, userInfo, err := models.GetUserAndUserInfo(uid)
	if err != nil {
		log.Println("查询用户注册信息和用户详情信息出错")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询用户注册信息和用户详情信息出错"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":     1,
		"message":  "查询用户注册信息和用户详情信息成功",
		"user":     user,
		"userInfo": userInfo,
	})

}

//获取用户和详情信息
func GetUserDetailInfo(ctx *gin.Context) {
	/*
	   判断用户是否登录
	*/
	_, isLogin := service.IsUserLoggedIn(ctx)
	if !isLogin {
		log.Println("用户未登录")
		ctx.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
		return
	}
	userId := ctx.PostForm("userId")
	user_Id, err := strconv.ParseInt(userId, 10, 64)
	if err != nil {
		fmt.Println("转换失败:", err)
		ctx.JSON(http.StatusOK, gin.H{"code": 0, "message": "userId类型转换失败"})
		return
	}
	// 根据当前用户登录的id，查询用户注册信息和用户详情信息
	_, userInfo, err := models.GetUserAndUserInfo(user_Id)
	if err != nil {
		log.Println("查询用户注册信息和用户详情信息出错")
		ctx.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询用户注册信息和用户详情信息出错"})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":     1,
		"message":  "查询用户注册信息和用户详情信息成功",
		"userInfo": userInfo,
	})

}

//修改用户详情信息
func EditUserInfo(c *gin.Context) {
	/*
	   判断用户是否登录
	*/
	uid, isLogin := service.IsUserLoggedIn(c)
	if !isLogin {
		log.Println("用户未登录")
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "用户未登录"})
		return
	}

	userName := c.PostForm("userName")
	userSex := c.PostForm("userSex")
	phone := c.PostForm("phone")
	idCard := c.PostForm("idCard")
	student_id := c.PostForm("studentId")
	unit := c.PostForm("unit")
	userHeight := c.PostForm("userHeight")
	userWeight := c.PostForm("userWeight")
	userBirthday := c.PostForm("userBirthday")

	var userinfo = &models.UserInfo{
		UserName:     userName,
		UserSex:      userSex,
		Phone:        phone,
		IDCard:       idCard,
		StudentId:    student_id,
		Unit:         unit,
		UserHeight:   userHeight,
		UserWeight:   userWeight,
		UserBirthday: userBirthday,
	}
	userInfo, err := models.GetUserInfo(uid)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "message": "查询用户详情信息失败!"})
		return
	}
	if userInfo != nil {
		userInfo.UserName = userName
		userinfo.UserSex = userSex
		userinfo.Phone = phone
		userinfo.IDCard = idCard
		userinfo.StudentId = student_id
		userinfo.Unit = unit
		userinfo.UserHeight = userHeight
		userinfo.UserWeight = userWeight
		userinfo.UserBirthday = userBirthday
	}

	err = models.EditUserInfo(userinfo)
	if err != nil {
		c.JSON(200, gin.H{"code": 0, "message": "更新用户详情信息出错"})
		return
	}

	c.JSON(200, gin.H{"code": 1, "message": "更新用户详情信息成功"})

}
