/*
 * @description:版本相关数据操作
 * @Author: CP
 * @Date: 2020-09-02 09:56:28
 * @FilePath: \construction_management\services\version_service.go
 */
package services

import (
	"errors"
	"strconv"
	"time"

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

//定义项目用户Service接口
type VersionService interface {
	Get() *viewmodels.Version
	GetListBs(pageData viewmodels.Version) ([]viewmodels.Version, int64)
	Add(inputData viewmodels.Version) error
	Delete(id int) error
}

//返回service操作类
type versionService struct {
	versionDao *dao.VersionDao
}

//创建项目用户service
func NewVersionService() VersionService {
	return &versionService{
		versionDao: dao.NewVersionDao(datasource.InstanceDbMaster()),
	}
}

// 验证项目用户登陆相关
func (s *versionService) Get() *viewmodels.Version {

	// 1-1.工程项目是否存在
	versionData := s.versionDao.Get()
	if versionData.Id == 0 {
		return nil
	}
	versionVm := &viewmodels.Version{}
	versionVm.Name = versionData.Name
	return versionVm
}

// 获得版本信息列表
func (s *versionService) GetListBs(pageData viewmodels.Version) ([]viewmodels.Version, int64) {

	versionList, total := s.versionDao.GetList(pageData)

	datalist := make([]viewmodels.Version, 0)
	for _, data := range versionList {
		itemVM := makeDataVM(&data)
		datalist = append(datalist, itemVM)
	}

	return datalist, total
}

// 新增版本信息11
func (s *versionService) Add(inputData viewmodels.Version) error {

	dataCm := &models.CmVersion{}
	dataCm.Name = inputData.Name
	dataCm.Content = inputData.Content
	dataCm.CreateTime = time.Now()

	err := s.versionDao.Add(dataCm)
	return err
}

// 删除版本信息
func (s *versionService) Delete(id int) error {
	// 是否有该版本信息
	if versionData := s.versionDao.FindById(id); versionData.Id == 0 {
		return errors.New("未找到该版本信息")
	}

	err := s.versionDao.Delete(id)
	return err
}

// 构造视图层models
func makeDataVM(dataCM *models.CmVersion) viewmodels.Version {
	dataVM := viewmodels.Version{}
	id, _ := comm.AesEncrypt(strconv.Itoa(dataCM.Id), conf.SignSecret)

	dataVM.Id = id
	dataVM.Name = dataCM.Name
	dataVM.Content = dataCM.Content

	if !dataCM.CreateTime.IsZero() {
		dataVM.CreateTime = dataCM.CreateTime.Format(conf.SysTimeform)
	}

	return dataVM
}
