package models

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

type CygxIndustryFllow struct {
	Id                     int       `orm:"column(id);pk"`
	IndustrialManagementId int       `description:"产业D"`
	UserId                 int       `description:"用户ID"`
	Mobile                 string    `description:"手机号"`
	Email                  string    `description:"邮箱"`
	CompanyId              int       `description:"公司id"`
	CompanyName            string    `description:"公司名称"`
	Type                   int       `description:"操作方式，1报名，2取消报名"`
	CreateTime             time.Time `description:"创建时间"`
	ModifyTime             time.Time `description:"更新时间"`
	RealName               string    `description:"用户实际名称"`
	Source                 int       `description:"来源1查研观向，2查研观向小助手,3勾选全部赛道的用户进行自动关注"`
	FollowType             int       `description:"1,重点关注，3不感兴趣，0默认接受推送"`
	FollowTypeOrder        int       `description:"排序方式，重点关注在最前面，不感兴趣在最后面。1,重点关注，-1不感兴趣，0默认接受推送"`
}

type CygxIndustryFllowRep struct {
	IndustrialManagementId int `description:"产业D"`
	FollowType             int `description:"1,重点关注，3不感兴趣，0默认接受推送"`
}

type IndustryFllowArryReq struct {
	SourceId int    `description:"资源ID"`
	Source   string `description:"资源类型 报告 ：article 、活动 ：activity"`
	DoType   string `description:"操作方式 关注 ：add 、取消关注 ：cancel"`
}

// 添加
func AddCygxIndustryFllow(item *CygxIndustryFllow) (lastId int64, err error) {

	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()
	sql := `DELETE FROM cygx_industry_fllow WHERE user_id=? AND industrial_management_id=? `
	_, err = o.Raw(sql, item.UserId, item.IndustrialManagementId).Exec()
	if err != nil {
		return
	}
	lastId, err = o.Insert(item)
	return
}

// 批量添加
func AddCygxIndustryFllowMulti(items []*CygxIndustryFllow) (err error) {
	o := orm.NewOrm()
	if len(items) > 0 {
		//批量添加新的关注记录
		_, err = o.InsertMulti(len(items), items)
	}
	return
}

type CygxIndustryFllowResp struct {
	Status   int  `description:"1:关注，2：取消关注"`
	GoFollow bool `description:"是否去关注"`
}

func RemoveCygxIndustryFllow(userId, industrialManagementId int) (err error) {
	o := orm.NewOrm()
	sql := `DELETE FROM cygx_industry_fllow WHERE user_id=? AND industrial_management_id=? `
	_, err = o.Raw(sql, userId, industrialManagementId).Exec()
	return
}

// RemoveCygxIndustryFllowArry 多个产业同时取消关注
func RemoveCygxIndustryFllowArry(userId int, condition string, pars []interface{}) (err error) {
	o := orm.NewOrm()
	if condition == "" {
		return
	}
	sql := `DELETE FROM cygx_industry_fllow WHERE user_id=?  ` + condition
	_, err = o.Raw(sql, userId, pars).Exec()
	return
}

// 获取数量
func GetCountCygxIndustryFllow(userId, industrialManagementId int, condition string) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM cygx_industry_fllow WHERE user_id=? AND industrial_management_id=? ` + condition
	err = orm.NewOrm().Raw(sql, userId, industrialManagementId).QueryRow(&count)
	return
}

// 获取关注数量
func GetCountCygxIndustryFllowByType(userId, industrialManagementId int) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM cygx_industry_fllow WHERE user_id=? AND industrial_management_id=?  AND  follow_type = 1  `
	err = orm.NewOrm().Raw(sql, userId, industrialManagementId).QueryRow(&count)
	return
}

// 获取数量
func GetCountCygxIndustryFllowByUid(userId int) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM cygx_industry_fllow WHERE user_id=? `
	err = orm.NewOrm().Raw(sql, userId).QueryRow(&count)
	return
}

// 获取列表信息根据手机号分组
func GetCygxIndustryFllowList(condition string) (items []*CygxIndustryFllow, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industry_fllow  WHERE 1 =1   ` + condition + `  GROUP BY user_id  `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 根据手机号获取用户关注的产业
func GetCygxIndustryFllowListByMobile(mobile string) (items []*CygxIndustryFllow, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industry_fllow WHERE mobile = ?`
	_, err = o.Raw(sql, mobile).QueryRows(&items)
	return
}

// 获取列表信息根据手机号分组
func GetCygxIndustryFllowListByUserId(condition string) (items []*CygxIndustryFllow, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industry_fllow  WHERE 1 =1   ` + condition
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 修改用户关注的相关信息
func UpdateCygxIndustryFllow(wxUser *WxUserItem) (err error) {
	o := orm.NewOrm()
	var sql string
	if wxUser.Mobile != "" {
		sql = `UPDATE cygx_industry_fllow SET email=?,company_id=?,company_name=?,user_id=?,real_name=? WHERE mobile=? `
		_, err = o.Raw(sql, wxUser.Email, wxUser.CompanyId, wxUser.CompanyName, wxUser.UserId, wxUser.RealName, wxUser.Mobile).Exec()
	} else if wxUser.Email != "" {
		sql = `UPDATE cygx_industry_fllow SET mobile=?,company_id=?,company_name=?,user_id=?,real_name=? WHERE mobile=? `
		_, err = o.Raw(sql, wxUser.Mobile, wxUser.CompanyId, wxUser.CompanyName, wxUser.UserId, wxUser.RealName, wxUser.Email).Exec()
	}
	return
}

// 获取用户关注的产业列表
func GetUserFllowIndustrialList(userId int) (items []*CygxIndustryFllow, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			f.user_id,
			m.industry_name,
			m.industrial_management_id 
		FROM
			cygx_industry_fllow AS f
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = f.industrial_management_id 
		WHERE
			1 = 1 
			AND f.user_id = ? `
	_, err = o.Raw(sql, userId).QueryRows(&items)
	return
}

type CygxIndustryFllowCountRep struct {
	IndustrialManagementId int `description:"产业D"`
	Num                    int `description:"数量"`
}

// 获取产业被关注的数量
func GetUserFllowIndustrialCountList() (items []*CygxIndustryFllowCountRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			COUNT( 1 ) AS num,
			f.industrial_management_id 
		FROM
			cygx_industry_fllow AS f
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = f.industrial_management_id 
		WHERE
			1 = 1 
		GROUP BY
			f.industrial_management_id 
		ORDER BY
			num DESC 
			LIMIT 30 `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// GetUserFllowIndustrialListByUserIdAndIndustrial 通过用户ID 跟产业ID获取用户关注的产业列表
func GetUserFllowIndustrialListByUserIdAndIndustrial(userIds, industrials string) (items []*CygxIndustryFllow, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industry_fllow 
			WHERE 1 = 1 
		AND user_id IN ( ` + userIds + ` ) 
		AND industrial_management_id IN ( ` + industrials + `) `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取某个用户关注某个行业下的产业数量
func GetCountCygxIndustryFllowByUidAndChartPermissionId(userId, ChartPermissionId int) (count int, err error) {
	sql := `SELECT
			COUNT( 1 ) AS count 
		FROM
			cygx_industry_fllow AS f
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = f.industrial_management_id 
		WHERE
			user_id = ? 
			AND m.chart_permission_id = ? `
	err = orm.NewOrm().Raw(sql, userId, ChartPermissionId).QueryRow(&count)
	return
}

// GetTopIndustryFollowData 获取关注度最高的产业关注数据
func GetTopIndustryFollowData(startSize, pageSize int, condition string, pars []interface{}) (list []*IndustrialManagement, err error) {
	sql := `SELECT
				man.*
			FROM
                cygx_industrial_management AS man 
			WHERE 1 = 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY
				one_month_follow_num DESC , man.industrial_management_id DESC 
			LIMIT ?,?`
	_, err = orm.NewOrm().Raw(sql, pars, startSize, pageSize).QueryRows(&list)
	return
}

// 列表
func GetCygxIndustryFllowListByCon(condition string, pars []interface{}) (items []*CygxIndustryFllow, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industry_fllow as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	//sql += ` LIMIT ?,?  `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

type CygxIndustryFllowNumResp struct {
	IndustrialManagementId int `description:"产业D"`
	Total                  int `description:"关注数量"`
}

// 获取用户关注的产业列表
func GetIndustrialManagementOneMonthFollowNum() (items []*CygxIndustryFllowNumResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			COUNT( 1 ) AS total,
			industrial_management_id 
		FROM
			cygx_industry_fllow AS idf 
		WHERE
			1 = 1 
			AND create_time > '%s' 
			AND create_time < '%s' 
			AND source != 3
		GROUP BY
			industrial_management_id `
	sql = fmt.Sprintf(sql, time.Now().AddDate(0, -1, 0).Format(utils.FormatDate), time.Now().Format(utils.FormatDate))
	_, err = o.Raw(sql).QueryRows(&items)
	return
}
