package models

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type CygxQuestionnaireVote struct {
	QuestionnaireVoteId  int `orm:"column(questionnaire_vote_id);pk"`
	QuestionnaireId      int `description:"问卷ID"`
	QuestionnaireThemeId int `description:"问卷主题ID"`
	UserId               int `description:"用户ID"`
	CreateTime           time.Time
	Mobile               string    `description:"手机号"`
	Email                string    `description:"邮箱"`
	CompanyId            int       `description:"公司id"`
	CompanyName          string    `description:"公司名称"`
	ModifyTime           time.Time `description:"修改时间"`
	RealName             string    `description:"用户实际名称"`
	SellerName           string    `description:"所属销售"`
	RegisterPlatform     int       `description:"来源 1小程序，2：网页"`
}

type CygxQuestionnaireVoteOtherTheme struct {
	QuestionnaireVoteOtherThemeId int `orm:"column(questionnaire_vote_other_theme_id);pk"`
	QuestionnaireId               int `description:"问卷ID"`
	UserId                        int `description:"用户ID"`
	CreateTime                    time.Time
	Mobile                        string    `description:"手机号"`
	Email                         string    `description:"邮箱"`
	CompanyId                     int       `description:"公司id"`
	CompanyName                   string    `description:"公司名称"`
	ModifyTime                    time.Time `description:"修改时间"`
	RealName                      string    `description:"用户实际名称"`
	SellerName                    string    `description:"所属销售"`
	Content                       string    `description:"内容"`
	RegisterPlatform              int       `description:"来源 1小程序，2：网页"`
}

// 获取数量
func GetCygxQuestionnaireVoteCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_questionnaire_vote as art WHERE 1= 1  `
	if condition != "" {
		sqlCount += condition
	}
	o := orm.NewOrm()
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

type CygxQuestionnaireVoteReq struct {
	QuestionnaireId       int    `description:"问卷ID"`
	QuestionnaireThemeIds []int  `description:"问卷主题ID"`
	Content               string `description:"内容"`
}

// 添加
func AddCygxQuestionnaireVote(voteItems []*CygxQuestionnaireVote, otherItem *CygxQuestionnaireVoteOtherTheme) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	//其它主题类型提交需要写入的信息
	if otherItem.Content != "" {
		_, err = to.Insert(otherItem)
		if err != nil {
			return
		}

		//更新其他主题投票数量
		sql := ` UPDATE cygx_questionnaire SET other_theme_total =  other_theme_total +1 WHERE questionnaire_id = ?  `
		_, err = o.Raw(sql, otherItem.QuestionnaireId).Exec()
	}
	//主题ID提交问卷需要写入的信息
	for _, v := range voteItems {
		_, err = to.Insert(v)
		if err != nil {
			return
		}
	}
	return
}
