package repository

import (
	"fmt"
	"strings"

	"be.ems/src/framework/datasource"
	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/repo"
	"be.ems/src/modules/system/model"
)

// 实例化数据层 SysRoleTenantImpl 结构体
var NewSysRoleTenantImpl = &SysRoleTenantImpl{}

// SysRoleTenantImpl 角色与部门关联表 数据层处理
type SysRoleTenantImpl struct{}

// DeleteRoleTenant 批量删除角色部门关联信息
func (r *SysRoleTenantImpl) DeleteRoleTenant(roleIds []string) int64 {
	placeholder := repo.KeyPlaceholderByQuery(len(roleIds))
	sql := "delete from sys_role_tenant where role_id in (" + placeholder + ")"
	parameters := repo.ConvertIdsSlice(roleIds)
	results, err := datasource.ExecDB("", sql, parameters)
	if err != nil {
		logger.Errorf("delete err => %v", err)
		return 0
	}
	return results
}

// DeleteTenantRole 批量删除部门角色关联信息
func (r *SysRoleTenantImpl) DeleteTenantRole(tenantIds []string) int64 {
	placeholder := repo.KeyPlaceholderByQuery(len(tenantIds))
	sql := "delete from sys_role_tenant where tenant_id in (" + placeholder + ")"
	parameters := repo.ConvertIdsSlice(tenantIds)
	results, err := datasource.ExecDB("", sql, parameters)
	if err != nil {
		logger.Errorf("delete err => %v", err)
		return 0
	}
	return results
}

// BatchRoleTenant 批量新增角色部门信息
func (r *SysRoleTenantImpl) BatchRoleTenant(sysRoleTenants []model.SysRoleTenant) int64 {
	keyValues := make([]string, 0)
	for _, item := range sysRoleTenants {
		keyValues = append(keyValues, fmt.Sprintf("(%s,%s)", item.RoleID, item.TenantID))
	}
	sql := "insert into sys_role_tenant(role_id, tenant_id) values " + strings.Join(keyValues, ",")
	results, err := datasource.ExecDB("", sql, nil)
	if err != nil {
		logger.Errorf("delete err => %v", err)
		return 0
	}
	return results
}
