/*
 * @description: 管理员数据处理
 * @Author: CP
 * @Date: 2020-08-20 17:08:38
 * @FilePath: \construction_management\services\manager_service.go
 */
package services

import (
	"strconv"

	"go.mod/comm"
	"go.mod/conf"
	"go.mod/dao"
	"go.mod/datasource"
	"go.mod/models"
	"go.mod/web/viewmodels"
)

//定义管理员Service接口
type ManagerService interface {
	GetAll() (dataList []viewmodels.Manager, total int64)
	CountAll() int64
	Get(id int) *viewmodels.Manager
	Update(data *models.CmManager, columns []string) error
	Create(data *models.CmManager) error
	Enable(id int, canLogin int) error
}

//返回service操作类
type managerService struct {
	dao *dao.ManagerDao
}

//创建管理员service
func NewManagerService() ManagerService {
	return &managerService{
		dao: dao.NewManagerDao(datasource.InstanceDbMaster()),
	}
}

//实现getall接口
func (s *managerService) GetAll() (dataList []viewmodels.Manager, total int64) {

	datalist := make([]viewmodels.Manager, 0)
	result, total := s.dao.GetAll()
	for _, item := range result {
		projectVM := makeManagerVM(&item)
		datalist = append(datalist, projectVM)
	}
	return dataList, total
}

func (s *managerService) CountAll() int64 {
	return s.dao.CountAll()
}

// 获得管理员详情
func (s *managerService) Get(id int) *viewmodels.Manager {
	result := s.dao.Get(id)
	data := makeManagerVM(result)
	return &data
}

func (s *managerService) Enable(id int, canLogin int) error {
	Manager := models.CmManager{}
	Manager.Id = id
	Manager.CanLogin = canLogin
	err := s.dao.Update(&Manager, []string{"CanLogin"})

	return err
}

func (s *managerService) Update(data *models.CmManager, columns []string) error {
	return s.dao.Update(data, columns)
}
func (s *managerService) Create(data *models.CmManager) error {
	return s.dao.Create(data)
}

// 构造视图层models
func makeManagerVM(projectCM *models.CmManager) viewmodels.Manager {
	modelsVM := viewmodels.Manager{}
	id, _ := comm.AesEncrypt(strconv.Itoa(projectCM.Id), conf.SignSecret)
	// userId, _ := comm.AesEncrypt(strconv.Itoa(projectCM.UserId), conf.SignSecret)

	modelsVM.Id = id
	modelsVM.Username = projectCM.Username
	modelsVM.Category = projectCM.Category
	modelsVM.GroupId = projectCM.GroupId
	modelsVM.RealName = projectCM.RealName
	modelsVM.Telephone = projectCM.Telephone
	modelsVM.LoginIp = projectCM.LoginIp
	modelsVM.CanLogin = projectCM.CanLogin
	modelsVM.Office = projectCM.Office

	modelsVM.Category = projectCM.Category

	if !projectCM.LastLogin.IsZero() {
		modelsVM.LastLogin = projectCM.LastLogin.Format(conf.SysTimeform)
	}
	if !projectCM.CreateTime.IsZero() {
		modelsVM.CreateTime = projectCM.CreateTime.Format(conf.SysTimeform)
	}

	return modelsVM
}
