package repository

import (
	"fmt"
	"strings"
	"time"

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

// 实例化数据层 SysTenantImpl 结构体
var NewSysTenantImpl = &SysTenantImpl{
	selectSql: `select 
		t.tenant_id, t.parent_id, t.ancestors, t.tenant_name, t.order_num, t.tenancy_type, t.tenancy_key, t.status, 
		t.del_flag, t.create_by, t.create_time 
		from sys_tenant t `,

	resultMap: map[string]string{
		"tenant_id":    "TenantID",
		"parent_id":    "ParentID",
		"ancestors":    "Ancestors",
		"tenant_name":  "TenantName",
		"order_num":    "OrderNum",
		"tenancy_type": "TenancyType",
		"tenancy_key":  "TenancyKey",
		"status":       "Status",
		"del_flag":     "DelFlag",
		"create_by":    "CreateBy",
		"create_time":  "CreateTime",
		"update_by":    "UpdateBy",
		"update_time":  "UpdateTime",
		"parent_name":  "ParentName",
	},
}

// SysTenantImpl 租户表 数据层处理
type SysTenantImpl struct {
	// 查询视图对象SQL
	selectSql string
	// 结果字段与实体映射
	resultMap map[string]string
}

// convertResultRows 将结果记录转实体结果组
func (r *SysTenantImpl) convertResultRows(rows []map[string]any) []model.SysTenant {
	arr := make([]model.SysTenant, 0)
	for _, row := range rows {
		sysTenant := model.SysTenant{}
		for key, value := range row {
			if keyMapper, ok := r.resultMap[key]; ok {
				repo.SetFieldValue(&sysTenant, keyMapper, value)
			}
		}
		arr = append(arr, sysTenant)
	}
	return arr
}

// SelectTenantList 查询租户管理数据
func (r *SysTenantImpl) SelectTenantList(sysTenant model.SysTenant, dataScopeSQL string) []model.SysTenant {
	// 查询条件拼接
	var conditions []string
	var params []any
	if sysTenant.TenantID != "" {
		conditions = append(conditions, "tenant_id = ?")
		params = append(params, sysTenant.TenantID)
	}
	if sysTenant.ParentID != "" {
		conditions = append(conditions, "parent_id = ?")
		params = append(params, sysTenant.ParentID)
	}
	if sysTenant.TenantName != "" {
		conditions = append(conditions, "tenant_name like concat(?, '%')")
		params = append(params, sysTenant.TenantName)
	}
	if sysTenant.Status != "" {
		conditions = append(conditions, "status = ?")
		params = append(params, sysTenant.Status)
	}

	// 构建查询条件语句
	whereSql := " where t.del_flag = '0' "
	if len(conditions) > 0 {
		whereSql += " and " + strings.Join(conditions, " and ")
	}

	// 查询数据
	orderSql := " order by t.parent_id, t.order_num asc "
	querySql := r.selectSql + whereSql + dataScopeSQL + orderSql
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		logger.Errorf("query err => %v", err)
		return []model.SysTenant{}
	}

	// 转换实体
	return r.convertResultRows(results)
}

// SelectTenantListByRoleId 根据角色ID查询租户树信息
func (r *SysTenantImpl) SelectTenantListByRoleId(roleId string, tenantCheckStrictly bool) []string {
	querySql := `select t.tenant_id as 'str' from sys_tenant t
		left join sys_role_tenant rt on t.tenant_id = rt.tenant_id
		where rt.role_id = ? and t.status = 1 `
	var params []any
	params = append(params, roleId)
	// 展开
	if tenantCheckStrictly {
		querySql += ` and t.tenant_id not in 
			(select t.parent_id from sys_tenant t
			inner join sys_role_tenant rt on t.tenant_id = rt.tenant_id 
			and rt.role_id = ?) `
		params = append(params, roleId)
	}
	querySql += "order by t.parent_id, t.order_num"

	// 查询结果
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		logger.Errorf("query err => %v", err)
		return []string{}
	}

	if len(results) > 0 {
		ids := make([]string, 0)
		for _, v := range results {
			ids = append(ids, fmt.Sprintf("%v", v["str"]))
		}
		return ids
	}
	return []string{}
}

// SelectTenantById 根据租户ID查询信息
func (r *SysTenantImpl) SelectTenantById(tenantId string) model.SysTenant {
	querySql := `select t.tenant_id, t.parent_id, t.ancestors,
		t.tenant_name, t.order_num, t.tenancy_type, t.tenancy_key, t.status,
		(select tenant_name from sys_tenant where tenant_id = t.parent_id and status = 1) parent_name
		from sys_tenant t where t.tenant_id = ? and t.del_flag = 0 `
	results, err := datasource.RawDB("", querySql, []any{tenantId})
	if err != nil {
		logger.Errorf("query err => %v", err)
		return model.SysTenant{}
	}
	// 转换实体
	rows := r.convertResultRows(results)
	if len(rows) > 0 {
		return rows[0]
	}
	return model.SysTenant{}
}

// SelectChildrenTenantById 根据ID查询所有子租户
func (r *SysTenantImpl) SelectChildrenTenantById(tenantId string) []model.SysTenant {
	querySql := r.selectSql + " where find_in_set(?, t.ancestors)"
	results, err := datasource.RawDB("", querySql, []any{tenantId})
	if err != nil {
		logger.Errorf("query err => %v", err)
		return []model.SysTenant{}
	}

	// 转换实体
	return r.convertResultRows(results)
}

// HasChildByTenantId 是否存在子节点
func (r *SysTenantImpl) HasChildByTenantId(tenantId string) int64 {
	querySql := "select count(1) as 'total' from sys_tenant where status = '1' and parent_id = ? limit 1"
	results, err := datasource.RawDB("", querySql, []any{tenantId})
	if err != nil {
		logger.Errorf("query err => %v", err)
		return 0
	}
	if len(results) > 0 {
		return parse.Number(results[0]["total"])
	}
	return 0
}

// CheckTenantExistUser 查询租户是否存在用户
func (r *SysTenantImpl) CheckTenantExistUser(tenantId string) int64 {
	querySql := "select count(1) as 'total' from sys_user where tenant_id = ? and del_flag = '0'"
	results, err := datasource.RawDB("", querySql, []any{tenantId})
	if err != nil {
		logger.Errorf("query err => %v", err)
		return 0
	}
	if len(results) > 0 {
		return parse.Number(results[0]["total"])
	}
	return 0
}

// CheckUniqueTenant 校验租户是否唯一
func (r *SysTenantImpl) CheckUniqueTenant(sysTenant model.SysTenant) string {
	// 查询条件拼接
	var conditions []string
	var params []any
	if sysTenant.TenantName != "" {
		conditions = append(conditions, "tenant_name = ?")
		params = append(params, sysTenant.TenantName)
	}
	if sysTenant.ParentID != "" {
		conditions = append(conditions, "parent_id = ?")
		params = append(params, sysTenant.ParentID)
	}

	// 构建查询条件语句
	whereSql := ""
	if len(conditions) > 0 {
		whereSql += " where " + strings.Join(conditions, " and ")
	}
	if whereSql == "" {
		return ""
	}

	// 查询数据
	querySql := "select tenant_id as 'str' from sys_tenant " + whereSql + " and del_flag = '0' limit 1"
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		logger.Errorf("query err %v", err)
		return ""
	}
	if len(results) > 0 {
		return fmt.Sprint(results[0]["str"])
	}
	return ""
}

// 校验租赁对象是否唯一
func (r *SysTenantImpl) IsUniqueTenancy(sysTenant model.SysTenant) bool {
	// 查询条件拼接
	var conditions []string
	var params []any

	if sysTenant.TenantID != "" {
		conditions = append(conditions, "tenant_id != ?")
		params = append(params, sysTenant.TenantID)
	}
	if sysTenant.TenancyType != "" {
		conditions = append(conditions, "tenancy_type = ?")
		params = append(params, sysTenant.TenancyType)
	}
	if sysTenant.TenancyKey != "" {
		conditions = append(conditions, "(? like tenancy_key or tenancy_key like ?)")
		//conditions = append(conditions, "(LOCATE(?, tenancy_key)>0 or LOCATE(tenancy_key, ?)>0)")
		params = append(params, sysTenant.TenancyKey, sysTenant.TenancyKey)
	}

	// 构建查询条件语句
	whereSql := ""
	if len(conditions) > 0 {
		whereSql += " where " + strings.Join(conditions, " and ")
	}
	if whereSql == "" {
		return true
	}

	// 查询数据
	querySql := "select 1 from sys_tenant " + whereSql + " and status = '1' and del_flag = '0' limit 1"
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		logger.Errorf("query err %v", err)
		return true
	}
	if len(results) > 0 {
		return false
	}
	return true
}

// InsertTenant 新增租户信息
func (r *SysTenantImpl) InsertTenant(sysTenant model.SysTenant) string {
	// 参数拼接
	params := make(map[string]any)
	if sysTenant.TenantID != "" {
		params["tenant_id"] = sysTenant.TenantID
	}
	if sysTenant.ParentID != "" {
		params["parent_id"] = sysTenant.ParentID
	}
	if sysTenant.TenantName != "" {
		params["tenant_name"] = sysTenant.TenantName
	} else {
		params["tenant_name"] = sysTenant.TenantName
	}
	if sysTenant.Ancestors != "" {
		params["ancestors"] = sysTenant.Ancestors
	}
	if sysTenant.OrderNum > 0 {
		params["order_num"] = sysTenant.OrderNum
	}
	if sysTenant.TenancyType != "" {
		params["tenancy_type"] = sysTenant.TenancyType
	}
	if sysTenant.TenancyKey != "" {
		params["tenancy_key"] = sysTenant.TenancyKey
	}
	if sysTenant.Status != "" {
		params["status"] = sysTenant.Status
	}
	if sysTenant.CreateBy != "" {
		params["create_by"] = sysTenant.CreateBy
		params["create_time"] = time.Now().UnixMilli()
	}

	// 构建执行语句
	keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
	sql := "insert into sys_tenant (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"

	db := datasource.DefaultDB()
	// 开启事务
	tx := db.Begin()
	// 执行插入
	err := tx.Exec(sql, values...).Error
	if err != nil {
		logger.Errorf("insert row : %v", err.Error())
		tx.Rollback()
		return ""
	}
	// 获取生成的自增 ID
	var insertedID string
	err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
	if err != nil {
		logger.Errorf("insert last id : %v", err.Error())
		tx.Rollback()
		return ""
	}
	// 提交事务
	tx.Commit()
	return insertedID
}

// UpdateTenant 修改租户信息
func (r *SysTenantImpl) UpdateTenant(sysTenant model.SysTenant) int64 {
	// 参数拼接
	params := make(map[string]any)
	if sysTenant.ParentID != "" {
		params["parent_id"] = sysTenant.ParentID
	}
	if sysTenant.TenantName != "" {
		params["tenant_name"] = sysTenant.TenantName
	}
	if sysTenant.Ancestors != "" {
		params["ancestors"] = sysTenant.Ancestors
	}
	if sysTenant.OrderNum > 0 {
		params["order_num"] = sysTenant.OrderNum
	}
	if sysTenant.TenancyType != "" {
		params["tenancy_type"] = sysTenant.TenancyType
	}
	if sysTenant.TenancyKey != "" {
		params["tenancy_key"] = sysTenant.TenancyKey
	}
	if sysTenant.Status != "" {
		params["status"] = sysTenant.Status
	}
	if sysTenant.UpdateBy != "" {
		params["update_by"] = sysTenant.UpdateBy
		params["update_time"] = time.Now().UnixMilli()
	}

	// 构建执行语句
	keys, values := repo.KeyValueByUpdate(params)
	sql := "update sys_tenant set " + strings.Join(keys, ",") + " where tenant_id = ?"

	// 执行更新
	values = append(values, sysTenant.TenantID)
	rows, err := datasource.ExecDB("", sql, values)
	if err != nil {
		logger.Errorf("update row : %v", err.Error())
		return 0
	}
	return rows
}

// UpdateTenantStatusNormal 修改所在租户正常状态
func (r *SysTenantImpl) UpdateTenantStatusNormal(tenantIds []string) int64 {
	placeholder := repo.KeyPlaceholderByQuery(len(tenantIds))
	sql := "update sys_tenant set status = '1' where tenant_id in (" + placeholder + ")"
	parameters := repo.ConvertIdsSlice(tenantIds)
	results, err := datasource.ExecDB("", sql, parameters)
	if err != nil {
		logger.Errorf("update err => %v", err)
		return 0
	}
	return results
}

// UpdateTenantChildren 修改子元素关系
func (r *SysTenantImpl) UpdateTenantChildren(sysTenants []model.SysTenant) int64 {
	// 无参数
	if len(sysTenants) == 0 {
		return 0
	}

	// 更新条件拼接
	var conditions []string
	var params []any
	for _, tenant := range sysTenants {
		caseSql := fmt.Sprintf("WHEN tenant_id = '%s' THEN '%s'", tenant.TenantID, tenant.Ancestors)
		conditions = append(conditions, caseSql)
		params = append(params, tenant.TenantID)
	}

	cases := strings.Join(conditions, " ")
	placeholders := repo.KeyPlaceholderByQuery(len(params))
	sql := "update sys_tenant set ancestors = CASE " + cases + " END where tenant_id in (" + placeholders + ")"
	results, err := datasource.ExecDB("", sql, params)
	if err != nil {
		logger.Errorf("delete err => %v", err)
		return 0
	}
	return results
}

// DeleteTenantById 删除租户管理信息
func (r *SysTenantImpl) DeleteTenantById(tenantId string) int64 {
	sql := "update sys_tenant set status = '0', del_flag = '1' where tenant_id = ?"
	results, err := datasource.ExecDB("", sql, []any{tenantId})
	if err != nil {
		logger.Errorf("delete err => %v", err)
		return 0
	}
	return results
}

// DeleteTenantById 删除租户管理信息
func (r *SysTenantImpl) UpdateUDMSubTenantID(tenantId, assetKey string) int64 {
	sql := "update u_sub_user set tenant_id = ? where imsi like ?"
	results, err := datasource.ExecDB("", sql, []any{tenantId, assetKey})
	if err != nil {
		logger.Errorf("update err: %v", err)
		return 0
	}
	return results
}
