package models

import (
	"github.com/beego/beego/v2/client/orm"
	"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 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
}

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

// 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
}
