package cygx

import (

	//"hongze/hongze_admin/models"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type CygxActivitySpecialTrip struct {
	Id             int       `orm:"column(id);pk"`
	UserId         int       `description:"用户id,多个用,隔开"`
	ActivityId     int       `description:"活动ID"`
	CreateTime     time.Time `description:"创建时间"`
	Mobile         string    `description:"手机号"`
	Email          string    `description:"邮箱号"`
	CompanyId      int       `description:"公司ID"`
	CompanyName    string    `description:"公司名称"`
	RealName       string    `description:"用户实际名称"`
	SellerName     string    `description:"所属销售"`
	AdminId        int       `description:"销售/管理员ID"`
	Source         int       `description:"来源，1小程序，2后台添加"`
	IsMeeting      int       `description:"是否到会"`
	OutboundMobile string    `description:"外呼手机号"`
	CountryCode    string    `description:"手机国家区号"`
}

type CygxActivitySpecialTripResp struct {
	Id             int    `description:"ID"`
	UserId         int    `description:"用户id"`
	ActivityId     int    `description:"活动ID"`
	CreateTime     string `description:"创建时间"`
	Mobile         string `description:"手机号"`
	Email          string `description:"邮箱号"`
	CompanyId      int    `description:"公司ID"`
	CompanyName    string `description:"公司名称"`
	RealName       string `description:"用户实际名称"`
	SellerName     string `description:"所属销售"`
	AdminId        int    `description:"销售/管理员ID"`
	Source         int    `description:"来源，1小程序，2后台添加"`
	OutboundMobile string `description:"外呼手机号"`
	CountryCode    string `description:"手机国家区号"`
	SpecialType    int    `description:"调研形式、 1 线上 ， 2 线下"`
}

// 修改外呼电话以及区号
type ActivitySpecialTripCancelReq struct {
	UserId     int `description:"用户id"`
	ActivityId int `description:"活动ID"`
}

func GetActivitySpecialTripCountByActivityId(activityId int) (count int, err error) {
	sqlCount := `SELECT
					COUNT( 1 ) AS count 
				FROM
					cygx_activity_special_trip AS s
				WHERE
					s.is_cancel = 0 
					AND s.activity_id = ? `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, activityId).QueryRow(&count)
	return
}

func GetActivitySpecialTripCountByThisUser(activityId int, uids string) (count int, err error) {
	sqlCount := `SELECT COUNT(1) AS count FROM cygx_activity_special_trip WHERE is_cancel = 0 AND activity_id=? AND user_id IN (` + uids + `) `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, activityId).QueryRow(&count)
	return
}

// 获取用户报名数量
func GetActivitySpecialTripCount(uid, activityId int) (count int, err error) {
	sqlCount := `SELECT COUNT(1) AS count FROM cygx_activity_special_trip WHERE is_cancel=0   AND user_id=? AND activity_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, uid, activityId).QueryRow(&count)
	return
}

// 新增预约人数
func AddCygxActivitySpecialTrip(items []*CygxActivitySpecialTrip, itemsBill []*CygxActivitySpecialTripBill, itemsMeet []*CygxActivitySpecialMeetingDetail) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	var count int
	var sql string
	//添加会议提醒
	for _, item := range items {
		sql = `SELECT COUNT(1) AS count FROM cygx_activity_special_trip WHERE user_id=? AND activity_id=? `
		err = to.Raw(sql, item.UserId, item.ActivityId).QueryRow(&count)
		if err != nil {
			return
		}
		if count == 0 {
			_, err = to.Insert(item)
		} else {
			sql := `UPDATE cygx_activity_special_trip SET  is_cancel=0 ,create_time = NOW() WHERE user_id=? AND activity_id=? `
			_, err = to.Raw(sql, item.UserId, item.ActivityId).Exec()
		}
		if err != nil {
			return
		}
	}

	//添加流水记录
	//倒序插入，让流水表看起来是正的
	for i := len(itemsBill) - 1; i >= 0; i-- {
		_, err = to.Insert(itemsBill[i])
		if err != nil {
			return
		}
	}

	//添加到会信息记录查询表
	for _, item := range itemsMeet {
		_, err = to.Insert(item)
		if err != nil {
			return
		}
	}
	return
}

type GetAppointmentSpecialListRsep struct {
	Source        int    `description:"来源 专项调研：1 "`
	ActivityId    int    `description:"活动ID"`
	Total         int    `description:"总人数"`
	MyTotal       int    `description:"本人名下客户"`
	IsLimitPeople int    `description:"是否限制人数 1是，0否"`
	MemberType    string `description:"管理员身份 Admin：超级管理员、权益管理员、权益研究员、专家组;GroupLeader:组长；Sale:销售"`
	SpecialType   int    `description:"调研形式、 1 线上 ， 2 线下"`
	List          []*CygxActivitySpecialTripResp
}

func GetCygxActivitySpecialTripList(activityId int, condition string) (item []*CygxActivitySpecialTripResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT s.*,
					a.activity_time,
					a.special_type
			FROM
			cygx_activity_special_trip AS s
			INNER JOIN cygx_activity_special AS a ON a.activity_id = s.activity_id
			WHERE a.activity_id = ?  ` + condition + `  GROUP BY s.user_id   ORDER BY s.create_time DESC `
	_, err = o.Raw(sql, activityId).QueryRows(&item)
	return
}

func GetActivitySpecialTripTotal(activityId int, sqlStr string) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT COUNT(*) FROM
			cygx_activity_special_trip AS s
			LEFT JOIN cygx_activity_special AS a ON a.activity_id = s.activity_id
			WHERE
			s.activity_id = ? ` + sqlStr + `
            GROUP BY s.user_id)`
	sql = `SELECT COUNT(*)  as count FROM (` + sql + ` a`

	err = o.Raw(sql, activityId).QueryRow(&count)
	return
}

// ActivitySpecialTripCancel 取消报名
func ActivitySpecialTripCancel(isValid, activityId, uid int) (err error) {
	o, err := orm.NewOrmUsingDB("hz_cygx").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()
	sql := `UPDATE cygx_activity_special_trip SET   is_valid= ?, is_cancel = 1  WHERE activity_id=? AND user_id = ? `
	_, err = o.Raw(sql, isValid, activityId, uid).Exec()
	if err != nil {
		return
	}
	//删除到会记录表信息
	sql = ` DELETE FROM cygx_activity_special_meeting_detail  WHERE activity_id = ?  AND user_id = ?  `
	_, err = o.Raw(sql, activityId, uid).Exec()
	return
}

// 获取报名了的用户IDs
func GetSpecialTripUserIds(activityId int, uIds string) (signupUids string, err error) {
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT s.user_id SEPARATOR ',' ) AS signupUids 
			FROM cygx_activity_special_trip AS s
            WHERE s.activity_id = ? AND s.is_cancel = 0 AND s.user_id not IN (` + uIds + `)`
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sql, activityId).QueryRow(&signupUids)
	return
}

// 修改外呼手机号
func SpecialTripOutboundMobileEdit(id int, outboundMobile, countryCode string) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_activity_special_trip SET outbound_mobile = ?,country_code=?  WHERE id=? `
	_, err = o.Raw(sql, outboundMobile, countryCode, id).Exec()
	return
}

func GetCygxActivitySpecialTripListByActivityId(activityId int) (item []*CygxActivitySpecialTripResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT *
			FROM
			cygx_activity_special_trip  
			WHERE activity_id = ?   AND is_cancel = 0 `
	_, err = o.Raw(sql, activityId).QueryRows(&item)
	return
}

// 获取公司报名的记录
func GetCygxActivitySpecialTripListByComapnyId(companyId int) (item []*CygxActivitySpecial, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			t.*,
			a.chart_permission_id,
			a.chart_permission_name
		FROM
			cygx_activity_special_trip AS t
			INNER JOIN cygx_activity_special AS a ON a.activity_id = t.activity_id 
		WHERE
			t.company_id = ?  AND t.is_valid = 1 `
	_, err = o.Raw(sql, companyId).QueryRows(&item)
	return
}

// 获取空降的公司报名的记录
func GetCygxActivitySpecialTripAirborneListByComapnyId(companyId int) (item []*CygxActivitySpecial, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			t.*,
			a.chart_permission_id,
			a.chart_permission_name
		FROM
			cygx_activity_special_meeting_detail AS t
			INNER JOIN cygx_activity_special AS a ON a.activity_id = t.activity_id 
		WHERE
			t.company_id = ?  AND t.is_airborne = 1 `
	_, err = o.Raw(sql, companyId).QueryRows(&item)
	return
}

type ActivitySpecialSignupTempMsgReq struct {
	ActivityIds   string `description:"活动id，用,隔开"`
	SendGroup     string `description:"发送对象，1已报名 用,隔开"`
	ResearchTheme string `description:"调研主题"`
	Content       string `description:"推送内容"`
}

// 列表
func GetCygxActivitySpecialTripListCondition(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxActivitySpecialTrip, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_special_trip as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	if startSize+pageSize > 0 {
		sql += ` LIMIT ?,?  `
		_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	} else {
		_, err = o.Raw(sql, pars).QueryRows(&items)
	}
	return
}

// 获取某一用户的报名的数量
func GetUserActivitySpecialTripCount(uid, activityId int) (count int, err error) {
	sqlCount := `SELECT COUNT(1) AS count FROM cygx_activity_special_trip  WHERE  user_id=?  AND   activity_id =? `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, uid, activityId).QueryRow(&count)
	return
}

func UpdateSpecialTrip(isValid, isCancel, userId, activityId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_activity_special_trip SET is_valid = ?,create_time=NOW(),is_cancel=?  WHERE user_id=? AND activity_id=? `
	_, err = o.Raw(sql, isValid, isCancel, userId, activityId).Exec()
	return
}
