package yb

import (
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/utils"
	"time"
)

// AddRegister 新增报名活动
func AddRegister(activityId, userId, opUserId int) (activityRegisterInfo *yb.ActivityRegister, err error, errMsg string) {
	wxUserInfo, err := models.GetWxUserByUserId(userId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "找不到该用户"
		}
		return
	}
	companyInfo, err := company.GetCompanyById(wxUserInfo.CompanyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "找不到该客户"
		}
		return
	}
	// ficc 产品
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(wxUserInfo.CompanyId, 1)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "找不到该客户产品"
		}
		return
	}

	activityRegisterInfo, err = yb.GetActivityRegister(activityId, userId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	if activityRegisterInfo != nil && activityRegisterInfo.RegisterState == 1 {
		err = fmt.Errorf("用户已报名")
		errMsg = "用户已报名"
		return
	}

	activityRegisterInfo = &yb.ActivityRegister{
		ActivityId:    activityId,
		UserId:        userId,
		CompanyId:     wxUserInfo.CompanyId,
		CompanyName:   companyInfo.CompanyName,
		SellerName:    companyProduct.SellerName,
		RealName:      wxUserInfo.RealName,
		Mobile:        wxUserInfo.Mobile,
		RegisterState: 1,
		CreateTime:    time.Now(),
	}

	yb.AddActivityRegister(activityRegisterInfo)
	return
}

// CancelRegister 取消报名活动
func CancelRegister(activityId, userId int) (activityRegisterInfo *yb.ActivityRegister, err error, errMsg string) {
	activityRegisterInfo, err = yb.GetActivityRegister(activityId, userId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "找不到该报名"
		}
		return
	}

	if activityRegisterInfo.RegisterState == 0 {
		err = fmt.Errorf("该用户已取消报名")
		errMsg = "该用户已取消报名"
		return
	}

	updateCols := make([]string, 0)
	//发布
	activityRegisterInfo.RegisterState = 0
	//取消报名
	updateCols = append(updateCols, "RegisterState")
	err = activityRegisterInfo.Update(updateCols)
	return
}
