package repository

import (
	"fmt"
	"strings"

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

// 实例化数据层 UDMVolteIMSUser 结构体
var NewUDMVolteIMSUser = &UDMVolteIMSUser{}

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

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

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

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

	// 查询数量 长度为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("imsi asc")
	}

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

	return rows, total
}

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

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

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

// Insert 批量添加
func (r UDMVolteIMSUser) Inserts(uArr []model.UDMVolteIMSUser) 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 UDMVolteIMSUser) Delete(imsi, neId string) int64 {
	tx := db.DB("").Where("imsi = ? and ne_id = ?", imsi, neId).Delete(&model.UDMVolteIMSUser{})
	if err := tx.Error; err != nil {
		logger.Errorf("Delete err => %v", err)
	}
	return tx.RowsAffected
}

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