package models

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

type UserRecord struct {
	UserRecordId   int       `orm:"column(user_record_id);pk"`
	OpenId         string    `description:"用户openid，最大长度：32"`
	UnionId        string    `description:"用户unionid，最大长度：64"`
	Subscribe      int       `description:"是否关注"`
	NickName       string    `descritpion:"用户昵称，最大长度：32"`
	RealName       string    `descritpion:"用户实际名称，最大长度：32"`
	BindAccount    string    `descritpion:"绑定时的账号，最大长度：128"`
	Sex            int       `descritpion:"普通用户性别，1为男性，2为女性"`
	Province       string    `description:"普通用户个人资料填写的省份,最大长度：30"`
	City           string    `description:"普通用户个人资料填写的城市,最大长度：30"`
	Country        string    `description:"国家，如中国为CN,最大长度：30"`
	Headimgurl     string    `description:"用户第三方（微信）头像,最大长度：512"`
	CreateTime     time.Time `description:"创建时间，关系添加时间、用户授权时间"`
	CreatePlatform int       `description:"注册平台,1:日度点评公众号,2:管理后台，3：pc端网站,4:查研观向小程序；默认：1"`
	SessionKey     string    `description:"微信小程序会话密钥，最大长度：255"`
	UserId         int       `description:"用户id"`
}

// 根据openid获取用户关系
func GetUserRecordByOpenId(openId string) (item *UserRecord, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT * FROM user_record WHERE open_id=? `
	err = o.Raw(sql, openId).QueryRow(&item)
	return
}

// 根据openid解除绑定用户关系
func UnBindUserRecordByOpenid(openId string) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	msql := ` UPDATE user_record SET user_id = 0,bind_account="" WHERE open_id = ? `
	_, err = o.Raw(msql, openId).Exec()
	return
}

// 根据用户id和平台id获取用户关系
func GetUserRecordByUserId(userId, platform int) (item *UserRecord, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT * FROM user_record WHERE user_id=? AND create_platform = ?`
	err = o.Raw(sql, userId, platform).QueryRow(&item)
	return
}

// 添加用户关系
func AddUserRecord(record *UserRecord) (recordId int64, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	recordId, err = o.Insert(record)
	return
}

// 根据openid绑定用户关系
func BindUserRecordByOpenid(userId int, openId, bindAccount string) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	msql := " UPDATE user_record SET user_id = ?,bind_account=? WHERE open_id = ? "
	_, err = o.Raw(msql, userId, bindAccount, openId).Exec()
	return
}

// 修改用户微信信息
func ModifyUserRecordInfo(openId, nickName, headimgUrl, city, province, country, sessionKey string, sex, userId int) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `UPDATE user_record SET nick_name=?,headimgurl=?,sex=?,city=?,province=?,country=?,session_key=? WHERE user_id=? and open_id=? `
	_, err = o.Raw(sql, nickName, headimgUrl, sex, city, province, country, sessionKey, userId, openId).Exec()
	return
}

// 修改用户微信信息
func ModifyUserRecordByDetail(openId, unionId, nickName, headimgUrl, city, province, country string, sex, userId int) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `UPDATE user_record SET union_id=?, nick_name=?,headimgurl=?,sex=?,city=?,province=?,country=? WHERE user_id=? and open_id=? `
	_, err = o.Raw(sql, unionId, nickName, headimgUrl, sex, city, province, country, userId, openId).Exec()
	return
}

// 修改用户微信信息
func ModifyUserRecordSessionKey(openId, sessionKey string) (err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `UPDATE user_record SET session_key=? WHERE open_id=? `
	_, err = o.Raw(sql, sessionKey, openId).Exec()
	return
}

// 根据用户id和平台id获取用户关系
func GetUserRecordByMobile(platform int, bindAccount string) (item *OpenIdList, err error) {
	var sql string
	sql = `SELECT open_id,cygx_user_id AS user_id  FROM	cygx_user_record  WHERE	1 = 1  AND cygx_bind_account = ?`
	err = orm.NewOrm().Raw(sql, bindAccount).QueryRow(&item)
	return
}

// 获取该用户第一个的 三方信息（微信头像信息）
func GetUserThirdRecordByUserId(userId int) (item *UserRecord, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT * FROM user_record WHERE user_id = ? order by user_record_id asc`
	err = o.Raw(sql, userId).QueryRow(&item)
	return
}

// 根据手机号获取用户的openid
func GetUserRecordListByMobile(platform int, bindAccount string) (items []*OpenIdList, err error) {
	var sql string
	//if utils.RunMode == "release" {
	//	sql = `SELECT cr.open_id,user_id FROM user_record  as u
	//		INNER JOIN cygx_user_record AS cr ON cr.union_id = u.union_id
	//		WHERE create_platform=? AND bind_account IN (` + bindAccount + `)`
	//} else {
	//	platform = 1
	//	sql = `SELECT open_id,user_id FROM	user_record  WHERE create_platform =? AND bind_account IN (` + bindAccount + `)`
	//}
	sql = `SELECT
			cr.open_id,
			cr.cygx_user_id as  user_id 
		FROM
		  cygx_user_record  as cr 
		WHERE 1= 1	AND cygx_bind_account IN (` + bindAccount + `)`
	_, err = orm.NewOrm().Raw(sql).QueryRows(&items)
	return
}

//// 获取单个用户openid
//func GetOpenIdDetailByMobile(platform int, bindAccount string) (item *OpenIdList, err error) {
//	o := orm.NewOrm()
//	var sql string
//	sql = `SELECT cr.open_id,wu.user_id FROM user_record  as u
//			INNER JOIN cygx_user_record AS cr ON cr.union_id = u.union_id
//			INNER JOIN wx_user AS wu ON wu.mobile = u.bind_account
//			WHERE create_platform=? AND u.bind_account = ?`
//	err = o.Raw(sql, platform, bindAccount).QueryRow(&item)
//	return
//}

func GetOpenIdByUserIds(ids string) (item []*OpenIdList, err error) {
	o := orm.NewOrm()
	var sql string
	sql = ` SELECT
			cr.open_id,
			cr.cygx_user_id as  user_id 
		FROM
		  cygx_user_record  as cr 
		WHERE 1= 1	AND cygx_user_id IN (` + ids + `)`
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

//// 根据手机号获取用户的openid
//func GetUserRecordListByMobileArr(bindAccount []string) (items []*OpenIdList, err error) {
//	lenarr := len(bindAccount)
//	if lenarr == 0 {
//		return
//	}
//	var condition string
//	var pars []interface{}
//	condition = ` AND u.bind_account IN (` + utils.GetOrmInReplace(lenarr) + `)`
//	pars = append(pars, bindAccount)
//	sql := `SELECT cr.open_id,u.user_id
//			FROM user_record  as u
//			INNER JOIN cygx_user_record AS cr ON cr.union_id = u.union_id
//			WHERE u.create_platform=4 ` + condition
//	_, err = orm.NewOrm().Raw(sql, pars).QueryRows(&items)
//	return
//}

// 根据手机号获取用户的openid
func GetUserRecordListByMobileArr(mobiles []string) (items []*OpenIdList, err error) {
	o := orm.NewOrm()
	lenarr := len(mobiles)
	if lenarr == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND u.cygx_bind_account IN (` + utils.GetOrmInReplace(lenarr) + `)`
	pars = append(pars, mobiles)
	sql := `SELECT
			u.open_id,
			u.cygx_user_id AS user_id 
		FROM
			cygx_user_record AS u 
		WHERE
			1 = 1  ` + condition
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 根据用户id和平台id获取用户关系
func GetMfyxUserRecordByMobile(platform int, bindAccount string) (item *OpenIdList, err error) {
	var sql string
	sql = `SELECT open_id,cygx_user_id AS user_id  FROM	cygx_mfyx_gzh_user_record  WHERE	1 = 1  AND cygx_bind_account = ?`
	err = orm.NewOrm().Raw(sql, bindAccount).QueryRow(&item)
	return
}

// 根据手机号获取mfyx用户的openid
func GetMfyxUserRecordListByMobileArr(mobiles []string) (items []*OpenIdList, err error) {
	o := orm.NewOrm()
	lenarr := len(mobiles)
	if lenarr == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND u.cygx_bind_account IN (` + utils.GetOrmInReplace(lenarr) + `)`
	pars = append(pars, mobiles)
	sql := `SELECT
			u.open_id,
			u.cygx_user_id AS user_id 
		FROM
			cygx_mfyx_gzh_user_record AS u 
		WHERE
			1 = 1  ` + condition
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func GetMfyxWxOpenIdByMobileList(mobile string) (items []*OpenIdList, err error) {
	sliceMobile := strings.Split(mobile, ",")
	var mobiles []string
	for _, v := range sliceMobile {
		mobiles = append(mobiles, v)
	}
	o := orm.NewOrm()
	lenarr := len(mobiles)
	if lenarr == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND u.cygx_bind_account IN (` + utils.GetOrmInReplace(lenarr) + `)`
	pars = append(pars, mobiles)
	sql := `SELECT
			u.open_id,
			u.cygx_user_id AS user_id 
		FROM
			cygx_mfyx_gzh_user_record AS u 
		WHERE
			1 = 1  ` + condition
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}
