package dao

import (
	"errors"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/model"
)

func GetAuthBind(db *DaoDB, bindType int, authType, authID string) (authBind *model.AuthBind, err error) {
	if bindType == model.AuthBindTypeAll || authType == "" || authID == "" {
		return nil, errors.New("bindType不是能all, authType和authID都要有值")
	}
	sql := `
	SELECT *
	FROM auth_bind t1
	WHERE t1.deleted_at = ? AND t1.status = ? AND t1.bind_type = ? AND t1.type = ? AND t1.auth_id = ?`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
		model.AuthBindStatusNormal,
		bindType,
		authType,
		authID,
	}
	err = GetRow(db, &authBind, sql, sqlParams...)
	return authBind, err
}

func GetUserBindAuthInfo(db *DaoDB, userID string, bindType int, typeList []string, authID, authID2 string, typeIDs []string) (authList []*model.AuthBind, err error) {
	sql := `
	SELECT *
	FROM auth_bind t1
	WHERE t1.deleted_at = ? AND t1.status = ?`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
		model.UserStatusNormal,
	}
	if userID != "" {
		sql += " AND t1.user_id = ?"
		sqlParams = append(sqlParams, userID)
	}
	if bindType != model.AuthBindTypeAll {
		sql += " AND t1.bind_type = ?"
		sqlParams = append(sqlParams, bindType)
	}

	if len(typeList) > 0 {
		sql += " AND t1.type IN (" + GenQuestionMarks(len(typeList)) + ")"
		sqlParams = append(sqlParams, typeList)
	}
	if authID != "" {
		sql += " AND t1.auth_id = ?"
		sqlParams = append(sqlParams, authID)
	}
	if authID2 != "" {
		sql += " AND t1.auth_id2 = ?"
		sqlParams = append(sqlParams, authID2)
	}
	if len(typeIDs) > 0 {
		sql += " AND t1.type_id IN (" + GenQuestionMarks(len(typeIDs)) + ")"
		sqlParams = append(sqlParams, typeIDs)
	}
	sql += " ORDER BY t1.type"
	err = GetRows(db, &authList, sql, sqlParams...)
	return authList, err
}
