package wx_user

import (
	"errors"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/utils"
)

// GetByMobile 根据手机号获取信息
func GetByMobile(mobile string) (wxUser *WxUser, err error) {
	err = global.DEFAULT_MYSQL.Where("mobile = ? ", mobile).First(&wxUser).Error
	return
}

// GetByEmail 根据邮箱号号获取信息
func GetByEmail(email string) (wxUser *WxUser, err error) {
	err = global.DEFAULT_MYSQL.Where("email = ? ", email).First(&wxUser).Error
	return
}

// GetByWhereMap 根据查询条件map获取信息
func GetByWhereMap(where map[string]interface{}) (wxUser *WxUser, err error) {
	cond, whereVal, buildErr := utils.WhereBuild(where)
	if buildErr != nil {
		err = errors.New("系统异常，生成查询语句失败")
		return
	}
	err = global.DEFAULT_MYSQL.Where(cond, whereVal...).First(&wxUser).Error
	return
}

// GetByUserId 根据user_id获取用户信息
func GetByUserId(userId int) (wxUser *WxUser, err error) {
	err = global.DEFAULT_MYSQL.Where("user_id =  ? ", userId).First(&wxUser).Error
	return
}

// GetByUserIds 根据user_id获取用户信息
func GetByUserIds(userIds []uint64) (list []*WxUser, err error) {
	err = global.DEFAULT_MYSQL.Model(WxUser{}).Where("user_id in  ? ", userIds).Scan(&list).Error
	return
}

type OpenIdList struct {
	OpenID string
	UserID int
}

func GetOpenIdList() (items []*OpenIdList, err error) {
	sql := `SELECT DISTINCT ur.open_id,wu.user_id FROM wx_user AS wu 
          INNER JOIN company AS c ON c.company_id = wu.company_id 
          INNER JOIN company_product AS d ON c.company_id=d.company_id
		INNER join user_record  as ur on wu.user_id=ur.user_id
          WHERE ur.open_id != "" AND ur.subscribe=1 and ur.create_platform=1 AND  d.status IN('正式','试用','永续') `

	err = global.DEFAULT_MYSQL.Raw(sql).Scan(&items).Error
	return
}

func ModifyQaAvatarUrl(qaAvatarUrl string, userId uint64) (err error) {
	err = global.DEFAULT_MYSQL.Model(WxUser{}).Where("user_id=?", userId).Update("qa_avatar_url", qaAvatarUrl).Error
	return err
}

func GetOpenIdArrByVarietyTag(varietyTagId int) (items []string, err error) {
	sql := ` SELECT DISTINCT ur.open_id FROM wx_user AS wu 
INNER JOIN company AS c ON c.company_id = wu.company_id 
INNER JOIN company_product AS d ON c.company_id=d.company_id
INNER JOIN user_record  AS ur ON wu.user_id=ur.user_id
INNER JOIN company_report_permission AS e ON d.company_id=e.company_id
INNER JOIN chart_permission AS f ON e.chart_permission_id=f.chart_permission_id
INNER JOIN variety_tag AS g ON f.chart_permission_id=g.chart_permission_id
WHERE ur.open_id != "" AND ur.subscribe=1 AND ur.create_platform=1 AND  d.status IN('正式','试用','永续') AND  e.status IN('正式','试用','永续')
AND g.variety_tag_id=?
ORDER BY FIELD(c.company_id, 16) DESC, ur.user_record_id ASC  `
	err = global.DEFAULT_MYSQL.Raw(sql, varietyTagId).Scan(&items).Error
	return
}
