package service

import (
	"Xcx_New/models"
	"Xcx_New/utils"

	"github.com/jinzhu/gorm"
)

func IsSuperAdmin(mobile string) bool {
	var count int
	readUserDb.Model(&models.AdminUser{}).Where("mobile = ? AND is_super_admin = 1 AND status = 1", mobile).Count(&count)
	return count == 1
}

func GetValidAdminUserByMobileReturnErr(mobile string) (*models.AdminUser, error) {
	var user models.AdminUser
	err := readUserDb.Where("mobile = ? AND status = 1", mobile).First(&user).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &user, nil
}

func DidAdminUserCreateOrg(adminUserID int64) (bool, error) {
	var count int
	err := readUserDb.Model(&models.Org{}).Where("creator = ? AND status <> 0", adminUserID).Count(&count).Error
	return count > 0, err
}

func DidAdminUserOrgCreateApp(adminUserID int, appType int) (bool, error) {
	var count int
	db := readUserDb.Model(&models.OrgApp{}).Where("creator = ? AND status = 1 AND open_status = 1", adminUserID)
	if appType != 0 {
		db = db.Where("app_type = ?", appType)
	}
	err := db.Count(&count).Error
	return count > 0, err
}

func GetAdminUserLastLoginLog(adminUserID int, appType int) (*models.AdminUserLoginLog, error) {
	var record models.AdminUserLoginLog
	var err error
	if appType > 0 {
		err = readUserDb.Last(&record, "admin_user_id = ? AND operate_type <> 2 AND app_type = ?", adminUserID, appType).Error
	} else {
		err = readUserDb.Last(&record, "admin_user_id = ? AND operate_type <> 2", adminUserID).Error
	}

	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	return &record, err
}

func GetAdminUserPrioritizedAppType(adminUserID int) (int8, error) {
	rows, err := readUserDb.Raw("SELECT app.app_type FROM sgj_user_org_app AS app, sgj_user_admin_role AS r WHERE r.admin_user_id = ? AND r.app_id = app.id AND app.status = 1 AND app.open_status = 1 AND r.status = 1 ORDER BY app.org_id ASC, app.app_type ASC LIMIT 1;", adminUserID).Rows()
	defer rows.Close()
	if err != nil {
		return 0, err
	} else {
		if rows.Next() {
			var appType int8
			rows.Scan(&appType)
			return appType, nil
		} else {
			return 0, nil
		}
	}
}

func GetAdminUserAllOrgWithUID(adminUserID int, isSuperAdmin bool) ([]*models.Org, error) {
	if isSuperAdmin {
		var org models.Org
		err := readUserDb.Preload("OrgGallery", "status = 1").Where("creator = ? AND status <> 0", adminUserID).First(&org).Error
		if err != nil {
			return nil, err
		}
		return []*models.Org{&org}, nil

	} else {
		rows, err := readUserDb.Raw("SELECT org.*, COUNT(DISTINCT org.id) FROM sgj_user_admin_role AS u_r, sgj_user_org AS org WHERE u_r.admin_user_id = ? AND u_r.org_id = org.id AND u_r.status = 1 AND org.status <> 0 GROUP BY org.id ORDER BY org.id;", adminUserID).Rows()
		defer rows.Close()
		if err != nil {
			return nil, err
		} else {
			orgs := make([]*models.Org, 0)
			for rows.Next() {
				var org models.Org
				if scanErr := readUserDb.Preload("OrgGallery", "status = 1").ScanRows(rows, &org); scanErr != nil {
					return nil, scanErr

				} else {
					orgs = append(orgs, &org)
				}
			}
			return orgs, nil
		}
	}
}

func GetAdminUserAllOrgApp(adminUserID int, orgID int) ([]*models.OrgApp, error) {
	rows, err := readUserDb.Raw("SELECT app.* from sgj_user_admin_role AS u_r, sgj_user_org_app AS app WHERE u_r.admin_user_id = ? AND u_r.org_id = ? AND u_r.app_id = app.id AND u_r.status = 1 AND app.status = 1 ORDER BY app_type ASC;", adminUserID, orgID).Rows()
	defer rows.Close()
	if err != nil {
		return nil, err
	} else {
		apps := make([]*models.OrgApp, 0)
		for rows.Next() {
			var app models.OrgApp
			if scanErr := readUserDb.ScanRows(rows, &app); scanErr != nil {
				return nil, scanErr
			} else {
				apps = append(apps, &app)
			}
		}
		return apps, nil
	}
}

func InsertLoginLog(loginLog *models.AdminUserLoginLog) error {
	tx := writeUserDb.Begin()
	if err := tx.Create(loginLog).Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}

//func GetAppRole(adminUserID int, orgID int, appID int) (*models.App_Role, error) {
//	var appRole models.App_Role
//	err := readUserDb.Where("admin_user_id = ? AND org_id = ? AND app_id = ? AND status = 1", adminUserID, orgID, appID).First(&appRole).Error
//	if err != nil {
//		return nil, err
//	}
//	return &appRole, nil
//}

// 获取最近被创建的血透系统管理员角色（AppType为3）
func GetLastXTAdminRole(adminUserID int64, appType int) (*models.App_Role, error) {
	var appRole models.App_Role
	// 	select a_r.* from sgj_user_admin_role as a_r
	// join sgj_user_admin as a on a.id = a_r.admin_user_id
	// join sgj_user_org_app as app on app.id = a_r.app_id and app.status = 1 and app.app_type = 3
	// where a_r.status = 1 and a_r.admin_user_id = 380
	err := readUserDb.Table("sgj_user_admin_role").
		Select("sgj_user_admin_role.*").
		Joins("join sgj_user_admin as a on a.id = sgj_user_admin_role.admin_user_id").
		Joins("join sgj_user_org_app as app on app.id = sgj_user_admin_role.app_id and app.status = 1 and app.app_type = ?", appType).
		Where("sgj_user_admin_role.status = 1 and sgj_user_admin_role.admin_user_id = ?", adminUserID).
		Order("sgj_user_admin_role.id desc").
		First(&appRole).
		Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &appRole, nil
}

func GetOrgById(orgID int64) (*models.Org, error) {
	var org models.Org
	err := readUserDb.Model(&models.Org{}).Where("id = ?", orgID).First(&org).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &org, nil
}

func GetAppById(appID int64) (*models.OrgApp, error) {
	var app models.OrgApp
	err := readUserDb.Model(&models.OrgApp{}).Where("id = ?", appID).First(&app).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &app, nil
}

func GetOrgServeSubscibe(orgID int64) (*models.ServeSubscibe, error) {
	var model models.ServeSubscibe
	err := readUserDb.Model(&models.ServeSubscibe{}).Where("org_id = ? AND status = 1", orgID).First(&model).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &model, nil
}

//
func GetAppRoleById(id int64) (*models.App_Role, error) {
	var model models.App_Role
	err := readUserDb.Model(&models.App_Role{}).Where("id = ? AND status = 1", id).First(&model).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &model, nil
}

func IsMobileRegister(mobile string) bool {
	var count int
	err := readUserDb.
		Model(&models.AdminUser{}).
		Where("mobile = ?", mobile).
		Count(&count).
		Error
	if err != nil {
		utils.ErrorLog("判断手机号是否被注册时失败: %v", err)
		return true
	}
	return count > 0
}

func FindAppRoleById(id int64) (*models.App_Role, error) {
	var model models.App_Role
	err := readUserDb.Model(&models.App_Role{}).Where("id = ? ", id).First(&model).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &model, nil
}
