package yb

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

const (
	// 回复状态
	ReplyStatusDitribute = 1
	ReplyStatusWait      = 2
	ReplyStatusDone      = 3
	ReplyStatusStop      = 4
)

// CommunityQuestion 问答社区
type CommunityQuestion struct {
	CommunityQuestionId     int       `orm:"column(community_question_id);pk" description:"问题ID"`
	UserId                  int       `description:"提问用户ID"`
	UserOpenid              string    `description:"提问用户openid"`
	Mobile                  string    `description:"用户手机号"`
	RealName                string    `description:"用户名"`
	QuestionContent         string    `description:"问题描述"`
	ReplierUserId           int       `description:"回复人的user_id"`
	ReplierOpenid           string    `description:"回复人openid"`
	ReplierAdminId          int       `description:"回复人关联的admin_id"`
	ReplierRealName         string    `description:"回复人姓名"`
	ReplierAvatar           string    `description:"回复人头像"`
	ResearchGroupFirstId    int       `description:"回复人研究方向一级分组ID"`
	ResearchGroupSecondId   int       `description:"回复人研究方向二级分组ID"`
	ResearchGroupFirstName  string    `description:"研究方向一级分组名称"`
	ResearchGroupSecondName string    `description:"研究方向二级分组名称"`
	DistributeAdminId       int       `description:"分配人admin_id"`
	DistributeTime          time.Time `description:"分配时间"`
	VarietyTagId            int       `description:"标签ID"`
	VarietyTagName          string    `description:"标签名称"`
	IsRead                  int       `description:"用户是否已读 0-未读 1-已读"`
	ReplierIsRead           int       `description:"回复人是否已读 0-未读 1-已读"`
	ReplyStatus             int       `description:"状态 1-待分配 2-待回答 3-已回答 4-已终止"`
	MsgSendStatus           int       `description:"消息推送进度 0-待推送 1-已推送回答人 2-已推送提问人"`
	ReplyTime               time.Time `description:"回复时间"`
	CreateTime              time.Time `description:"提问时间"`
	ModifyTime              time.Time `description:"修改时间"`
	IsDeleted               int       `description:"是否已删除 0-否 1-是"`
	DeleteTime              time.Time `description:"删除时间"`
	StopReason              string    `description:"终止原因"`
}

type CommunityQuestionMore struct {
	CommunityQuestion
	ClickNum    int `description:"点击量"`
	UserQaCount int `description:"用户提问数"`
}

func (item *CommunityQuestion) TableName() string {
	return "yb_community_question"
}

func (item *CommunityQuestion) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(item, cols...)
	return
}

// GetQuestionById 主键获取提问
func GetQuestionById(questionId int) (item *CommunityQuestion, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM yb_community_question WHERE community_question_id = ? AND is_deleted = 0 LIMIT 1`
	err = o.Raw(sql, questionId).QueryRow(&item)
	return
}

// GetCommunityQuestionList 获取问答列表
func GetCommunityQuestionList(condition string, pars []interface{}, order string, startSize, pageSize int) (total int, list []*CommunityQuestionMore, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				q.*, l.click_num,
				c.user_qa_count
			FROM
				yb_community_question q
			LEFT JOIN (
				SELECT
					count(*) AS click_num,
					community_question_id
				FROM
					yb_community_audio_listen_log
				GROUP BY
					community_question_id
			) AS l ON q.community_question_id = l.community_question_id
			LEFT JOIN (
				SELECT
					count(*) AS user_qa_count,
					user_id
				FROM
					yb_community_question
				GROUP BY
					user_id
			) AS c ON q.user_id = c.user_id
			WHERE
				q.is_deleted = 0 `
	sql += condition
	if order != "" {
		sql += order
	} else {
		sql += ` ORDER BY q.create_time DESC`
	}
	totalSQl := `SELECT COUNT(1) total FROM (` + sql + `) z`
	if err = o.Raw(totalSQl, pars).QueryRow(&total); err != nil {
		return
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
	return
}

type CommunityQuestionCount struct {
	ReplyStatus int `json:"reply_status"`
	Total       int `json:"total"`
}

// GetCommunityQuestionCount 根据状态获取问答数
func GetCommunityQuestionCount() (list []*CommunityQuestionCount, err error) {
	o := orm.NewOrm()
	sql := `SELECT reply_status, COUNT(1) total FROM yb_community_question WHERE is_deleted = 0 GROUP BY reply_status`
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// DeleteQuestion (软)删除问题
func DeleteQuestion(questionId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE yb_community_question SET is_deleted = 1, delete_time = NOW() WHERE community_question_id = ? LIMIT 1`
	_, err = o.Raw(sql, questionId).Exec()
	return
}

// GetQuestionListByIds 根据IDs获取问答列表
func GetQuestionListByIds(questionIds []int) (list []*CommunityQuestion, err error) {
	arrLen := len(questionIds)
	if arrLen == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT * FROM yb_community_question WHERE community_question_id IN (` + utils.GetOrmInReplace(arrLen) + `) AND is_deleted = 0`
	_, err = o.Raw(sql, questionIds).QueryRows(&list)
	return
}

// GetQuestionByIds 根据IDs获取问答列表
func GetQuestionByIds(questionIds []int) (list []*CommunityQuestion, err error) {
	arrLen := len(questionIds)
	if arrLen == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT * FROM yb_community_question WHERE community_question_id IN (` + utils.GetOrmInReplace(arrLen) + `)`
	_, err = o.Raw(sql, questionIds).QueryRows(&list)
	return
}

// CommunityQuestionDetail 问答社区详情
type CommunityQuestionDetail struct {
	CommunityQuestionId     int    `description:"问题ID"`
	Mobile                  string `description:"用户手机号"`
	RealName                string `description:"用户名"`
	QuestionContent         string `description:"问题描述"`
	ResearchGroupFirstName  string `description:"研究方向一级分组名称"`
	ResearchGroupSecondName string `description:"研究方向二级分组名称"`
	VarietyTagName          string `description:"标签名称"`
	ReplyStatus             int    `description:"状态 1-待分配 2-待回答 3-已回答 4-已终止"`
	MsgSendStatus           int    `description:"消息推送进度 0-待推送 1-已推送回答人 2-已推送提问人"`
	ReplyTime               string `description:"回复时间"`
	CreateTime              string `description:"提问时间"`
	StopReason              string `description:"终止原因"`
	ProcessList             []*CommunityQuestionProcessItem
}
