package course

import (
	"errors"

	"courseSign/server/global"
	"courseSign/server/model/common/request"
	"courseSign/server/model/course"
	courseReq "courseSign/server/model/course/request"
	"go.uber.org/zap"
)

type CourseSignupService struct {
}

// CreateCourseSignup 创建CourseSignup记录
// Author [piexlmax](https://github.com/piexlmax)
func (courseSignupService *CourseSignupService) CreateCourseSignup(courseSignup course.CourseSignup) (err error) {
	err = global.GVA_DB.Create(&courseSignup).Error
	return err
}

// DeleteCourseSignup 删除CourseSignup记录
// Author [piexlmax](https://github.com/piexlmax)
func (courseSignupService *CourseSignupService)DeleteCourseSignup(courseSignup course.CourseSignup) (err error) {
	err = global.GVA_DB.Delete(&courseSignup).Error
	return err
}

// DeleteCourseSignupByIds 批量删除CourseSignup记录
// Author [piexlmax](https://github.com/piexlmax)
func (courseSignupService *CourseSignupService)DeleteCourseSignupByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]course.CourseSignup{},"id in ?",ids.Ids).Error
	return err
}

// UpdateCourseSignup 更新CourseSignup记录
// Author [piexlmax](https://github.com/piexlmax)
func (courseSignupService *CourseSignupService)UpdateCourseSignup(courseSignup course.CourseSignup) (err error) {
	var preSign course.CourseSignup
	var user course.CourseUsers
	tx := global.GVA_DB.Begin()
	err = tx.Model(&course.CourseUsers{}).Where("id = ?",courseSignup.Uid).First(&user).Error
	if err != nil {
		tx.Rollback()
		return
	}
	err = tx.Model(&course.CourseSignup{}).Where("id = ?",courseSignup.ID).First(&preSign).Error
	if err != nil {
		tx.Rollback()
		return
	}
	// 审核通过 分配学号
	if !*preSign.IsPass && *courseSignup.IsPass {
		if user.Number > 0 {
			err = errors.New("异常！用户已存在学号")
			return
		}

		var next int
		var numberUser course.CourseUsers
		err = tx.Model(&course.CourseUsers{}).Order("number desc").First(&numberUser).Error
		if err != nil {
			tx.Rollback()
			return
		}
		if numberUser.Number == 0 {
			next = 88800001
		} else {
			next = numberUser.Number+1
		}
		global.GVA_LOG.Info("UpdateCourseSignup",zap.Int("number pre",numberUser.Number),zap.Int("number next",next))
		err = tx.Model(&course.CourseUsers{}).Where("id = ?",courseSignup.Uid).Update("number",next).Error
		if err != nil {
			tx.Rollback()
			return
		}
	}
	err = global.GVA_DB.Save(&courseSignup).Error
	if err != nil {
		tx.Rollback()
	}
	tx.Commit()
	return err
}

// GetCourseSignup 根据id获取CourseSignup记录
// Author [piexlmax](https://github.com/piexlmax)
func (courseSignupService *CourseSignupService)GetCourseSignup(id uint) (courseSignup course.CourseSignup, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&courseSignup).Error
	var user course.CourseUsers
	err = global.GVA_DB.Model(&course.CourseUsers{}).Where("id = ?",courseSignup.Uid).First(&user).Error
	if err != nil {
		return
	}
	courseSignup.Photo = user.Photo
	courseSignup.Addr = user.Address
	courseSignup.Company = user.Company
	courseSignup.Age = user.Age
	courseSignup.Sex = user.Sex
	courseSignup.Name = user.Name
	courseSignup.Phone = user.Phone
	return
}


// GetCourseSignupByUidAndCid 根据id获取CourseSignup记录
// Author [piexlmax](https://github.com/piexlmax)
func (courseSignupService *CourseSignupService)GetCourseSignupByUidAndCid(cid uint,uid uint) (courseSignup course.CourseSignup, err error) {
	err = global.GVA_DB.Where("cid = ? and uid = ?", cid,uid).First(&courseSignup).Error
	return
}


// GetCourseSignupInfoList 分页获取CourseSignup记录
// Author [piexlmax](https://github.com/piexlmax)
func (courseSignupService *CourseSignupService)GetCourseSignupInfoList(info courseReq.CourseSignupSearch) (list []course.CourseSignup, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Debug().Model(&course.CourseSignup{})
    var courseSignups []course.CourseSignup
	var courseSignupsRead []course.CourseSignupRead
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
    if info.Uid != nil {
        db = db.Where("uid = ?",info.Uid)
    }
    if info.Cid != nil {
        db = db.Where("cid = ?",info.Cid)
    }
	err = db.Count(&total).Error
    db = db.Select("course_signup.*,course_users.address as addr,course_list.course_name").
    	Joins("join course_users on course_users.id = course_signup.uid").
    	Joins("join course_list on course_list.id = course_signup.cid")

	if err!=nil {
    	return
    }
	err = db.Limit(limit).
		Offset(offset).
		Find(&courseSignupsRead).Error
	for _,v:= range courseSignupsRead {
		var cs course.CourseSignup
		cs.ID = v.ID
		cs.CourseName = v.CourseName
		cs.Addr = v.Addr
		cs.Uid = v.Uid
		cs.Cid = v.Cid
		cs.CreatedAt = v.CreatedAt
		cs.IsPass = v.IsPass
		courseSignups = append(courseSignups,cs)
	}
	return  courseSignups, total, err
}

// GetUserCourse 分页获取CourseSignup记录
// Author [piexlmax](https://github.com/piexlmax)
func (courseSignupService *CourseSignupService)GetUserCourse(info courseReq.CourseSignupSearch,uid,cid uint) (list []course.CourseSignup, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Debug().Model(&course.CourseSignup{})
	var courseSignups []course.CourseSignup
	var courseSignupsRead []course.CourseSignupRead
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if uid > 0 {
		db = db.Where("uid = ?",uid)
	}
	if cid > 0 {
		db = db.Where("cid = ?",cid)
	}
	err = db.Count(&total).Error
	db = db.Select("course_signup.*,course_users.address as addr,course_list.course_name").
		Joins("join course_users on course_users.id = course_signup.uid").
		Joins("join course_list on course_list.id = course_signup.cid")

	if err!=nil {
		return
	}
	err = db.Limit(limit).
		Offset(offset).
		Find(&courseSignupsRead).Error
	for _,v:= range courseSignupsRead {
		var cs course.CourseSignup
		cs.ID = v.ID
		cs.CourseName = v.CourseName
		cs.Addr = v.Addr
		cs.Uid = v.Uid
		cs.Cid = v.Cid
		cs.CreatedAt = v.CreatedAt
		cs.IsPass = v.IsPass
		courseSignups = append(courseSignups,cs)
	}
	return  courseSignups, total, err
}
