package models

import (
	"rdluck_tools/orm"
)

type HongzeUsers struct {
	RealName    string
	CompanyName string
	Mobile      string
	IsRegister  string
	UserType    string
}

func GetHongzeUsers() (items []*HongzeUsers, err error) {
	sql := `select wu.real_name,c.company_name,left(wu.mobile, 11) as mobile ,if(wu.open_id is null,'否','是') as is_register,if(c.type in (1),'是','否') as user_type
	from wx_user wu
	inner join company c on c.company_id = wu.company_id
	where c.company_id <> 1 and c.company_id <> 16
	and c.type in (1)
	order by company_name desc `
	_, err = orm.NewOrm().Raw(sql).QueryRows(&items)
	return
}

type WxUser struct {
	UserId    int64
	Mobile    string
	Email     string
	CompanyId int
	ExpiredIn int64
	OpenId    string
}

func GetWxUserByUserId(userId int) (item *WxUser, err error) {
	sql := `SELECT * FROM wx_user WHERE user_id=? `
	err = orm.NewOrm().Raw(sql, userId).QueryRow(&item)
	return
}

func GetWxUserByMobile(mobile string) (item *WxUser, err error) {
	sql := `SELECT * FROM wx_user WHERE mobile=? `
	err = orm.NewOrm().Raw(sql, mobile).QueryRow(&item)
	return
}

func AddWxUser(companyId int, mobile, realName, email string) (err error) {
	sql := `INSERT INTO wx_user(company_id,real_name,mobile,first_login,enabled,is_note,from_type,apply_method,email) VALUES (?,?,?,1,1,1,'report',0,?);`
	orm.NewOrm().Raw(sql, companyId, realName, mobile, email).Exec()
	return
}

func GetPotentialUser() (items []*WxUser, err error) {
	sql := ` SELECT * FROM wx_user WHERE company_id=1 AND report_last_view_time <> '' `
	o := orm.NewOrm()
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetMaxReviewTime(uid int) (max_time string, err error) {
	o := orm.NewOrm()
	sql := `SELECT MAX(a.max_time) AS max_time FROM (
			SELECT MAX(created_time)AS max_time FROM user_view_history AS a WHERE user_id=?
			UNION 
			SELECT MAX(create_time)AS max_time FROM  hongze_rddp.report_view_record AS a WHERE user_id=?
			)AS a`
	err = o.Raw(sql, uid, uid).QueryRow(&max_time)
	return
}

func ModifyUserLastViewTime(uid int, lastViewTime string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE wx_user SET report_last_view_time=? WHERE user_id=? `
	_, err = o.Raw(sql, lastViewTime, uid).Exec()
	return
}
