package manager_service

import (
	"bwallet/models"
	"bwallet/pkg/util"
	"time"
)

type Manager struct {
	Uid           int32
	UserName      string
	Password      string
	Salt          string
	RegTime       int64
	LastLoginTime int64
	RegIp         uint32
	LastLoginIp   uint32
	Status        uint8
	Group         string
	PlatformId    int32

	PageNum  int
	PageSize int
}

func (m *Manager) GetManager() (*models.Manager, error) {
	manager, err := models.GetManager(m.Uid)
	if err != nil {
		return nil, err
	}

	return manager, nil
}

func (m *Manager) GetAll() ([]*models.ManagerSearch, error) {
	var manager []*models.Manager

	manager, err := models.GetManagers(m.PageNum, m.PageSize, m.getMaps())
	if err != nil {
		return nil, err
	}

	var tmp []*models.ManagerSearch
	for _, value := range manager {
		ip_reg, _ := util.Long2IPString(uint(value.RegIp))
		ip_login, _ := util.Long2IPString(uint(value.LastLoginIp))

		m := &models.ManagerSearch{}
		m.Uid = value.Uid
		m.Username = value.Username
		m.PlatformId = value.PlatformId
		m.Status = value.Status
		m.Group = value.Group
		m.RegIp = ip_reg
		m.LastLoginIp = ip_login
		m.RegTime = time.Unix(value.RegTime, 0).Format("2006-01-02 15:04:05")
		m.LastLoginTime = time.Unix(value.LastLoginTime, 0).Format("2006-01-02 15:04:05")
		tmp = append(tmp, m)
	}

	return tmp, nil
}

func (m *Manager) Add() error {
	manager := map[string]interface{}{
		"username":      m.UserName,
		"password":      m.Password,
		"reg_ip":        m.RegIp,
		"last_login_ip": m.LastLoginIp,
		"group":         m.Group,
		"platform_id":   m.PlatformId,
	}

	if err := models.AddManager(manager); err != nil {
		return err
	}

	return nil
}

func (m *Manager) Edit() error {
	return models.EditManager(m.Uid, map[string]interface{}{
		"status": m.Status,
	})
}

func (m *Manager) ExistById() (bool, error) {
	return models.ExistManagerById(m.Uid)
}

func (m *Manager) Count() (int, error) {
	return models.GetManagerTotal(m.getMaps())
}

func (m *Manager) Delete() error {
	return models.DeleteManager(m.Uid)
}

func (m *Manager) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if m.Uid != 0 {
		maps["uid"] = m.Uid
	}

	if m.PlatformId != 0 {
		maps["platform_id"] = m.PlatformId
	}

	if m.Status != 0 {
		maps["status"] = m.Status
	}

	if m.UserName != "" {
		maps["username"] = m.UserName
	}

	if m.Group != "" {
		maps["group"] = m.Group
	}

	return maps
}
