package dao

import (
	"server/global"
	"server/model/common/request"
	"time"
)

type Project struct {
	global.GVA_MODEL
	ProjectName string    `gorm:"type:varchar(64)" json:"projectName"`           //项目名称
	StartTime   time.Time `gorm:"type:date" json:"startTime" time_format:"date"` //开始时间
	Remark      string    `gorm:"type:varchar(64);default:''" json:"remark"`     //备注

	Users []SysUser `json:"users" gorm:"many2many:user_project;"`
}

func (Project) TableName() string {
	return "project"
}

func (p Project) AddProject() error {
	return global.GVA_DB.Model(&Project{}).Create(&p).Error
}

func (p Project) DelProject(id int) error {
	err := global.GVA_DB.Model(&p).Where("id = ?", id).Delete(&p).Error
	return err
}

func (p Project) UpdateProject() error {
	return global.GVA_DB.Model(&Project{}).Debug().Where("id = ?", p.GVA_MODEL.ID).Updates(map[string]interface{}{
		"project_name": p.ProjectName,
		"start_time":   p.StartTime,
		"remark":       p.Remark,
	}).Error
}

// 根据用户ID查询对应的项目
func (p Project) GetProjectListByUserID(info request.PageInfo, userid uint) (projectList []Project, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&Project{}).
		Joins("JOIN user_project ON project.id = user_project.project_id").
		Where("user_project.sys_user_id = ?", userid)

	err = db.Count(&total).Error

	err = db.Limit(limit).Offset(offset).Scan(&projectList).Error
	return
}

// 查询项目列表
func (p Project) GetProjectAndDetails(info request.PageInfo) (projectList []Project, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&Project{}).Find(&projectList)

	err = db.Count(&total).Error

	err = db.Limit(limit).Offset(offset).Scan(&projectList).Error
	return
}

// 增加user_project记录
func AddUserProjectRelation(userID, projectID uint) error {
	return global.GVA_DB.Table("user_project").Exec("INSERT INTO user_project (sys_user_id, project_id) VALUES (?, ?)", userID, projectID).Error
}

// 获取所有项目列表
func GetProjectList() (projectList []Project, err error) {
	err = global.GVA_DB.Model(&Project{}).Find(&projectList).Error
	return projectList, err
}

func GetProjectListByUserIDNoPage(userid uint) (projectList []Project, err error) {
	db := global.GVA_DB.Model(&Project{}).
		Joins("JOIN user_project ON project.id = user_project.project_id").
		Where("user_project.sys_user_id = ?", userid).Scan(&projectList).Error
	return projectList, db
}

func DelOldProjectsByUserId(userId uint) error {
	db := global.GVA_DB.Table("user_project").Exec("DELETE FROM user_project WHERE sys_user_id = ?", userId).Error
	return db
}

// 批量新增新的项目id
func ChangeProjects(up []request.UserProject) error {
	return global.GVA_DB.Table("user_project").Create(&up).Error
}
