/*
 * @description: 管理员组
 * @Author: CP
 * @Date: 2021-06-01 14:56:44
 * @FilePath: \construction_management\services\group_service.go
 */
package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"time"

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

//定义管理员Service接口
type GroupService interface {
	GetAll() (dataList []viewmodels.Group, total int64)
	Add(dataVM viewmodels.Group) error
	Update(dataVM viewmodels.Group, id int) error
	Delete(id int) error
}

//返回service操作类
type groupService struct {
	dao *dao.GroupDao
}

//创建管理员service
func NewGroupService() GroupService {
	return &groupService{
		dao: dao.NewGroupDao(datasource.InstanceDbMaster()),
	}
}

//实现getall接口
func (s *groupService) GetAll() (data []viewmodels.Group, total int64) {

	datalist := make([]viewmodels.Group, 0)
	result, total := s.dao.GetAll()

	for _, item := range result {
		projectVM := makeGroupVM(&item)
		datalist = append(datalist, projectVM)
	}

	return datalist, total
}

func (s *groupService) Add(dataVM viewmodels.Group) error {
	data := &models.CmGroup{}
	persission, err := json.Marshal(dataVM.Permission)
	if err != nil {
		return err
	}

	data.Permission = string(persission)
	data.Name = dataVM.Name

	data.Remark = dataVM.Remark
	data.CreateTime = time.Now()

	return s.dao.Add(data)
}

func (s *groupService) Update(dataVM viewmodels.Group, id int) error {
	persission, err := json.Marshal(dataVM.Permission)
	if err != nil {
		return err
	}
	updateData := models.CmGroup{}
	updateData.Id = id
	updateData.Name = dataVM.Name
	updateData.Permission = string(persission)

	// 要填写字段名称必须要更新的字段
	if err := s.dao.Update(&updateData, []string{"permission", "name"}); err != nil {
		fmt.Println(err)
		return err
	}
	return nil
}

//移除标段成员
func (s *groupService) Delete(id int) error {
	// 1.检查权限组合法性
	groupData := s.dao.Get(id)
	if groupData.Id == 0 {
		return errors.New("添加的账号不合法")
	}

	// 2.权限组下是否有管理员
	managerDao := dao.NewManagerDao(datasource.InstanceDbMaster())
	managerList := managerDao.GetGroupId(id)
	if len(managerList) != 0 {
		return errors.New("权限组下还有管理员")
	}

	// 删除权限组
	data := models.CmGroup{}
	data.Id = id
	err := s.dao.Delete(&data)
	if err != nil {
		return err
	}
	return nil
}

// 构造视图层models
func makeGroupVM(projectCM *models.CmGroup) viewmodels.Group {
	modelsVM := viewmodels.Group{}
	permission := []string{}
	id, _ := comm.AesEncrypt(strconv.Itoa(projectCM.Id), conf.SignSecret)
	// userId, _ := comm.AesEncrypt(strconv.Itoa(projectCM.UserId), conf.SignSecret)

	modelsVM.Id = id
	modelsVM.Name = projectCM.Name
	modelsVM.Remark = projectCM.Remark
	json.Unmarshal([]byte(projectCM.Permission), &permission)
	modelsVM.Permission = permission

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

	return modelsVM
}
