package service

import (
	"strings"

	"be.ems/features/udm_user/model"
	"be.ems/src/framework/redis"
)

// phoneImsiList 获取所有imsi
// func phoneImsiList() map[string]string {
// 	phoneAndImsiArr := make(map[string]string, 0)
// 	phoneKeys, err := redis.GetKeys("udmuser", "1*********")
// 	if err != nil {
// 		return phoneAndImsiArr
// 	}
// 	for _, phone := range phoneKeys {
// 		imsi, err := redis.Get("udmuser", phone)
// 		if err != nil {
// 			continue
// 		}
// 		phoneAndImsiArr[phone] = imsi
// 	}
// 	return phoneAndImsiArr
// }

// redisUdmAuthUserList UDM鉴权用户
func redisUdmAuthUserList() []model.UdmAuthUser {
	user := []model.UdmAuthUser{}
	ausfArr, err := redis.GetKeys("udmuser", "ausf:*")
	if err != nil {
		return user
	}
	for _, key := range ausfArr {
		m, err := redis.GetHash("udmuser", key)
		if err != nil {
			continue
		}

		// 跳过-号数据
		imsi := key[5:]
		if strings.Contains(imsi, "-") {
			continue
		}

		status := "0"
		if _, ok := m["auth_success"]; ok {
			status = "1"
		}
		amf := ""
		if v, ok := m["amf"]; ok {
			amf = strings.Replace(v, "\r\n", "", 1)
		}
		a := model.UdmAuthUser{
			Imsi:      imsi,
			Amf:       amf,
			Status:    status,
			Ki:        m["ki"],
			AlgoIndex: m["algo"],
			Opc:       m["opc"],
		}
		user = append(user, a)
	}
	return user
}

// redisUdmSubUserList UDM签约用户
func redisUdmSubUserList() []model.UdmSubUser {
	user := []model.UdmSubUser{}
	udmsdArr, err := redis.GetKeys("udmuser", "udm-sd:*")
	if err != nil {
		return user
	}
	for _, key := range udmsdArr {
		m, err := redis.GetHash("udmuser", key)
		if err != nil {
			continue
		}

		a := model.UdmSubUser{
			Imsi:   key[7:],
			Msisdn: m["gpsi"], // 46003550072 strings.TrimPrefix(m["gpsi"], "86"),
			SmfSel: m["smf-sel"],
			SmData: m["sm-dat"], // 1-000001&cmnet&ims&3gnet
		}

		// def_ambr,def_nssai,0,def_arfb,def_sar,3,1,12000,1,1000,0,1,-
		if v, ok := m["am-dat"]; ok {
			arr := strings.Split(v, ",")
			a.Ambr = arr[0]
			a.Nssai = arr[1]
			a.Rat = arr[2]
			a.Arfb = arr[3]
			a.Sar = arr[4]
			a.Cn = arr[5]
		}
		// 1,64,24,65,def_eps,1,2,010200000000,-
		if v, ok := m["eps-dat"]; ok {
			arr := strings.Split(v, ",")
			// 跳过非常规数据
			if len(arr) > 9 {
				continue
			}
			a.EpsDat = v
			a.EpsFlag = arr[0]
			a.EpsOdb = arr[1]
			a.HplmnOdb = arr[2]
			a.Ard = arr[3]
			a.Epstpl = arr[4]
			a.ContextId = arr[5]
			a.ApnContext = arr[7]
			// [6] 是不要的，导入和导出不用
			a.StaticIp = arr[8]
		}

		user = append(user, a)
	}
	return user
}
