package models

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

type CygxUserRecord struct {
	UserRecordId  int       `orm:"column(user_record_id);pk" description:"id"`
	OpenId        string    `description:"用户openid，最大长度：32"`
	UnionId       string    `description:"用户unionid，最大长度：64"`
	Subscribe     int       `description:"是否关注,0:未关注,1:已关注"`
	SubscribeTime string    `description:"关注/取消关注时间"`
	CreateTime    time.Time `description:"创建时间"`
}

// 优化建议
func AddCygxUserRecord(item *CygxUserRecord) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

// 获取数量
func GetCygxUserRecordCount(openId string) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_user_record WHERE open_id=? `
	err = o.Raw(sqlCount, openId).QueryRow(&count)
	return
}

func GetCygxUserRecordSubscribe(unionId string) (item *CygxUserRecord, err error) {
	sql := ` SELECT * FROM cygx_user_record WHERE union_id=?  AND subscribe = 1  limit 1 `
	err = orm.NewOrm().Raw(sql, unionId).QueryRow(&item)
	return
}

// 获取所有关注了该产业用户的openid
func GetCygxUserIndustryFllowOpneid(IndustrialManagementId int) (items []*OpenIdList, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			cr.open_id,
			cr.cygx_user_id AS user_id 
		FROM
			cygx_user_record AS cr
			INNER JOIN cygx_industry_fllow AS cf ON cr.cygx_user_id = cf.user_id 
		WHERE
			1 = 1 
			AND cf.industrial_management_id = ? `
	_, err = o.Raw(sql, IndustrialManagementId).QueryRows(&items)
	return
}
