package repository

import (
	"fmt"
	"strings"

	"be.ems/src/framework/database/db"
	"be.ems/src/framework/logger"
	"be.ems/src/modules/ne_data/model"
)

// 实例化数据层 UDMVOIPUser 结构体
var NewUDMVOIPUser = &UDMVOIPUser{}

// UDMVOIPUser UDMVOIP用户信息表 数据层处理
type UDMVOIPUser struct{}

// ClearAndInsert 清空ne_id后新增实体
func (r UDMVOIPUser) ClearAndInsert(neId string, uArr []model.UDMVOIPUser) int64 {
	// 不指定neID时，用 TRUNCATE 清空表快
	// _, err := datasource.ExecDB("", "TRUNCATE TABLE udm_voip", nil)
	result := db.DB("").Where("ne_id = ?", neId).Unscoped().Delete(&model.UDMVOIPUser{})
	if result.Error != nil {
		logger.Errorf("Delete err => %v", result.Error)
	}
	return r.Inserts(uArr)
}

// SelectPage 根据条件分页查询
func (r UDMVOIPUser) SelectPage(query map[string]string) ([]model.UDMVOIPUser, int64) {
	tx := db.DB("").Model(&model.UDMVOIPUser{})
	// 查询条件拼接
	if v, ok := query["username"]; ok && v != "" {
		tx = tx.Where("username like ?", fmt.Sprintf("%%%s%%", v))
	}
	if v, ok := query["neId"]; ok && v != "" {
		tx = tx.Where("ne_id = ?", v)
	}
	if v, ok := query["usernames"]; ok && v != "" {
		arr := strings.Split(v, ",")
		tx = tx.Where("username in ?", arr)
		// 勾选时，pageSize为勾选的数量
		query["pageSize"] = fmt.Sprint(len(arr))
	}

	var total int64 = 0
	rows := []model.UDMVOIPUser{}

	// 查询数量 长度为0直接返回
	if err := tx.Count(&total).Error; err != nil || total <= 0 {
		return rows, total
	}

	// 分页
	pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
	tx = tx.Offset(int(pageNum * pageSize)).Limit(int(pageSize))

	// 排序
	if v, ok := query["sortField"]; ok && v != "" {
		sortSql := v
		if o, ok := query["sortOrder"]; ok && o != "" {
			if o == "desc" {
				sortSql += " desc "
			} else {
				sortSql += " asc "
			}
		}
		tx = tx.Order(sortSql)
	} else {
		tx = tx.Order("username asc")
	}

	// 查询数据
	if err := tx.Find(&rows).Error; err != nil {
		logger.Errorf("query err => %v", err)
	}

	return rows, total
}

// SelectList 根据实体查询
func (r UDMVOIPUser) SelectList(u model.UDMVOIPUser) []model.UDMVOIPUser {
	tx := db.DB("").Model(&model.UDMVOIPUser{})
	// 查询条件拼接
	if u.UserName != "" {
		tx = tx.Where("username = ?", u.UserName)
	}
	if u.NeId != "" {
		tx = tx.Where("ne_id = ?", u.NeId)
	}

	// 查询数据
	arr := []model.UDMVOIPUser{}
	if err := tx.Order("username asc").Find(&arr).Error; err != nil {
		logger.Errorf("query err => %v", err)
	}
	return arr
}

// SelectByUserNameAndNeID 通过username和ne_id查询
func (r UDMVOIPUser) SelectByUserNameAndNeID(username, neId string) model.UDMVOIPUser {
	tx := db.DB("").Model(&model.UDMVOIPUser{})
	item := model.UDMVOIPUser{}
	// 查询条件拼接
	tx = tx.Where("username = ? and ne_id = ?", username, neId)
	// 查询数据
	if err := tx.Order("username asc").Limit(1).Find(&item).Error; err != nil {
		logger.Errorf("query err => %v", err)
	}
	return item
}

// Insert 批量添加
func (r UDMVOIPUser) Inserts(uArr []model.UDMVOIPUser) int64 {
	tx := db.DB("").CreateInBatches(uArr, 500)
	if err := tx.Error; err != nil {
		logger.Errorf("CreateInBatches err => %v", err)
	}
	return tx.RowsAffected
}

// Delete 删除实体
func (r UDMVOIPUser) Delete(username, neId string) int64 {
	tx := db.DB("").Where("username = ? and ne_id = ?", username, neId).Delete(&model.UDMVOIPUser{})
	if err := tx.Error; err != nil {
		logger.Errorf("Delete err => %v", err)
	}
	return tx.RowsAffected
}

// DeletePrefixByUserName 删除前缀匹配的实体
func (r UDMVOIPUser) DeletePrefixByUserName(username, neId string) int64 {
	tx := db.DB("").Where("username like ? and ne_id = ?", fmt.Sprintf("%s%%", username), neId).Delete(&model.UDMVOIPUser{})
	if err := tx.Error; err != nil {
		logger.Errorf("DeletePrefixByUserName err => %v", err)
	}
	return tx.RowsAffected
}
