package models

import (
	"eta/eta_api/global"
	"eta/eta_api/utils"
	"time"
)

type WxUser struct {
	UserId              int64 `gorm:"column:user_id;primaryKey;autoIncrement"`
	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    `gorm:"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 := global.DbMap[utils.DbNameWeekly]
	sql := `SELECT * FROM wx_user WHERE mobile = ? LIMIT 1`
	err = o.Raw(sql, mobile).First(&item).Error
	return
}

// Update 更新wxUser信息
func (WxUser *WxUser) Update(cols []string) (err error) {
	o := global.DbMap[utils.DbNameWeekly]
	err = o.Select(cols).Updates(WxUser).Error
	return
}

// GetWxUserByCompanyIdAndMobile 根据客户ID及手机号获取用户
func GetWxUserByCompanyIdAndMobile(companyId int, mobile string) (item *WxUser, err error) {
	o := global.DbMap[utils.DbNameWeekly]
	sql := ` SELECT * FROM wx_user WHERE company_id = ? AND mobile = ? LIMIT 1 `
	err = o.Raw(sql, companyId, mobile).First(&item).Error
	return
}

// DeleteWxUserAndRecordByUserId 删除用户及第三方信息
func DeleteWxUserAndRecordByUserId(userId int) (err error) {
	to := global.DbMap[utils.DbNameWeekly].Begin()
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

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