package service

import (
	"errors"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
	"gin-vue-admin/utils"
	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
	"strconv"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: Register
//@description: 运营端注册
//@param: u model.SysUser
//@return: err error, userInter model.SysUser

func Register(u model.SysUser) (err error, userInter model.SysUser) {
	var user model.SysUser
	if !errors.Is(global.GVA_DB.Where("mobile = ?", u.Mobile).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
		return errors.New("用户名已注册"), userInter
	}
	// 否则 附加uuid 密码md5简单加密 注册
	u.Password = utils.MD5V([]byte(u.Password))
	u.UUID = uuid.NewV4()
	u.IsManager = 1
	err = global.GVA_DB.Create(&u).Error
	return err, u
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: Login
//@description: 用户登录
//@param: u *model.SysUser
//@return: err error, userInter *model.SysUser

func Login(u *model.SysUser) (err error, userInter *model.SysUser) {
	var user model.SysUser
	u.Password = utils.MD5V([]byte(u.Password))
	err = global.GVA_DB.Where("mobile = ? AND password = ? AND is_manager=1", u.Mobile, u.Password).Preload("Authority").First(&user).Error
	return err, &user
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: ChangePassword
//@description: 修改用户密码
//@param: u *model.SysUser, newPassword string
//@return: err error, userInter *model.SysUser

func ChangePassword(u *model.SysUser, newPassword string) (err error, userInter *model.SysUser) {
	var user model.SysUser
	u.Password = utils.MD5V([]byte(u.Password))
	err = global.GVA_DB.Where("mobile = ? AND password = ?", u.Mobile, u.Password).First(&user).Update("password", utils.MD5V([]byte(newPassword))).Error
	return err, u
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetUserInfoList
//@description: 分页获取数据
//@param: info request.PageInfo
//@return: err error, list interface{}, total int64

func GetUserInfoList(info request.PageInfo) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&model.SysUser{})
	var userList []model.SysUser
	err = db.Count(&total).Error
	err = db.Where("is_manager=1").Limit(limit).Offset(offset).Preload("Authority").Find(&userList).Error
	return err, userList, total
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: SetUserAuthority
//@description: 设置一个用户的权限
//@param: uuid uuid.UUID, authorityId string
//@return: err error

func SetUserAuthority(uuid uuid.UUID, authorityId string) (err error) {
	err = global.GVA_DB.Where("uuid = ?", uuid).First(&model.SysUser{}).Update("authority_id", authorityId).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteUser
//@description: 删除用户
//@param: id float64
//@return: err error

func DeleteUser(id float64) (err error) {
	var user model.SysUser
	err = global.GVA_DB.Where("id = ?", id).Delete(&user).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: SetUserInfo
//@description: 设置用户信息
//@param: reqUser model.SysUser
//@return: err error, user model.SysUser

func SetUserInfo(reqUser model.SysUser) (err error, user model.SysUser) {
	err = global.GVA_DB.Updates(&reqUser).Error
	return err, reqUser
}

//@author: [SliverHorn](https://github.com/SliverHorn)
//@function: FindUserById
//@description: 通过id获取用户信息
//@param: id int
//@return: err error, user *model.SysUser

func FindUserById(id int) (err error, user *model.SysUser) {
	var u model.SysUser
	err = global.GVA_DB.Where("`id` = ?", id).First(&u).Error
	return err, &u
}

//@author: [SliverHorn](https://github.com/SliverHorn)
//@function: FindUserByUuid
//@description: 通过uuid获取用户信息
//@param: uuid string
//@return: err error, user *model.SysUser

func FindUserByUuid(uuid string) (err error, user *model.SysUser) {
	var u model.SysUser
	if err = global.GVA_DB.Where("`uuid` = ?", uuid).First(&u).Error; err != nil {
		return errors.New("用户不存在"), &u
	}
	return nil, &u
}

func GetMobileUserList(req request.GetMobileUserListReq) (err error, list []request.GetMobileUserListReply, total int64) {
	pagesize := 10
	page := 1
	if req.PageSize != 0 {
		pagesize = req.PageSize
	}
	if req.Page != 0 {
		page = req.Page
	}
	currentpage := pagesize * (page - 1)

	table := " sys_users as su " +
		" left join sys_user_authe as sua on su.id = sua.user_id and sua.delflag=0 " +
		" LEFT JOIN region as r on sua.hospital_province=r.region_id " +
		" LEFT JOIN region as r2 on sua.hospital_city=r2.region_id " +
		" LEFT JOIN region as r3 on sua.hospital_county=r3.region_id " +
		" LEFT JOIN vip_user as vu on su.id=vu.user_id "
	field := " su.id, su.mobile, su.created_at, su.nick_name, sua.name, sua.phone, sua.working_years" +
		", sua.working_place, sua.position, r.region_name as province_name, r2.region_name as city_name" +
		", r3.region_name as county_name, sua.hospital_address, vu.update_time, vu.maturity_time" +
		", vu.vip_level "
	conditions := " AND su.deleted_at is null "
	orderby := " su.created_at desc, su.id desc"

	if req.Mobile != "" {
		conditions += " AND su.mobile like '%" + req.Mobile + "%' "
	}

	if req.StartCreatedAt != "" {
		conditions += " AND su.created_at >'" + req.StartCreatedAt + "'"
	}

	if req.EndCreatedAt != "" {
		conditions += " AND su.created_at <='" + utils.REndDate(req.EndCreatedAt) + "'"
	}

	if req.IsManager != "" {
		conditions += " AND su.is_manager = " + req.IsManager
	}

	if req.AuthorityId != "" {
		conditions += " AND su.authority_id = " + req.AuthorityId
	}

	if req.UserType != "" {
		conditions += " AND su.user_type = " + req.UserType
	}

	data := []request.GetMobileUserListReply{}

	//@@总条数，总页数
	var totalItem int64 = 0

	sqlStr := "SELECT count(su.id) as totalItem FROM " + table + " where 1=1 " + conditions
	global.GVA_DB.Raw(sqlStr).Count(&totalItem) //获取总条数

	//table += " left join (select thumb_cos_path, studyuid from study_image_store group by studyuid)as si on rm.studyuid=si.studyuid "
	//field += ", thumb_cos_path "
	sqlStr2 := "SELECT " + field +
		" FROM " + table +
		" where 1>0 " + conditions +
		" ORDER BY " + orderby +
		" LIMIT " + strconv.Itoa(currentpage) + "," + strconv.Itoa(pagesize)

	global.GVA_DB.Raw(sqlStr2).Scan(&data)

	return err, data, totalItem
}

func GetMobileUserInfo(id string) (error, *request.GetMobileUserListReply) {

	table := " sys_users as su " +
		" left join sys_user_authe as sua on su.id = sua.user_id and sua.delflag=0 " +
		" LEFT JOIN region as r on sua.hospital_province=r.region_id " +
		" LEFT JOIN region as r2 on sua.hospital_city=r2.region_id " +
		" LEFT JOIN region as r3 on sua.hospital_county=r3.region_id " +
		" LEFT JOIN vip_user as vu on su.id=vu.user_id "
	field := " su.id, su.mobile, su.created_at, sua.name, sua.phone, sua.working_years" +
		", sua.working_place, sua.position, r.region_name as province_name, r2.region_name as city_name" +
		", r3.region_name as county_name, sua.hospital_address, vu.update_time, vu.maturity_time" +
		", vu.vip_level "
	conditions := " AND su.id = " + id

	data := new(request.GetMobileUserListReply)

	sqlStr2 := "SELECT " + field +
		" FROM " + table +
		" where 1>0 " + conditions

	global.GVA_DB.Raw(sqlStr2).Find(&data)

	return nil, data
}
