package models

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

type WxUser struct {
	UserId              int       `orm:"column(user_id);pk"`
	OpenId              string    `description:"open_id"`
	UnionId             string    `description:"union_id"`
	Subscribe           string    `description:"是否关注"`
	CompanyId           int       `description:"客户id"`
	NickName            string    `description:"用户昵称"`
	RealName            string    `description:"用户实际名称"`
	UserCode            string    `description:"用户编码"`
	Mobile              string    `description:"手机号码"`
	BindAccount         string    `description:"绑定时的账号"`
	WxCode              string    `description:"微信号"`
	Profession          string    `description:"职业"`
	Email               string    `description:"邮箱"`
	Telephone           string    `description:"座机"`
	Sex                 int       `description:"普通用户性别,1为男性,2为女性"`
	Province            string    `description:"普通用户个人资料填写的省份"`
	City                string    `description:"普通用户个人资料填写的城市"`
	Country             string    `description:"国家,如中国为CN"`
	SubscribeTime       int       `description:"关注时间"`
	Remark              string    `description:"备注"`
	Headimgurl          string    `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
	Privilege           string    `description:"用户特权信息,json数组,如微信沃卡用户为(chinaunicom)"`
	Unionid             string    `description:"用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。"`
	FirstLogin          int       `description:"是否第一次登陆"`
	Enabled             int       `description:"是否可用"`
	CreatedTime         time.Time `description:"创建时间"`
	LastUpdatedTime     time.Time `description:"最新一次修改时间"`
	Seller              string    `description:"销售员"`
	Note                string    `description:"客户备份信息"`
	IsNote              int       `description:"是否备注过信息"`
	FromType            string    `description:"report' COMMENT 'report:研报,teleconference:电话会"`
	ApplyMethod         int       `description:"0:未申请,1:已付费客户申请试用,2:非客户申请试用"`
	RegisterTime        time.Time `description:"注册时间"`
	RegisterPlatform    int       `description:"注册平台,1:微信端,2:PC网页端"`
	IsFreeLogin         bool      `description:"是否免登陆,true:免登陆,false:非免登陆"`
	LoginTime           time.Time `description:"最近一次登录时间"`
	SessionKey          string    `description:"微信小程序会话密钥"`
	IsRegister          int       `description:"是否注册:1:已注册,0:未注册"`
	Source              int       `description:"绑定来源,1:微信端,2:pc网页端,3:查研观向小程序,4:每日咨询"`
	CountryCode         string    `description:"区号"`
	OutboundMobile      string    `description:"外呼手机号"`
	OutboundCountryCode string    `description:"外呼手机号区号"`
}

type WxUserItem struct {
	UserId              int       `description:"用户id"`
	OpenId              string    `description:"open_id"`
	UnionId             string    `description:"union_id"`
	CompanyId           int       `description:"客户id"`
	NickName            string    `description:"用户昵称"`
	RealName            string    `description:"用户实际名称"`
	Mobile              string    `description:"手机号码"`
	BindAccount         string    `description:"绑定时的账号"`
	Email               string    `description:"邮箱"`
	Headimgurl          string    `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
	HeadimgurlRecord    string    `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
	ApplyMethod         int       `description:"0:未申请,1:已付费客户申请试用,2:非客户申请试用"`
	FirstLogin          int       `description:"是否第一次登陆"`
	IsFreeLogin         int       `description:"是否免登陆,true:免登陆,false:非免登陆"`
	LoginTime           time.Time `description:"登录时间"`
	CreatedTime         time.Time `description:"创建时间"`
	LastUpdatedTime     time.Time `description:"最近一次修改时间"`
	SessionKey          string    `description:"微信小程序会话密钥"`
	CompanyName         string    `description:"公司名称"`
	IsRegister          int       `description:"是否注册:1:已注册,0:未注册"`
	CountryCode         string    `description:"手机国家区号"`
	OutboundMobile      string    `description:"外呼手机号"`
	OutboundCountryCode string    `description:"外呼手机号区号"`
	IsMsgOutboundMobile int       `description:"是否弹窗过绑定外呼手机号区号"`
	Source              int
	IsMaker             int    `description:"是否是决策人"`
	Position            string `description:"职务"`
	InviteCompany       string `description:"邀请机构 ,LUODING:络町"`
}

func GetWxUserItemByUserId(userId int) (item *WxUserItem, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT a.*,b.company_name FROM wx_user AS a
			LEFT JOIN company AS b on a.company_id=b.company_id
			WHERE a.user_id=? `
	err = o.Raw(sql, userId).QueryRow(&item)
	return
}

func GetWxUserItemByMobile(mobile string) (item *WxUserItem, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT a.*,b.company_name FROM wx_user AS a
			LEFT JOIN company AS b on a.company_id=b.company_id
			WHERE a.mobile=? `
	err = o.Raw(sql, mobile).QueryRow(&item)
	return
}

type WxLoginResp struct {
	Authorization string
	UserId        int
	FirstLogin    int
	Headimgurl    string `description:"用户头像"`
	Mobile        string `description:"手机号"`
	Email         string `description:"邮箱"`
	CompanyName   string `description:"客户名称"`
	Status        string `description:"状态"`
	EndDate       string `description:"到期日期"`
	ProductName   string `description:"客户类型名称"`
}

type WxGetUserInfoReq struct {
	RawData       string `description:"rawData"`
	Signature     string `description:"signature"`
	EncryptedData string `description:"encryptedData"`
	Iv            string `description:"iv"`
}

func GetWxUserItemByUserUnionId(unionId string) (item *WxUserItem, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT a.*,r.headimgurl as headimgurl_record, b.company_name FROM wx_user AS a
			INNER JOIN company AS b on a.company_id=b.company_id
			INNER JOIN user_record  as  r ON r.user_id = a.user_id 
			WHERE r.union_id=?
			GROUP BY a.user_id`
	err = o.Raw(sql, unionId).QueryRow(&item)
	return
}

// 根据用户手机号获取相关信息
func GetWxUserItemByUserMobile(mobile string) (item *WxUserItem, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT
			a.user_id,
			a.real_name,
			a.headimgurl,
			a.company_id,
			a.mobile,
			a.email,
			r.union_id,
			r.open_id,
			b.company_name 
		FROM
			wx_user AS a
			INNER JOIN company AS b ON a.company_id = b.company_id
			INNER JOIN user_record AS r ON r.bind_account = a.mobile

		WHERE
			a.mobile = ? 
			and	 r.create_platform = 4
		GROUP BY
			a.mobile `
	err = o.Raw(sql, mobile).QueryRow(&item)
	return
}

// GetUserCountByMobile 获取数量
func GetUserCountByMobile(mobile string) (count int, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sqlCount := ` SELECT COUNT(1) AS count  FROM wx_user WHERE mobile = ? `
	err = o.Raw(sqlCount, mobile).QueryRow(&count)
	return
}

// 添加用户信息
func AddWxUser(item *WxUser) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	lastId, err = o.Insert(item)
	return
}

// 变更联系人是否已注册状态
func ModifyWxUserRegisterStatus(userId int) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `UPDATE wx_user SET is_register=?,source=3,register_time=NOW() WHERE user_id = ? `
	_, err = o.Raw(sql, 1, userId).Exec()
	return
}

// 判断这个用户是否被设置消息提醒
func GetUserRemind(uid int) (count int, err error) {
	sql := `SELECT  COUNT(1) AS count FROM cygx_user_remind WHERE user_id = ? `
	err = orm.NewOrm().Raw(sql, uid).QueryRow(&count)
	return
}

func ModifyReportLastViewTime(uid int) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := ` UPDATE wx_user SET report_last_view_time=NOW()
			WHERE user_id=? `
	_, err = o.Raw(sql, uid).Exec()
	return
}

// GetWxUserListByUserIds 根据用户ID集合获取用户
func GetWxUserListByUserIds(userIds string) (list []*WxUserItem, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := ` SELECT u.*, c.company_name FROM wx_user AS u
			INNER JOIN company AS c ON c.company_id = u.company_id 
			WHERE user_id IN (` + userIds + `) `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}