package system

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/google/uuid"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/logger"
	"go-admin/tools"
	"go-admin/tools/app"
	"net/http"
	"strconv"
	"strings"
)

// GetSysUserList
// @Summary 列表用户信息数据(update)
// @Description 获取JSON
// @Tags system/用户
// @Param username query string false "用户名称"
// @Param status query int false "状态：0-正常，1-停用"
// @Param phone query string false "手机号"
// @Param pageIndex query string false "页码"
// @Param pageSize query string false "页面条数"
// @Param roleId query string false "角色id"
// @Param nickName query string false "昵称"
// @Param storeId query string false "门店id"
// @Param shopper_code query string false "店员兑换码"
// @Param uid query string false "小程序ID"
// @Param is_export query string false "是否导出：1-导出"
// @Success 200 {object} models.SysUserListResp
// @Router /api/v1/sysUserList [get]
// @Security Bearer
func GetSysUserList(c *gin.Context) {
	var data models.SysUser
	var err error
	var pageSize = 10
	var pageIndex = 1

	size := c.Request.FormValue("pageSize")
	if size != "" {
		pageSize, err = tools.StringToInt(size)
	}

	index := c.Request.FormValue("pageIndex")
	if index != "" {
		pageIndex, err = tools.StringToInt(index)
	}
	data.Username = c.Request.FormValue("username")             // 用户名称
	data.Status = c.Request.FormValue("status")                 // 状态
	data.Phone = c.Request.FormValue("phone")                   // 手机号
	strRoleId := c.Request.FormValue("roleId")                  // 用户角色
	data.NickName = c.Request.FormValue("nickName")             // 用户昵称
	strStoreId := c.Request.FormValue("storeId")                // 门店id
	data.ShopperCode = c.Request.FormValue("shopper_code")      // 店员兑换码
	UidFlag, _ := tools.StringToInt(c.Request.FormValue("uid")) // 小程序ID
	data.Uid = uint32(UidFlag)
	exportFlag := c.Request.FormValue("is_export") // 是否导出excel
	export := 0
	if exportFlag != "" {
		export, _ = tools.StringToInt(exportFlag)
	}

	data.RoleId, _ = tools.StringToInt(strRoleId)
	//nStoreId, _ := tools.StringToInt(strStoreId)
	//data.StoreId = uint32(nStoreId)

	var ids []int
	if strStoreId != "" {
		// 将字符串按逗号分隔成字符串数组
		idsStrArray := strings.Split(strStoreId, ",")

		// 将每个字符串转换为整数，并添加到 ids 数组
		for _, idStr := range idsStrArray {
			id, err := strconv.Atoi(idStr)
			if err != nil {
				tools.HasError(err, "门店id传参有误", -1)
			}
			ids = append(ids, id)
		}
	}

	postId := c.Request.FormValue("postId")
	data.PostId, _ = tools.StringToInt(postId)

	deptId := c.Request.FormValue("deptId")
	data.DeptId, _ = tools.StringToInt(deptId)

	data.DataScope = tools.GetUserIdStr(c)
	result, count, exportUrl, err := data.GetPage(pageSize, pageIndex, export, ids)
	tools.HasError(err, "", -1)
	var resp models.SysUserListResp
	resp.List = result
	resp.ExportUrl = exportUrl
	resp.Total = count
	resp.PageSize = pageSize
	resp.PageIndex = pageIndex

	app.OK(c, resp, "查询成功")
	return
}

// GetSysUser
// @Summary 获取用户
// @Description 获取JSON
// @Tags system/用户
// @Param userId path int true "用户编码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sysUser/{userId} [get]
// @Security Bearer
func GetSysUser(c *gin.Context) {
	var SysUser models.SysUser
	SysUser.UserId, _ = tools.StringToInt(c.Param("userId"))
	result, err := SysUser.Get()
	tools.HasError(err, "抱歉未找到相关信息", -1)
	var SysRole models.SysRole
	var Post models.Post
	roles, err := SysRole.GetList()
	posts, err := Post.GetList()

	postIds := make([]int, 0)
	postIds = append(postIds, result.PostId)

	roleIds := make([]int, 0)
	roleIds = append(roleIds, result.RoleId)
	app.Custum(c, gin.H{
		"code":    200,
		"data":    result,
		"postIds": postIds,
		"roleIds": roleIds,
		"roles":   roles,
		"posts":   posts,
	})
}

// @Summary 获取个人中心用户
// @Description 获取JSON
// @Tags system/用户
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/profile [get]
// @Security Bearer
func GetSysUserProfile(c *gin.Context) {
	var SysUser models.SysUser
	userId := tools.GetUserIdStr(c)
	SysUser.UserId, _ = tools.StringToInt(userId)
	result, err := SysUser.Get()
	tools.HasError(err, "抱歉未找到相关信息", -1)
	var SysRole models.SysRole
	var Post models.Post
	var Dept models.SysDept
	//获取角色列表
	roles, err := SysRole.GetList()
	//获取职位列表
	posts, err := Post.GetList()
	//获取部门列表
	Dept.DeptId = result.DeptId
	dept, err := Dept.Get()

	postIds := make([]int, 0)
	postIds = append(postIds, result.PostId)

	roleIds := make([]int, 0)
	roleIds = append(roleIds, result.RoleId)

	app.Custum(c, gin.H{
		"code":    200,
		"data":    result,
		"postIds": postIds,
		"roleIds": roleIds,
		"roles":   roles,
		"posts":   posts,
		"dept":    dept,
	})
}

// @Summary 获取用户角色和职位
// @Description 获取JSON
// @Tags system/用户
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sysUser [get]
// @Security Bearer
func GetSysUserInit(c *gin.Context) {
	var SysRole models.SysRole
	var Post models.Post
	roles, err := SysRole.GetList()
	posts, err := Post.GetList()
	tools.HasError(err, "抱歉未找到相关信息", -1)
	mp := make(map[string]interface{}, 2)
	mp["roles"] = roles
	mp["posts"] = posts
	app.OK(c, mp, "")
}

// InsertSysUser
// @Summary 创建用户(update)
// @Description 获取JSON
// @Tags system/用户
// @Accept  application/json
// @Product application/json
// @Param data body models.InsertSysUserReq true "用户数据"
// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /api/v1/sysUser [post]
func InsertSysUser(c *gin.Context) {
	var req models.InsertSysUserReq
	err := c.BindWith(&req, binding.JSON)
	tools.HasError(err, "非法数据格式", 500)

	SalesCommRateFloat, err := models.StringToFloat(req.SalesCommRate)
	if err != nil {
		//logger.Error("brokerage1 err:", err)
		tools.HasError(err, "数据解析失败", 500)
	}

	if req.ShopperCode != "" {
		if len(req.ShopperCode) != 6 {
			logger.Error("兑换码不是6位")
			app.Error(c, http.StatusInternalServerError, err, "兑换码长度不符合要求[6位]")
			return
		}

		if req.Uid == 0 {
			logger.Error("uid为0")
			app.Error(c, http.StatusInternalServerError, err, "配置店员兑换码需填写小程序账号ID")
			return
		}

		// 判断店员兑换码是否重复
		if models.IsShopperCodeExists(req.ShopperCode) {
			logger.Error("兑换码重复")
			app.Error(c, http.StatusInternalServerError, err, fmt.Sprintf("兑换码[%s]重复，请更换", req.ShopperCode))
			return
		}
	}

	// 判断小程序账号ID是否正常
	if req.Uid != 0 {
		userInfo, err := models.GetUserInfoByUid(req.Uid)
		if err != nil {
			logger.Error("get user info err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "小程序账号ID有误，请检查")
			return
		}
		// 是否是真实id
		if userInfo.Uid != req.Uid {
			app.Error(c, http.StatusInternalServerError, err, "小程序账号ID有误，请检查")
			return
		}
		// 是否已经绑定过账号
		if userInfo.UserType == models.UserTypeShopAssistant {
			app.Error(c, http.StatusInternalServerError, err, "小程序账号ID重复，请检查")
			return
		}
	}

	sysUser := models.SysUser{
		SysUserId: req.SysUserId,
		LoginM:    req.LoginM,
		SysUserB: models.SysUserB{
			NickName:              req.NickName,
			Phone:                 req.Phone,
			RoleId:                req.RoleId,
			Salt:                  req.Salt,
			Avatar:                req.Avatar,
			Sex:                   req.Sex,
			Email:                 req.Email,
			DeptId:                req.DeptId,
			PostId:                req.PostId,
			Remark:                req.Remark,
			Status:                req.Status,
			AccountType:           req.AccountType,
			CooperativeBusinessId: req.CooperativeBusinessId,
			CooperativeName:       req.CooperativeName,
			SalesCommRate:         SalesCommRateFloat,
		},
	}

	if req.Uid != 0 {
		sysUser.Uid = req.Uid
	}

	if len(req.StoreList) != 0 {
		// 将 StoreData 转换为 JSON 字符串
		storeDataJSON, err := json.Marshal(req.StoreList)
		if err != nil {
			tools.HasError(err, "数据解析失败", 500)
		}
		sysUser.StoreData = string(storeDataJSON)
	} else {
		sysUser.StoreData = ""
	}
	begin := orm.Eloquent.Begin()
	sysUser.CreateBy = tools.GetUserIdStr(c)
	id, err := sysUser.Insert(begin)
	if err != nil {
		begin.Rollback()
		logger.Error("Insert err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "添加失败")
		return
	}

	// 如果添加了小程序id，则需要更新user表的user_type字段为2-店员
	if req.Uid != 0 {
		err = models.UpdateUserTypeAndShopperName(begin, req.Uid, models.UserTypeShopAssistant, uint32(req.RoleId),
			req.NickName)
		if err != nil {
			begin.Rollback()
			logger.Error("UpdateUserType err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "添加失败")
			return
		}
	}

	if req.ShopperCode != "" {
		err = models.AddShopperCode(req, begin)
		if err != nil {
			begin.Rollback()
			logger.Error("AddShopperCode err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, err.Error())
			return
		}
	}

	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Error("commit err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "添加失败")
		return
	}

	tools.HasError(err, "添加失败", 500)
	app.OK(c, id, "添加成功")
}

// UpdateSysUser
// @Summary 修改用户数据(update)
// @Description 获取JSON
// @Tags system/用户
// @Accept  application/json
// @Product application/json
// @Param data body models.InsertSysUserReq true "body"
// @Success 200 {string} string	"{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "修改失败"}"
// @Router /api/v1/sysuser/{userId} [put]
func UpdateSysUser(c *gin.Context) {
	var req models.InsertSysUserReq
	err := c.BindWith(&req, binding.JSON)
	tools.HasError(err, "非法数据格式", 500)

	if req.ShopperCode != "" {
		if len(req.ShopperCode) != 6 {
			logger.Error("兑换码不是6位")
			app.Error(c, http.StatusInternalServerError, err, "店员识别码长度不符合要求[6位]")
			return
		}

		if req.Uid == 0 {
			logger.Error("uid为0")
			app.Error(c, http.StatusInternalServerError, err, "配置店员识别码需填写小程序账号ID")
			return
		}
	}

	SalesCommRateFloat, err := models.StringToFloat(req.SalesCommRate)
	if err != nil {
		//logger.Error("brokerage1 err:", err)
		tools.HasError(err, "数据解析失败", 500)
	}

	sysInfo := models.GetSysUserById(uint32(req.UserId))
	if sysInfo.Uid != 0 {
		// 添加店员兑换码
		var shopperCode models.ShopperPromotionCode
		err = orm.Eloquent.Table("shopper_promotion_code").Where("uid = ?", sysInfo.Uid).Find(&shopperCode).Error
		if err != nil {
			logger.Error("query shopper_promotion_code err:", logger.Field("err", err))
		}
		sysInfo.ShopperCode = shopperCode.Code
	}

	// 判断小程序账号ID是否正常
	if req.Uid != 0 && sysInfo.Uid != req.Uid {
		userInfo, err := models.GetUserInfoByUid(req.Uid)
		if err != nil {
			logger.Error("get user info err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "小程序账号ID有误，请检查")
			return
		}
		// 是否是真实id
		if userInfo.Uid != req.Uid {
			app.Error(c, http.StatusInternalServerError, err, "小程序账号ID有误，请检查")
			return
		}
		// 是否已经绑定过账号
		if userInfo.UserType == models.UserTypeShopAssistant {
			app.Error(c, http.StatusInternalServerError, err, "小程序账号ID重复，请检查")
			return
		}
	}

	data := models.SysUser{
		SysUserId: req.SysUserId,
		LoginM:    req.LoginM,
		SysUserB: models.SysUserB{
			NickName:              req.NickName,
			Phone:                 req.Phone,
			RoleId:                req.RoleId,
			Salt:                  req.Salt,
			Avatar:                req.Avatar,
			Sex:                   req.Sex,
			Email:                 req.Email,
			DeptId:                req.DeptId,
			PostId:                req.PostId,
			Remark:                req.Remark,
			Status:                req.Status,
			AccountType:           req.AccountType,
			CooperativeBusinessId: req.CooperativeBusinessId,
			CooperativeName:       req.CooperativeName,
			SalesCommRate:         SalesCommRateFloat,
			Uid:                   req.Uid,
		},
	}

	// 重置密码时uid赋值为原有的uid
	if req.Phone == "" && req.LoginM.PassWord.Password != "" && req.Uid == 0 {
		data.Uid = sysInfo.Uid
	}

	if len(req.StoreList) != 0 {
		// 将 StoreData 转换为 JSON 字符串
		storeDataJSON, err := json.Marshal(req.StoreList)
		if err != nil {
			tools.HasError(err, "数据解析失败", 500)
		}
		data.StoreData = string(storeDataJSON)
	} else {
		data.StoreData = ""
	}

	begin := orm.Eloquent.Begin()
	data.UpdateBy = tools.GetUserIdStr(c)
	result, err := data.Update(begin, data.UserId)
	if err != nil {
		begin.Rollback()
	}
	tools.HasError(err, "修改失败", 500)

	// 判断是否修改了uid
	if req.Phone != "" { // 手机号目前是必填项，不能为空，否则可能是重置密码
		if sysInfo.Uid == 0 && req.Uid != 0 { // 新增uid，直接更新为2即可
			err = models.UpdateUserType(begin, req.Uid, models.UserTypeShopAssistant, uint32(req.RoleId))
		} else if sysInfo.Uid != 0 {
			if sysInfo.Uid != req.Uid {
				// 原uid的状态更新为1
				err = models.UpdateUserType(begin, sysInfo.Uid, models.UserTypeConsumer, 0)
				if err == nil {
					if req.Uid != 0 {
						// 新uid状态更新为2
						err = models.UpdateUserType(begin, req.Uid, models.UserTypeShopAssistant, uint32(req.RoleId))
					}
				}
			} else if sysInfo.Uid == req.Uid && sysInfo.RoleId != req.RoleId { // 更改了用户角色
				err = models.UpdateUserType(begin, sysInfo.Uid, models.UserTypeShopAssistant, uint32(req.RoleId))
			}
		}
		if err != nil {
			begin.Rollback()
			logger.Error("UpdateUserType err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "修改失败")
			return
		}
	}

	if req.ShopperCode != "" { // 添加店员兑换码：删除原兑换码，添加新兑换码
		err = models.UpdateShopperCode(req, begin, sysInfo)
		if err != nil {
			begin.Rollback()
			logger.Error("UpdateShopperCode err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, err.Error())
			return
		}
	}

	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Error("commit err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "修改失败")
		return
	}

	app.OK(c, result, "修改成功")
}

// DeleteSysUser
// @Summary 删除用户数据
// @Description 删除数据
// @Tags system/用户
// @Param userId path int true "userId"
// @Success 200 {string} string	"{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "删除失败"}"
// @Router /api/v1/sysuser/{userId} [delete]
func DeleteSysUser(c *gin.Context) {
	var data models.SysUser
	data.UpdateBy = tools.GetUserIdStr(c)
	IDS := tools.IdsStrToIdsIntGroup("userId", c)

	begin := orm.Eloquent.Begin()
	for _, item := range IDS {
		data.UserId = item
		result, err := data.Get()
		if err != nil {
			tools.HasError(err, "删除失败", 500)
		}
		err = models.UpdateUserType(begin, result.Uid, models.UserTypeConsumer, 0)
		if err != nil {
			begin.Rollback()
			logger.Error("DeleteSysUser UpdateUserType err:", logger.Field("err", err))
			tools.HasError(err, "删除失败", 500)
		}
	}

	result, err := data.BatchDelete(begin, IDS)
	if err != nil {
		begin.Rollback()
		logger.Error("DeleteSysUser BatchDelete err:", logger.Field("err", err))
		tools.HasError(err, "删除失败", 500)
	}

	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Error("DeleteSysUser commit err:", logger.Field("err", err))
		tools.HasError(err, "删除失败", 500)
	}

	app.OK(c, result, "删除成功")
}

// @Summary 修改头像
// @Description 获取JSON
// @Tags system/用户
// @Accept multipart/form-data
// @Param file formData file true "file"
// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /api/v1/user/profileAvatar [post]
func InsetSysUserAvatar(c *gin.Context) {
	form, _ := c.MultipartForm()
	files := form.File["upload[]"]
	guid := uuid.New().String()
	filPath := "static/uploadfile/" + guid + ".jpg"
	for _, file := range files {
		logger.Debug(file.Filename)
		// 上传文件至指定目录
		_ = c.SaveUploadedFile(file, filPath)
	}
	sysuser := models.SysUser{}
	sysuser.UserId = tools.GetUserId(c)
	sysuser.Avatar = "/" + filPath
	sysuser.UpdateBy = tools.GetUserIdStr(c)
	sysuser.Update(nil, sysuser.UserId)
	app.OK(c, filPath, "修改成功")
}

func SysUserUpdatePwd(c *gin.Context) {
	var pwd models.SysUserPwd
	err := c.Bind(&pwd)
	tools.HasError(err, "数据解析失败", 500)
	sysuser := models.SysUser{}
	sysuser.UserId = tools.GetUserId(c)
	sysuser.SetPwd(pwd)
	app.OK(c, "", "密码修改成功")
}
