package controllers

import (
	"LAPP_LF_MOM_BACKEND/conf"
	"LAPP_LF_MOM_BACKEND/utils"
	"LAPP_LF_MOM_BACKEND/web/middleware/glog"
	"LAPP_LF_MOM_BACKEND/web/middleware/jwts"
	"LAPP_LF_MOM_BACKEND/web/models"
	"LAPP_LF_MOM_BACKEND/web/supports"
	"github.com/kataras/iris/v12"
	"io"
	"log"
	"net/http"
	"strings"
	"time"
)

//用户登录
func Login(ctx iris.Context) {
	user := new(models.Usertab)
	if err := ctx.ReadJSON(user); err != nil {
		log := new(models.LeitServerLog)
		log.File = "user_controller.go"
		log.Level = "debug"
		log.Function = "Login"
		log.Message = error.Error(err)
		log.Operator = user.Userid
		log.TimeStamp = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
		log.InsertRecord()
		supports.Error(ctx, iris.StatusPaymentRequired, supports.LoginFailur, nil)
		return
	}
	mUser := new(models.Usertab)
	mUser.Pid = user.Pid
	mUser.Userid = user.Userid
	has, err := mUser.GetUserByUsername()
	mUser.Clipped()
	if err != nil {
		glog.InfoExt("登录测试", err)
		log := new(models.LeitServerLog)
		log.File = "user_controller.go"
		log.Level = "debug"
		log.Function = "Login"
		log.Message = error.Error(err)
		log.Operator = user.Userid
		log.TimeStamp = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
		log.InsertRecord()
		supports.Error(ctx, iris.StatusPaymentRequired, supports.LoginFailur, nil)
		return
	}

	if !has { // 用户名不正确
		glog.InfoExt("登录测试", "has 错误")
		supports.Error(ctx, iris.StatusPaymentRequired, supports.UsernameFailur, nil)
		return
	}

	ckPassword, err := utils.CompareHashAndPassword(mUser.Password, user.Password)
	if !ckPassword {
		glog.InfoExt("登录测试", "密码 错误")
		supports.Error(ctx, iris.StatusPaymentRequired, supports.PasswordFailur, nil)
		return
	}

	token, err := jwts.GenerateToken(mUser)
	if err != nil {
		log := new(models.LeitServerLog)
		log.File = "user_controller.go"
		log.Level = "debug"
		log.Function = "Login"
		log.Message = "创建token失败"
		log.Operator = user.Userid
		log.TimeStamp = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
		log.InsertRecord()
		supports.Error(ctx, iris.StatusInternalServerError, supports.TokenCreateFailur, nil)
		return
	}
	log := new(models.LeitServerLog)
	log.File = "user_controller.go"
	log.Level = "info"
	log.Function = "Login"
	log.Message = "登录成功"
	log.Operator = user.Userid
	log.TimeStamp = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
	log.InsertRecord()
	data := make(map[string]string)
	data["token"] = token
	supports.Ok(ctx, supports.LoginSuccess, data)
	return
}

//车间列表
func PlantsTable(ctx iris.Context) {
	plants, err := models.GetPlants()
	if err != nil {
		log := new(models.LeitServerLog)
		log.File = "user_controller.go"
		log.Level = "debug"
		log.Function = "PlantsTable"
		log.Message = "车间查询失败"
		log.Operator = ""
		log.TimeStamp = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
		log.InsertRecord()
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}
	supports.Ok(ctx, supports.Success, plants)
}

// @Summary 获取用户角色和职位
// @Description 获取JSON
// @Tags 用户
// @Success 200 {object} supports.Ok "{"code": 200,msg, "data": [...]}"
// @Router /user/getuserinfo [get]
// @Security
func GetUserInfo(ctx iris.Context) {

	var roles = make([]string, 1)
	user, ok := jwts.ParseToken(ctx)
	utils.TrimStruct(user, *user)
	if !ok {
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}
	roles[0] = user.Role

	var permissions = make([]string, 1)
	permissions[0] = "*:*:*"
	RoleMenu := models.RoleMenu{}
	RoleMenu.RoleId = user.RoleId

	var mp = make(map[string]interface{})
	mp["roles"] = roles
	if user.Userid == "admin" {
		mp["permissions"] = permissions
	} else {
		list, _ := RoleMenu.GetPermis()
		mp["permissions"] = list
	}

	mUser := new(models.Usertab)
	mUser.Pid = user.Pid
	mUser.Userid = user.Userid
	ok, err := mUser.GetUserByUsername()
	mUser.Clipped()
	if !ok || err != nil {
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}
	mp["introduction"] = " am a super administrator"

	mp["avatar"] = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"
	if mUser.Avatar != "" {
		mp["avatar"] = mUser.Avatar
	}
	mp["name"] = mUser.Nickname
	utils.TrimStruct(&mp, mp)
	supports.Ok(ctx, supports.Success, mp)
}

// @Summary 列表数据
// @Description 获取JSON
// @Tags 用户
// @Param username query string false "username"
// @Success 200 {string} string "{"code": 200, "data": [...]}"
// @Success 200 {string} string "{"code": -1, "message": "抱歉未找到相关信息"}"
// @Router /api/v1/sysUserList [get]
// @Security Bearer
func GetSysUserList(ctx iris.Context) {
	var data models.Usertab
	var err error
	var pageSize = 10
	var pageIndex = 1

	size := ctx.URLParam("pageSize")
	if size != "" {
		pageSize = utils.ValueToInt(size, 0)
	}

	index := ctx.URLParam("pageIndex")
	if index != "" {
		pageIndex = utils.ValueToInt(index, 0)
	}

	data.Userid = ctx.URLParam("userid")
	data.Status = ctx.URLParam("status")
	data.Phone = ctx.URLParam("phone")
	data.Name = ctx.URLParam("name")

	result, count, err := data.GetPage(pageSize, pageIndex)
	if err != nil {
		supports.Error(ctx, iris.StatusBadRequest, "抱歉未找到相关信息", nil)
		return
	}
	res := make(map[string]interface{})
	res["result"] = result
	res["count"] = count
	res["pageIndex"] = pageIndex
	res["pageSize"] = pageSize
	supports.Ok(ctx, "成功", res)
}

// @Summary 获取用户
// @Description 获取JSON
// @Tags 用户
// @Param userId path int true "用户编码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sysUser/{userId} [get]
// @Security
func GetSysUser(ctx iris.Context) {
	var SysUser models.Usertab
	SysUser.Userid = ctx.Params().Get("userId")
	result, err := SysUser.Get()
	if err != nil {
		supports.Error(ctx, iris.StatusBadRequest, "抱歉未找到相关信息", nil)
		return
	}
	var SysRole models.Roletab
	roles, err := SysRole.GetList()

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

	data := make(map[string]interface{})
	data["data"] = result
	data["roleIds"] = roleIds
	data["roles"] = roles
	supports.Ok(ctx, supports.OptionSuccess, data)
}

// @Summary 获取当前登录用户
// @Description 获取JSON
// @Tags 个人中心
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /admin/user/profile [get]
// @Security
func GetSysUserProfile(ctx iris.Context) {

	user, ok := jwts.ParseToken(ctx)
	utils.TrimStruct(user, *user)
	if !ok {
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}

	var SysUser models.Usertab
	SysUser.Userid = user.Userid
	result, err := SysUser.Get()
	if err != nil {
		supports.Error(ctx, iris.StatusBadRequest, "抱歉未找到相关信息", nil)
		return
	}
	var SysRole models.Roletab
	//获取角色列表
	roles, err := SysRole.GetList()

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

	data := make(map[string]interface{})
	data["data"] = result
	data["roleIds"] = roleIds
	data["roles"] = roles
	supports.Ok(ctx, supports.OptionSuccess, data)
}

// @Summary 获取用户角色
// @Description 获取JSON
// @Tags 用户
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sysUser [get]
// @Security
func GetSysUserInit(ctx iris.Context) {
	var SysRole models.Roletab
	roles, err := SysRole.GetList()
	if err != nil {
		supports.Error(ctx, iris.StatusBadRequest, "抱歉未找到相关信息", nil)
		return
	}
	mp := make(map[string]interface{}, 0)
	mp["roles"] = roles
	supports.Ok(ctx, supports.OptionSuccess, mp)
}

// @Summary 创建用户
// @Description 获取JSON
// @Tags 用户
// @Accept  application/json
// @Product application/json
// @Param data body models.SysUser true "用户数据"
// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /api/v1/sysUser [post]
func InsertSysUser(ctx iris.Context) {
	user := new(models.Usertab)
	if err := ctx.ReadJSON(user); err != nil {
		log := new(models.LeitServerLog)
		log.File = "user_controller.go"
		log.Level = "debug"
		log.Function = "InsertSysUser"
		log.Message = "json解析失败"
		log.Operator = ""
		log.TimeStamp = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
		log.InsertRecord()
		supports.Error(ctx, iris.StatusInternalServerError, "json解析错误", nil)
		return
	}

	user.Lastmodify = user.Lastmodify
	user.Password = "123456"
	user.Createtime = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
	id, err := user.Insert()
	if err != nil {
		supports.Error(ctx, iris.StatusInternalServerError, "添加失败", nil)
		return
	}
	supports.Ok(ctx, supports.OptionSuccess, id)
}

// @Summary 修改用户数据
// @Description 获取JSON
// @Tags 用户
// @Accept  application/json
// @Product application/json
// @Param data body models.SysUser true "body"
// @Success 200 {string} string	"{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "修改失败"}"
// @Router /api/v1/sysuser/{userId} [put]
func UpdateSysUser(ctx iris.Context) {

	user, ok := jwts.ParseToken(ctx)
	utils.TrimStruct(user, *user)
	if !ok {
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}

	data := new(models.Usertab)
	if err := ctx.ReadJSON(data); err != nil {
		supports.Error(ctx, iris.StatusInternalServerError, "json解析错误", nil)
		return
	}
	data.Pid = user.Pid
	data.Lastmodify = user.Userid
	result, err := data.Update(data.Userid)
	if err != nil {
		supports.Error(ctx, iris.StatusInternalServerError, "更新失败:"+err.Error(), nil)
		return
	}
	supports.Ok(ctx, supports.OptionSuccess, result)
}

// @Summary 删除用户数据
// @Description 删除数据
// @Tags 用户
// @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(ctx iris.Context) {
	user, ok := jwts.ParseToken(ctx)
	utils.TrimStruct(user, *user)
	if !ok {
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}
	var data models.Usertab
	data.Lastmodify = user.Userid
	userId := ctx.Params().Get("userId")
	ids := strings.Split(userId, ",")
	result, err := data.BatchDelete(ids)
	if err != nil {
		supports.Error(ctx, iris.StatusInternalServerError, "删除失败", nil)
		return
	}
	supports.Ok(ctx, supports.OptionSuccess, result)
}

// @Summary 修改头像
// @Description 获取JSON
// @Tags 用户
// @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(ctx iris.Context) {

	user, ok := jwts.ParseToken(ctx)
	utils.TrimStruct(user, *user)
	if !ok {
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}

	//获取通过iris.WithPostMaxMemory获取的最大上传值大小。
	maxSize := ctx.Application().ConfigurationReadOnly().GetPostMaxMemory()
	err := ctx.Request().ParseMultipartForm(maxSize)
	if err != nil {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.WriteString(err.Error())
		return
	}
	form := ctx.Request().MultipartForm
	files := form.File["upload[]"]

	guid := utils.MakeOrderSn(user.Userid)
	filPath := "public/uploadfile/" + guid + ".jpg"
	savePath := "web/public/uploadfile/" + guid + ".jpg"

	for _, file := range files {
		// 上传文件至指定目录
		err := utils.SaveUploadedFile(file, savePath)
		if err != nil {
			log.Printf("上传图片错误:%v", err)
			return
		}
	}

	sysuser := new(models.Usertab)
	sysuser.Userid = user.Userid
	sysuser.Pid = user.Pid
	sysuser.Avatar = "/" + filPath
	sysuser.Lastmodify = user.Userid
	_, err = sysuser.Update(sysuser.Userid)
	if err != nil {
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}
	supports.Ok(ctx, "修改成功", filPath)
}

func SysUserUpdatePwd(ctx iris.Context) {
	user, ok := jwts.ParseToken(ctx)
	utils.TrimStruct(user, *user)
	if !ok {
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}
	pwd := new(models.SysUserPwd)
	if err := ctx.ReadJSON(pwd); err != nil {
		log := new(models.LeitServerLog)
		log.File = "user_controller.go"
		log.Level = "debug"
		log.Function = "SysUserUpdatePwd"
		log.Message = "json解析失败"
		log.Operator = ""
		log.TimeStamp = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
		log.InsertRecord()
		supports.Error(ctx, iris.StatusInternalServerError, "json解析错误", nil)
		return
	}
	sysuser := models.Usertab{}
	sysuser.Userid = user.Userid
	sysuser.Pid = user.Pid
	_, err := sysuser.SetPwd(pwd)
	if err != nil {
		supports.Error(ctx, iris.StatusBadRequest, supports.ParseParamsFailur, nil)
		return
	}
	supports.Ok(ctx, "密码修改成功", "")
}

//反代理图片
func GetImg(ctx iris.Context) {
	imgpath := ctx.URLParam("imgpath")
	url := conf.Baseurl + imgpath
	res, err := http.Get(url)
	defer res.Body.Close() //不要泄露资源
	if err != nil {
		log.Println("获取文件错误")
	}
	io.Copy(ctx.ResponseWriter(), res.Body)
}
