package auth

// var AuthAccounts = make(map[string]string)

/* 20230419 pms 删除 =======================================================================================================
// Login 登录认证
// @tags PBX-Auth
// @Summary 登录认证
// @Description 获取登录参数(账号，密码，角色) 与数据库数据对比，认证通过返回 jwt token
// @Accept  json
// @Produce  json
// @Param   data body  commonModel.UserInfoReqVO  true "登录信息"
// @Router /pbx/auth/login [post]
func Login(ctx *gin.Context) {
	var userReqInfo commonModel.UserInfoReqVO
	if err := ctx.ShouldBindJSON(&userReqInfo); err != nil {
		api.Error(ctx, http.StatusBadRequest, err.Error())
		return
	}
	lfshook.NewLogger().Infof("user input info: %+v", userReqInfo)

	var info *commonModel.UserInfoVO

	// 用户名转换成分机号(数字)
	var err error
	result := utils.IsDigit(userReqInfo.UserName)
	if !result {
		// 用户登录
		lfshook.NewLogger().Info("login by user")
		info, err = services.AuthUser(userReqInfo.UserName, userReqInfo.Password)
	} else {
		// 分机登录
		lfshook.NewLogger().Info("login by digital")
		info, err = services.AuthDigital(userReqInfo.UserName, userReqInfo.Password)
	}

	if err != nil {
		weblog.AuthError(ctx.ClientIP(), err.Error())
		api.Error(ctx, http.StatusBadRequest, err.Error())
		return
	}

	exp := time.Now().Add(time.Duration(time.Hour * 24 * 31)).Unix()
	claim := commonModel.JWTCustomClaims{
		ID:        info.ID,
		UserName:  info.UserName,
		Role:      info.Role,
		Extension: info.Exten,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: exp,
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenString, err := token.SignedString([]byte(configs.ConfigGlobal.IdentityKey))
	if err != nil {
		lfshook.NewLogger().Error(err)
		api.Error(ctx, http.StatusBadRequest, "signed failure")
		return
	}
	api.Success(ctx, fmt.Sprintf("Bearer %s", tokenString))
}
* ========================================================================================================================= */
/* 20250102 删除 =======================================================================================================
// // AddAuth pms用户认证
// // @tags PBX-Auth
// // @Summary pms用户认证
// // @Description 从t_user表中抽出数据，添加到用户认证
// // @Security ApiKeyAuth

// func AddAuth() {
// 	// 取表 t_user 中用户
// 	/*var dbUser []commonModel.User
// 	if err := mysql.DBOrmInstance.Find(&dbUser); err != nil {
// 		lfshook.NewLogger().Error(err)
// 	}
// 	for _, item := range dbUser {
// 		AuthAccounts[item.UserName] = item.PassWord
// 	}
// 	fmt.Printf("extenList=%s\n", AuthAccounts)*/

// 	// 设计变更
// 	// 读取pms配置文件中的用户密码
// 	confPath := "/etc/asterisk/pms_api.conf"
// 	cfg, err := ini.Load(confPath)
// 	if err != nil {
// 		lfshook.NewLogger().Error(err)
// 		return
// 	}
// 	UserName := cfg.Section("general").Key("username").String()
// 	PassWord := cfg.Section("general").Key("password").String()
// 	if UserName == "" || PassWord == "" {
// 		lfshook.NewLogger().Error("/etc/asterisk/pms_api.conf not set username or password")
// 		return
// 	}
// 	AuthAccounts[UserName] = PassWord
// 	// fmt.Printf("extenList=%s\n", AuthAccounts)
// }
// * ========================================================================================================================= */

/* 20250102 删除 =======================================================================================================
// VtigerAddAuth vtiger用户认证
// @tags PBX-Auth
// @Summary vtiger用户认证
// @Description 从配置文件中取出数据，添加到用户认证
// @Security ApiKeyAuth

func VtigerAddAuth() {
	// 读取vtiger配置文件中的用户密码
	// confPath := "/etc/asterisk/vtiger_api.conf"
	confPath := "/etc/asterisk/crm_api.conf"
	cfg, err := ini.Load(confPath)
	if err != nil {
		lfshook.NewLogger().Error(err)
		return
	}
	BasicAuthUser := cfg.Section("general").Key("vtigerBasicAuthUser").String()
	BasicAuthPWD := cfg.Section("general").Key("vtigerBasicAuthPWD").String()
	ApiKey := cfg.Section("general").Key("vtigerApiKey").String()
	ApiKeyValue := cfg.Section("general").Key("vtigerApiKeyValue").String()
	if (BasicAuthUser == "" || BasicAuthPWD == "") && (ApiKey == "" || ApiKeyValue == "") {
		lfshook.NewLogger().Error("/etc/asterisk/crm_api.conf not set vtigerBasicAuth or vtigerApiKey")
		return
	}
	AuthAccounts[BasicAuthUser] = BasicAuthPWD
	AuthAccounts[ApiKey] = ApiKeyValue
	// fmt.Printf("AuthAccounts=%s\n", AuthAccounts)
}

// ZohoAddAuth zoho用户认证
// @tags PBX-Auth
// @Summary zoho用户认证
// @Description 从配置文件中取出数据，添加到用户认证
// @Security ApiKeyAuth

func ZohoAddAuth() {
	// 读取vtiger配置文件中的用户密码
	// confPath := "/etc/asterisk/vtiger_api.conf"
	confPath := "/etc/asterisk/crm_api.conf"
	cfg, err := ini.Load(confPath)
	if err != nil {
		lfshook.NewLogger().Error(err)
		return
	}
	BasicAuthUser := cfg.Section("general").Key("zohoBasicAuthUser").String()
	BasicAuthPWD := cfg.Section("general").Key("zohoBasicAuthPWD").String()
	if BasicAuthUser == "" || BasicAuthPWD == "" {
		lfshook.NewLogger().Error("/etc/asterisk/crm_api.conf not set zohoBasicAuthUser or zohoBasicAuthPWD")
		return
	}
	AuthAccounts[BasicAuthUser] = BasicAuthPWD
	// fmt.Printf("AuthAccounts=%s\n", AuthAccounts)
}

// * ========================================================================================================================= */

/* 20230419 pms 删除 =======================================================================================================
// Logout 注销登录
// @tags PBX-Auth
// @Summary 注销登录
// @Description 将 token 写入 redis, 标记注销。此 token 认证失效。
// @Security ApiKeyAuth
// @Accept  json
// @Produce  json
// @Router /pbx/auth/logout [get]
func Logout(ctx *gin.Context) {
	ID, _ := ctx.Get("ID")
	UserName, _ := ctx.Get("UserName")
	authorization := ctx.GetHeader("Authorization")
	auth.Logout(authorization)
	api.Success(ctx, map[string]string{"ID": strconv.FormatInt(ID.(int64), 10), "UserName": UserName.(string)})
}

// CurrentUser 当前用户
// @tags PBX-Auth
// @Summary 当前用户
// @Description 获取当前用户信息ID UserName Password Role UserExtension(关联的分机号) PanelQueueuNumber(关联的随机一个队列号)
// @Security ApiKeyAuth
// @Accept  json
// @Produce  json
// @Router /pbx/auth/currentuser [get]
func CurrentUser(ctx *gin.Context) {
	ID, _ := ctx.Get("ID")
	if ID == nil {
		lfshook.NewLogger().Error("currentUser get no not found")
		api.Error(ctx, http.StatusInternalServerError, "not found id")
		return
	}
	idInt64 := ID.(int64)
	lfshook.NewLogger().Infof("currentUser id: %d", idInt64)
	dbUser := mysql.GetUserInfoByID(idInt64)

	// 根据分机号查询关联队列
	data, err := mysql.DBOrmInstance.SQL("select queue_name from t_queue_agent where exten = ? and agent_type='static'", dbUser.UserExtension).QueryString()
	if err != nil {
		lfshook.NewLogger().Errorf("currentUser get queue %+v", err)
	}
	if len(data) > 0 {
		dbUser.PanelQueueNumber = data[0]["queue_name"]
	}
	api.Success(ctx, dbUser)
}

// @tags PBX-Auth
// @Summary 更新密码
// @Description 更新当前用户密码
// @Security ApiKeyAuth
// @Accept  json
// @Produce  json
// @Router /pbx/auth/update-password [post]
func UpdatePassword(ctx *gin.Context) {
	var info commonModel.UserPasswordVO
	if err := ctx.ShouldBind(&info); err != nil {
		api.Error(ctx, http.StatusBadRequest, err.Error())
		return
	}
	ID, _ := ctx.Get("ID")
	if ID == nil {
		lfshook.NewLogger().Error("currentUser get no not found")
		api.Error(ctx, http.StatusInternalServerError, "not found id")
		return
	}
	idInt64 := ID.(int64)
	user := commonModel.User{ID: idInt64}
	exist, err := mysql.DBOrmInstance.Get(&user)
	if err != nil {
		api.Error(ctx, http.StatusInternalServerError, err.Error())
		return
	}
	if !exist {
		api.Error(ctx, http.StatusInternalServerError, "not found user by id "+strconv.FormatInt(idInt64, 10))
		return
	}
	if user.PassWord != info.OldPassWord {
		api.Error(ctx, http.StatusInternalServerError, "old password error")
		return
	}
	user.PassWord = info.NewPassWord
	_, err = mysql.DBOrmInstance.ID(idInt64).Cols("password").Update(&user)
	if err != nil {
		api.Error(ctx, http.StatusInternalServerError, err.Error())
		return
	}
	api.Success(ctx, "success")
}
* ========================================================================================================================= */
