package models

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

type WxUser struct {
	UserId              int64 `orm:"column(user_id);pk"`
	Mobile              string
	Email               string
	CompanyId           int
	RealName            string `description:"姓名"`
	NickName            string `description:"昵称"`
	CreatedTime         time.Time
	MobileTwo           string `description:"备用手机号"`
	BusinessCardUrl     string `description:"名片"`
	IsMaker             int    `description:"是否决策人，1:是，0:否"`
	Position            string `description:"职位"`
	Sex                 int    `description:"普通用户性别，1为男性，2为女性"`
	DepartmentName      string `description:"联系人部门"`
	RegisterTime        time.Time
	RegisterPlatform    int
	Remark              string    `description:"备注"`
	CountryCode         string    `description:"区号，86、852、886等"`
	OutboundMobile      string    `description:"外呼手机号"`
	OutboundCountryCode string    `description:"外呼手机号区号，86、852、886等"`
	LastUpdatedTime     time.Time `description:"最近一次更新时间"`
	IsDeal              int       `description:"是否标记处理 0-未处理 1-已处理"`
	OpenId              string    `orm:"column(open_id)" description:"微信openid"`
	Headimgurl          string    `description:"用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空"`
	UserLabel           string    `description:"查研观向用户标签"`
}

func AddWxUser(item *WxUser) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("weekly")
	lastId, err = o.Insert(item)
	return
}

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

// GetWxUserByMobileCountryCode 根据手机号和区号获取用户信息
func GetWxUserByMobileCountryCode(mobile, countryCode string) (item *WxUser, err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := `SELECT * FROM wx_user WHERE mobile = ? `
	sql += ` and country_code in ("","` + countryCode + `") `
	sql += ` LIMIT 1 `
	err = o.Raw(sql, mobile).QueryRow(&item)
	return
}

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

// 更新wxUser信息
func (wxUser *WxUser) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("weekly")
	_, err = o.Update(wxUser, cols...)
	return
}

type PotentialUserItem struct {
	UserId          int       `description:"用户id"`
	RealName        string    `description:"姓名"`
	CountryCode     string    `description:"区号，86、852、886等"`
	Mobile          string    `description:"手机号"`
	Email           string    `description:"邮箱"`
	CreatedTime     string    `description:"注册时间"`
	ApplyMethod     int       `description:"0:未申请，1:已付费客户申请试用，2:非客户申请试用"`
	CompanyName     string    `description:"客户名称"`
	ViewTotal       int       `description:"累计阅读次数"`
	LastViewTime    time.Time `json:"-" description:"最后一次阅读时间"`
	LastViewTimeStr string    `description:"最后一次阅读时间"`
	FromType        string    `description:"report:研报，teleconference:电话会"`
	BusinessCardUrl string    `description:"名片"`
	Source          int       `description:"来源,1:微信端,2:pc网页端，3:查研观向小程序,4:每日咨询，5:电话会"`
	IsDeal          int       `description:"是否标记处理，0是未处理，1是已处理"`
}

type PotentialUserListResp struct {
	List   []*PotentialUserItem
	Paging *paging.PagingItem `description:"分页数据"`
}

// GetWxUserByCompanyIdAndMobile 根据客户ID及手机号获取用户
func GetWxUserByCompanyIdAndMobile(companyId int, mobile string) (item *WxUser, err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := ` SELECT * FROM wx_user WHERE company_id = ? AND mobile = ? LIMIT 1 `
	err = o.Raw(sql, companyId, mobile).QueryRow(&item)
	return
}

// DeleteWxUserAndRecordByUserId 删除用户及第三方信息
func DeleteWxUserAndRecordByUserId(userId int) (err error) {
	o := orm.NewOrmUsingDB("weekly")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 删除wx_user
	userSql := ` DELETE FROM wx_user WHERE user_id = ? LIMIT 1 `
	_, err = to.Raw(userSql, userId).Exec()
	// 删除user_record
	if err == nil {
		recordSql := ` DELETE FROM user_record WHERE user_id = ? `
		_, err = to.Raw(recordSql, userId).Exec()
	}

	return
}

// 获取这个公司下面所有用户的手机号
func SetUserSubscribe(openId string) (err error) {
	o := orm.NewOrmUsingDB("weekly")
	sql := ` UPDATE user_record SET subscribe=1,subscribe_time=NOW() WHERE open_id=? `
	_, err = o.Raw(sql, openId).Exec()
	return
}

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正方形头像），用户没有头像时该项为空"`
	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:"是否弹窗过绑定外呼手机号区号"`
	IsMaker             int       `description:"是否是决策人"`
	Source              int
}
