package cygx

import (
	"fmt"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/utils"

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

// 活动详情
type CygxSignupList struct {
	ActivityId                int    `orm:"column(activity_id);pk";description:"活动ID 等于0新增活动，大于0修改活动"`
	ActivityName              string `description:"活动名称"`
	ActivityTypeName          string `description:"活动类型名称"`
	ChartPermissionName       string `description:"行业名称"`
	ChartPermissionNames      string `description:"行业名称辅助字段，区分研选子分类"`
	LimitPeopleNum            int    `description:"限制的人数数量"`
	ActivityTime              string `description:"活动时间"`
	ActivityTimeText          string `description:"活动时间带文字"`
	SignupPeopleNum           int    `description:"报名人数/预约外呼人数"`
	SignupFailPeopleNum       int    `description:"报名/预约外呼失败人数"`
	AskNum                    int    `description:"带问人数"`
	AppointmentPeopleNum      int    `description:"预约纪要人数"`
	ReminderPeopleNum         int    `description:"设置会议提醒人数"`
	IsShowAppointment         bool   `description:"是否展示预约纪要"`
	IsHideAppointment         int    `description:"是否隐藏预约纪要按钮  1是，0 否"`
	ActivityTypeId            int    `description:"活动类型id"`
	Label                     string `description:"标签"`
	ActiveState               int    `description:"活动进行状态 未开始：1、进行中2、已结束3"`
	PublishStatus             int    `description:"发布状态 1已发布，0未发布"`
	TemporaryLabel            string `description:"临时标签"`
	YidongActivityId          string `description:"易董的活动ID"`
	IsCanAppointmentMinutes   int    `description:"是否可预约纪要 1是 ，0 否 默认0 "`
	IsCancel                  int    `description:"是否取消，1是，0否"`
	IsYidongConduct           int    `description:"是否属于易董办会 1：是 、0：否"`
	IsResearchPoints          int    `description:"是否为研选扣点  1是，0否"`
	ChartPermissionNameDeputy string `description:"副行业名称"`
}

type GetCygxSignupListRep struct {
	Paging *paging.PagingItem `description:"分页数据"`
	List   []*CygxSignupList
}

// 获取数量
func GetCygxSignupCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_activity as art WHERE 1= 1  `
	if condition != "" {
		sqlCount += condition
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

// 列表
func GetCygxSignupListAll(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxSignupList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT 
		( SELECT COUNT( 1 ) FROM cygx_activity_signup AS s WHERE s.activity_id = art.activity_id  AND s.is_cancel = 0 AND  s.do_fail_type = 0 AND  s.company_id != 16 ) AS signup_people_num,
		( SELECT COUNT( 1 ) FROM cygx_activity_signup AS s  WHERE s.activity_id = art.activity_id  AND s.is_cancel = 0 AND  s.fail_type >= 1) AS signup_fail_people_num, 
		( SELECT COUNT( 1 ) FROM cygx_activity_help_ask AS k  WHERE k.activity_id = art.activity_id ) AS ask_num, 
		( SELECT COUNT( 1 ) FROM cygx_activity_appointment AS ap  WHERE ap.activity_id = art.activity_id ) AS appointment_people_num,
		( SELECT COUNT( 1 ) FROM cygx_activity_meeting_reminder AS ap    WHERE ap.activity_id = art.activity_id ) AS reminder_people_num,
		art.* FROM cygx_activity as art
		WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type CygxAppointmentList struct {
	Id             int    `orm:"column(id);pk"`
	ActivityId     int    `description:"活动ID"`
	ActivityTime   string `description:"活动时间"`
	UserId         int    `description:"用户ID"`
	CreateTime     string `description:"创建时间"`
	Mobile         string `description:"手机号"`
	OutboundMobile string `description:"外呼手机号"`
	CountryCode    string `description:"手机国家区号"`
	CompanyName    string `description:"公司名称"`
	CompanyId      int    `description:"公司ID"`
	RealName       string `description:"姓名"`
	FailType       int    `description:"失败原因，0，未失败，1总人数已满，2单机构超限制，3，爽约次数超限"`
	//MeetingType int    `description:"参会方式，0，无，1预约外呼，2自主拨入"`
	SellerName          string `description:"销售姓名"`
	PsellerName         string `description:"销售姓名"`
	SignupType          int    `description:"报名方式，1预约外呼，2自主拨入，3我要报名"`
	YidongExamineStatus int    `description:"易董活动报名审核状态0审核中，1：审核通过、2审核不通过"`
	Email               string `description:"邮箱"`
}

type CygxSignupUser struct {
	UserId     int `description:"用户ID"`
	ActivityId int `description:"活动ID"`
}

type CygxSignupId struct {
	SignupId    int `description:"报名ID"`
	CancelClass int `description:"取消类型 0取消报名，1取消外呼"`
}

// 预约外呼列表
func GetCygxAppointmentLisssst(activityId int) (items []*CygxAppointmentList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_signup  WHERE activity_id= ? `
	_, err = o.Raw(sql, activityId).QueryRows(&items)
	return
}

func GetCygxAppointmentList(article_id int, sqlStr string) (item []*CygxAppointmentList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT s.*
			FROM
			cygx_activity_signup AS s
			LEFT JOIN cygx_activity AS a ON a.activity_id = s.activity_id
			WHERE a.activity_id = ?  AND s.do_fail_type = 0 ` + sqlStr + `  GROUP BY s.user_id   ORDER BY s.create_time DESC `
	_, err = o.Raw(sql, article_id).QueryRows(&item)
	return
}

type GetAppointmentListRep struct {
	ExcelType        string `description:"EXcel下载类型 AppointmentCall：预约外呼、ExpertSalon：专家沙龙报名、Teleconference：公司调研电话会、OfflineResearch：公司线下调研 、CClass： C类电话会 、YiDong：易董 "`
	ActivityId       int    `description:"活动ID"`
	Total            int    `description:"总人数"`
	MyTotal          int    `description:"本人名下客户"`
	IsLimitPeople    int    `description:"是否限制人数 1是，0否"`
	MemberType       string `description:"管理员身份 Admin：超级管理员、权益管理员、权益研究员、专家组;GroupLeader:组长；Sale:销售"`
	ActivityType     int    `description:"1线上 ，0 线下"`
	IsYidongConduct  int    `description:"是否属于易董办会 1：是 、0：否"`
	IsResearchPoints int    `description:"是否为研选扣点  1是，0否"`
	List             []*CygxAppointmentList
}

func GetCygxAppointmentCount(articleId int, sqlStr string) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT COUNT(*) FROM
			cygx_activity_signup AS s
			LEFT JOIN cygx_activity 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, articleId).QueryRow(&count)
	return
}

// 新增外呼人员
type GetOutboundPersonnelListRep struct {
	List []*GetOutboundPersonnelRep
}

type GetOutboundPersonnelRep struct {
	UserId      int    `description:"用户id"`
	RealName    string `description:"姓名"`
	Mobile      string `description:"手机号"`
	CompanyName string `description:"公司名称"`
}

// 列表
func GetOutboundPersonnelList(name string) (items []*GetOutboundPersonnelRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT u.user_id,u.real_name,u.mobile,p.company_name FROM wx_user as u INNER JOIN company AS p ON p.company_id = u.company_id WHERE  real_name LIKE '%` + name + `%'  AND u.company_id >1   GROUP BY u.user_id  ORDER BY user_id ASC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

type AddOutboundPersonnelItm struct {
	UserIds     string `description:"用户id,多个用,隔开"`
	ActivityIds string `description:"活动ID，多个用,隔开"`
}

type AddOutboundPersonnelJsonItm struct {
	JsonStar    string `description:"报名信息json字符串 ：Uid 用户ID，int类型 。Type string类型，报名方式，1预约外呼，2自主拨入 "`
	ActivityIds string `description:"活动ID，多个用,隔开"`
}

type CygxActivitySignup 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:"公司名称"`
	OutboundMobile string    `description:"外呼手机号"`
	CountryCode    string    `description:"手机国家区号"`
	Source         int       `description:"来源，1小程序，2后台添加"`
	SignupType     int       `description:"报名方式，1预约外呼，2自主拨入，3我要报名"`
	RealName       string    `description:"用户实际名称"`
	SellerName     string    `description:"所属销售"`
}

// 我的日程
type CygxMySchedule struct {
	Id          int       `orm:"column(id);pk"`
	ActivityId  int       `description:"活动ID"`
	UserId      int       `description:"用户ID"`
	CreateTime  time.Time `description:"创建时间"`
	Mobile      string    `description:"手机号"`
	Email       string    `description:"邮箱"`
	CompanyId   int       `description:"公司id"`
	CompanyName string    `description:"公司名称"`
}

type UserAndCompanyName struct {
	UserId              int `orm:"column(user_id);pk"`
	Mobile              string
	Email               string
	CompanyId           int
	CompanyName         string `description:"公司名称"`
	CountryCode         string `description:"手机国家区号"`
	OutboundMobile      string `description:"外呼手机号"`
	OutboundCountryCode string `description:"外呼手机号区号"`
	SellerName          string `description:"所属销售"`
	RealName            string `description:"真实姓名"`
}

func GetUserAndCompanyNameList(uid int) (item *UserAndCompanyName, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
			u.*,
			c.company_name,
			GROUP_CONCAT( DISTINCT p.seller_name SEPARATOR '/' ) AS seller_name 
		FROM
			wx_user AS u
			INNER JOIN company AS c ON c.company_id = u.company_id
			LEFT JOIN company_product AS p ON p.company_id = u.company_id 
		WHERE
			user_id = ?`
	err = o.Raw(sql, uid).QueryRow(&item)
	return
}

func GetUserAndCompanyNameListByUids(uids string) (items []*UserAndCompanyName, err error) {
	o := orm.NewOrm()
	sql := ` SELECT u.*,c.company_name FROM wx_user AS u
	INNER JOIN company AS c ON c.company_id = u.company_id
	WHERE user_id IN (` + uids + `)`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 新增预约人数
func AddCygxActivitySignup(items []*CygxActivitySignup, itemsAppointment []*CygxActivityAppointment, mapYidongActivity map[int]int) (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()
		}
	}()
	//添加预约纪要部分
	if len(itemsAppointment) > 0 {
		for _, item := range itemsAppointment {
			var count int
			sql := `SELECT COUNT(1) AS count FROM cygx_activity_appointment 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)
				if err != nil {
					return
				}
			}
		}
	}
	//添加会议提醒
	for _, item := range items {
		var count int
		sql := `SELECT COUNT(1) AS count FROM cygx_my_schedule WHERE user_id=? AND activity_id=? `
		err = to.Raw(sql, item.UserId, item.ActivityId).QueryRow(&count)
		if err != nil {
			return
		}
		//如果是易懂的活动就不加入日程
		if count == 0 && mapYidongActivity[item.ActivityId] == 0 {
			itemMy := new(CygxMySchedule)
			itemMy.UserId = item.UserId
			itemMy.ActivityId = item.ActivityId
			itemMy.CreateTime = time.Now()
			itemMy.Mobile = item.Mobile
			itemMy.Email = item.Email
			itemMy.CompanyId = item.CompanyId
			itemMy.CompanyName = item.CompanyName
			_, err = to.Insert(itemMy)
			if err != nil {
				return
			}
		}
		sql = `SELECT COUNT(1) AS count FROM cygx_activity_signup 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_signup SET  is_cancel=0, do_fail_type = 0 ,create_time = NOW() WHERE user_id=? AND activity_id=? `
			_, err = to.Raw(sql, item.UserId, item.ActivityId).Exec()
		}
	}
	return
}

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

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

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

//end

// 报名失败
type FailSignupListRep struct {
	Id               int    `orm:"column(id);pk;"description:"报名ID"`
	ActivityId       int    `description:"活动ID"`
	CreateTime       string `description:"创建时间"`
	Mobile           string `description:"手机号"`
	CompanyName      string `description:"公司名称"`
	CompanyId        int    `description:"公司ID"`
	RealName         string `description:"姓名"`
	UserId           int    `description:"用户id"`
	SellerName       string `description:"销售姓名"`
	PsellerName      string `description:"销售姓名"`
	FailType         int    `description:"失败原因，0，未失败，1总人数已满，2单机构超限制，3，爽约次数超限"`
	DoFailType       int    `description:"报名失败之后的操作，失败原因，0，未失败，1总人数已满，2单机构超限制，3，爽约次数超限"`
	SalonOperation   bool   `description:"操作按钮1，true,加入报名，false 限制报名"`
	CallOperation    int    `description:"操作按钮2，1预约外呼，2自主拨入，3限制报名"`
	IsAdminAddSignup int    `description:"（多余字段不使用）"`
	MeetingType      int    `description:"（多余字段不使用）"`
	IsMeeting        int    `description:"是否到会 ，1是， 0否"`
	SignupType       int    `description:"报名方式，1预约外呼，2自主拨入，3我要报名"`
}

type GetFailSignupListRep struct {
	ExcelType  string `description:"EXcel下载类型 AppointmentCall：预约外呼、ExpertSalon：专家沙龙报名、Teleconference：公司调研电话会、OfflineResearch：公司线下调研 "`
	MemberType string `description:"管理员身份 Admin：超级管理员、权益管理员、权益研究员、专家组;GroupLeader:组长；Sale:销售"`
	//ActivityId    int    `description:"活动ID"`
	Total         int  `description:"预约外呼总人数"`
	MyTotal       int  `description:"预约外呼本人名下客户"`
	IsLimitPeople int  `description:"是否限制人数 1是，0否"`
	IsFull        bool `description:"报名人数是否已满"`
	List          []*FailSignupListRep
}

func GetFailSignupList(activity_id int, sqlStr string) (item []*FailSignupListRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT s.* ,a.is_limit_people
			FROM
			cygx_activity_signup AS s
			LEFT JOIN cygx_activity AS a ON a.activity_id = s.activity_id
			WHERE a.activity_id = ?` + sqlStr + ` GROUP BY s.id  ORDER BY s.create_time DESC `
	_, err = o.Raw(sql, activity_id).QueryRows(&item)
	return
}

//end

type SignupId struct {
	Id int `orm:"column(id);pk;"description:"报名ID"`
}

type SignupIdCall struct {
	Id              int `description:"报名ID"`
	OperationStatus int `description:"操作方式：1预约外呼，2自主拨入，3限制报名"`
}

// 获取失败数量
func GetCygxSignupCountFile(id int) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_activity_signup  WHERE id= ?`
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, id).QueryRow(&count)
	return
}
func GetCygxSignupDetailById(id int) (item *FailSignupListRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_signup  WHERE id=?`
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func GetCygxSignupDetailByUid(id int) (item *FailSignupListRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_signup  WHERE user_id=? LIMIT 1`
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

// 加入报名限制报名
func SalonSignupEdit(newIsAdminAddSignup, doFailType, id int, item *CygxActivitySignup) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	var count int
	sql := `SELECT COUNT(1) AS count FROM cygx_activity_meeting_reminder  WHERE user_id=?  AND activity_id=?  `
	err = to.Raw(sql, item.UserId, item.ActivityId).QueryRow(&count)
	if err != nil {
		return
	}
	sql = `UPDATE cygx_activity_signup SET is_admin_add_signup=?,do_fail_type=? WHERE id=? `
	_, err = to.Raw(sql, newIsAdminAddSignup, doFailType, id).Exec()
	if doFailType == 0 && count == 0 {
		//加入报名后并添加到我的日程
		itemMy := new(CygxMySchedule)
		itemMy.UserId = item.UserId
		itemMy.ActivityId = item.ActivityId
		itemMy.CreateTime = time.Now()
		itemMy.Mobile = item.Mobile
		itemMy.Email = item.Email
		itemMy.CompanyId = item.CompanyId
		itemMy.CompanyName = item.CompanyName
		_, err = to.Insert(itemMy)
		if err != nil {
			return
		}
	} else {
		//删除我的日程
		if count == 0 {
			sql = `DELETE  FROM cygx_my_schedule   WHERE user_id=?  AND activity_id=? `
			_, err = to.Raw(sql, item.UserId, item.ActivityId).Exec()
			if err != nil {
				return
			}
		}
	}
	return
}

func CallSignupEditByStatus3(doFailType, id int, item *CygxMySchedule) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	sql := `UPDATE cygx_activity_signup SET is_admin_add_signup=0, do_fail_type = ?  WHERE id=? `
	_, err = to.Raw(sql, id, doFailType).Exec()
	if err != nil {
		return
	}
	sql = `DELETE  FROM cygx_my_schedule   WHERE user_id=?  AND activity_id=? `
	_, err = to.Raw(sql, item.UserId, item.ActivityId).Exec()
	if err != nil {
		return
	}
	return
}

func CallSignupEditByStatus1_2(operationStatus, id int, item *CygxMySchedule) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	var count int
	sql := `UPDATE cygx_activity_signup SET is_admin_add_signup = 1,do_fail_type=0, signup_type =?  WHERE id=? `
	_, err = to.Raw(sql, operationStatus, id).Exec()
	if err != nil {
		return
	}
	sql = `SELECT COUNT(1) AS count FROM cygx_my_schedule 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)
	}

	return
}

//报名信息Excel下载

type SignupExportRep struct {
	Mobile         string `description:"手机号"`
	CompanyName    string `description:"公司名称"`
	RealName       string `description:"姓名"`
	CountryCode    string `description:"区号"`
	SellerName     string `description:"销售姓名"`
	OutboundMobile string `description:"外呼手机号"`
}

type CygxActivitySignupList struct {
	Id          int    `orm:"column(id);pk"`
	UserId      int    `description:"用户id"`
	ActivityId  int    `description:"活动ID"`
	CompanyName string `description:"公司名称"`
	RealName    string `description:"姓名"`
	CreateTime  string `description:"创建时间"`
	IsMeeting   int    `description:"是否到会 ，1是， 0否"`
	Operation   bool   `description:"操作按钮，true,到会，false 未到会"`
	Channel     int    `description:"报名渠道，0 空降、 1小程序报名"`
	SigninTime  string `description:"签到时间"`
	SellerName  string `description:"所属销售"`
	Mobile      string `description:"手机号"`
	Email       string `description:"邮箱"`
	CompanyId   int    `description:"公司id"`
	IsAirborne  int    `description:"是否属于空降  1.是 ，0否"`
}
type CygxActivitySignupListRep struct {
	ActivityId int `description:"活动ID"`
	List       []*CygxActivitySignupList
	ListSignin []*CygxActivitySignin
}

// 预约外呼列表
func GetCygxActivitySignup(condition string) (items []*CygxActivitySignupList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT s.*  FROM cygx_activity_signup  as s 
	  WHERE 1 =1 ` + condition
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取用户报名数量
func GetActivitySignupNomeetingCount(activityId int) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sqlCount := `SELECT
	COUNT( 1 ) count 
FROM
	cygx_activity_signup AS s
	INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id 
WHERE
	1 = 1 
	AND a.is_limit_people > 0 
	AND s.is_meeting = 0 
	AND a.is_submit_meeting = 1
	AND a.activity_id = ?`
	err = o.Raw(sqlCount, activityId).QueryRow(&count)
	return
}

// 获取用户报名列表
func GetActivitySignupNomeetingCountList(activityId int) (items []*CygxActivitySignupList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
	s.*
FROM
	cygx_activity_signup AS s
	INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id 
WHERE
	1 = 1 
	AND s.do_fail_type = 0
	AND s.is_meeting = 0
	AND a.activity_id = ?`
	_, err = o.Raw(sql, activityId).QueryRows(&items)
	return
}

// 获取用户爽约次数
func GetActivitySignupNomeetingCountByUid(uid int) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sqlCount := `SELECT
	COUNT( 1 ) count 
FROM
	cygx_activity_signup AS s
	INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id 
WHERE
	1 = 1 
	AND a.is_limit_people > 0 
	AND s.is_meeting = 0 
	AND a.is_submit_meeting = 1
	AND s.do_fail_type = 0
	AND s.user_id = ?`
	err = o.Raw(sqlCount, uid).QueryRow(&count)
	return
}

func GetUserMeetingMobile(activityId int) (items []*CygxActivitySignup, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT *
FROM
	cygx_activity_signup AS s 
WHERE
	s.is_meeting = 1 
	AND s.activity_id = ?`
	_, err = o.Raw(sql, activityId).QueryRows(&items)
	return
}

// 修改外呼电话以及区号
type OutboundMobileEditResp struct {
	Id             int    `description:"报名ID"`
	OutboundMobile string `description:"外呼手机号"`
	CountryCode    string `description:"手机国家区号"`
}

func OutboundMobileEdit(id int, outboundMobile, countryCode string) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_activity_signup SET outbound_mobile = ?,country_code=?  WHERE id=? `
	_, err = o.Raw(sql, outboundMobile, countryCode, id).Exec()
	return
}

//end

func AddCygxActivitySignupUser(items []*CygxActivitySignup) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	for _, item := range items {
		var count int
		sql := `SELECT COUNT(1) AS count FROM cygx_my_schedule WHERE user_id=? AND activity_id=? `
		err = to.Raw(sql, item.UserId, item.ActivityId).QueryRow(&count)
		if err != nil {
			return
		}
		if count == 0 {
			itemMy := new(CygxMySchedule)
			itemMy.UserId = item.UserId
			itemMy.ActivityId = item.ActivityId
			itemMy.CreateTime = time.Now()
			itemMy.Mobile = item.Mobile
			itemMy.Email = item.Email
			itemMy.CompanyId = item.CompanyId
			itemMy.CompanyName = item.CompanyName
			_, err = to.Insert(itemMy)
			if err != nil {
				return
			}
		}
		sql = `SELECT COUNT(1) AS count FROM cygx_activity_signup 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_signup SET  is_cancel=0, do_fail_type = 0 ,create_time = NOW()  WHERE user_id=? AND activity_id=? `
			_, err = to.Raw(sql, item.UserId, item.ActivityId).Exec()
		}
	}
	return
}

// 通过ID获取报名详情
func GetActivitySignupInfoById(id int) (item *CygxActivitySignup, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_signup  WHERE id=?`
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

type RequestCommonPolicyConfigrep struct {
	Type string `description:"报名方式 ，1 预约外呼 ，2 自主拨入"`
	Uid  int    `description:"用户ID"`
}

type RequestCommonPolicyConfig struct {
	CommonPolicyconfig  []interface{}                  `json:"common_policy_config"`
	CommonPolicyconfigs []RequestCommonPolicyConfigrep `json:"common_policy_configs"`
}

// 取消报名
func CancelActivitySignup(item *CygxActivitySignup) (lastId int64, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	//判断是否删除我的日程
	var count int
	sql := `SELECT COUNT(1) AS count FROM cygx_activity_meeting_reminder WHERE is_cancel = 0  AND  user_id=? AND activity_id=? `
	err = to.Raw(sql, item.UserId, item.ActivityId).QueryRow(&count)
	if err != nil {
		return
	}
	if count == 0 {
		sql = `DELETE  FROM cygx_my_schedule   WHERE user_id=?  AND activity_id=? `
		_, err = to.Raw(sql, item.UserId, item.ActivityId).Exec()
		if err != nil {
			return
		}
	}
	sql = `DELETE  FROM cygx_activity_signup   WHERE user_id=?  AND activity_id=? `
	_, err = to.Raw(sql, item.UserId, item.ActivityId).Exec()
	if err != nil {
		return
	}
	return
}

func GetCompanyPermission(companyId int) (permission string, err error) {
	sql := ` SELECT GROUP_CONCAT(DISTINCT b.remark  ORDER BY b.sort ASC SEPARATOR ',') AS permission
			FROM company_report_permission AS a
			INNER JOIN chart_permission AS b ON a.chart_permission_id=b.chart_permission_id
			INNER JOIN company_product AS c ON a.company_id=c.company_id AND a.product_id=c.product_id
			WHERE  a.company_id=?
			AND c.is_suspend=0
            AND b.cygx_auth=1 
			AND c.status IN('正式','试用','永续')
			AND a.status IN('正式','试用','永续') `
	o := orm.NewOrm()
	err = o.Raw(sql, companyId).QueryRow(&permission)
	return
}

// 获取可查看升级权限的正式权限
func GetCompanyPermissionByUserZhengShiTrip(companyId int) (permission string, err error) {
	sql := ` SELECT GROUP_CONCAT(DISTINCT b.chart_permission_name  ORDER BY b.sort ASC  SEPARATOR ',') AS permission
			FROM company_report_permission AS a
			INNER JOIN chart_permission AS b ON a.chart_permission_id=b.chart_permission_id
			INNER JOIN company_product AS c ON a.company_id=c.company_id AND a.product_id=c.product_id
			WHERE  a.company_id=?
			AND c.is_suspend=0
            AND b.cygx_auth=1
			AND ( a.is_upgrade = 1 AND c.STATUS = '正式' OR c.STATUS = '永续' ) `
	o := orm.NewOrm()
	err = o.Raw(sql, companyId).QueryRow(&permission)
	return
}

func GetCountCompanyDetailByIdGroup(companyId int) (count int, err error) {
	sql := ` SELECT COUNT(1) AS count
            FROM company AS a
			INNER JOIN company_product AS b ON a.company_id=b.company_id
			INNER JOIN company_report_permission AS p ON p.company_id = a.company_id
			INNER JOIN chart_permission AS cp ON cp.chart_permission_id = p.chart_permission_id
			LEFT JOIN admin AS c ON b.seller_id=c.admin_id
			WHERE a.company_id=? AND b.product_id = 2    OR (a.company_id = ? AND  cp.permission_name = '策略' )   `
	o := orm.NewOrm()
	err = o.Raw(sql, companyId, companyId).QueryRow(&count)
	return
}

type CompanyDetail struct {
	CompanyId   int    `orm:"column(company_id);pk"`
	CompanyName string `description:"客户名称"`
	Status      string `description:"客户状态"`
	SellerId    int    `description:"销售id"`
	SellerName  string `description:"销售名称"`
	Mobile      string `description:"销售手机号"`
	ProductId   int    `description:"1,FICC,2权益"`
}

func GetCompanyDetailByIdGroup(companyId int) (item *CompanyDetail, err error) {
	sql := ` SELECT a.company_id,a.company_name,b.status,b.seller_id,b.seller_name,c.mobile
            FROM company AS a
			INNER JOIN company_product AS b ON a.company_id=b.company_id
			INNER JOIN company_report_permission AS p ON p.company_id = a.company_id
			INNER JOIN chart_permission AS cp ON cp.chart_permission_id = p.chart_permission_id
			LEFT JOIN admin AS c ON b.seller_id=c.admin_id
			WHERE a.company_id=? AND b.product_id = 2
			OR (a.company_id = ? AND  cp.permission_name = '策略' )
			ORDER BY b.product_id DESC  LIMIT 0,1 `
	o := orm.NewOrm()
	err = o.Raw(sql, companyId, companyId).QueryRow(&item)
	return
}

func GetCompanyPermissionByUser(companyId int) (permission string, err error) {
	sql := ` SELECT GROUP_CONCAT(DISTINCT b.remark  ORDER BY b.sort ASC  SEPARATOR ',') AS permission
			FROM company_report_permission AS a
			INNER JOIN chart_permission AS b ON a.chart_permission_id=b.chart_permission_id
			INNER JOIN company_product AS c ON a.company_id=c.company_id AND a.product_id=c.product_id
			WHERE  a.company_id=?
			AND c.is_suspend=0
            AND b.cygx_auth=1`
	o := orm.NewOrm()
	err = o.Raw(sql, companyId).QueryRow(&permission)
	return
}

// 获取正式权限
func GetCompanyPermissionByUserZhengShi(companyId int) (permission string, err error) {
	sql := ` SELECT GROUP_CONCAT(DISTINCT b.remark  ORDER BY b.sort ASC  SEPARATOR ',') AS permission
			FROM company_report_permission AS a
			INNER JOIN chart_permission AS b ON a.chart_permission_id=b.chart_permission_id
			INNER JOIN company_product AS c ON a.company_id=c.company_id AND a.product_id=c.product_id
			WHERE  a.company_id=?
			AND c.is_suspend=0
            AND b.cygx_auth=1
			AND c.status IN('正式')
			AND a.status IN('正式') `
	o := orm.NewOrm()
	err = o.Raw(sql, companyId).QueryRow(&permission)
	return
}

// 活动模板消息推送，权限处理start
// GetCompanyDetailByIdGroupList 根据公司ID获取公司对应状态
func GetCompanyDetailByIdGroupList(companyIds []int) (items []*CompanyDetail, err error) {
	lenCompanyId := len(companyIds)
	if lenCompanyId == 0 {
		return
	}
	sql := ` SELECT a.company_id,a.company_name,b.status
            FROM company AS a
			INNER JOIN company_product AS b ON a.company_id=b.company_id
			WHERE a.company_id IN (` + utils.GetOrmInReplace(lenCompanyId) + `)  AND b.product_id = 2
			GROUP BY a.company_id  `
	o := orm.NewOrm()
	_, err = o.Raw(sql, companyIds).QueryRows(&items)
	return
}

type CompanyPermission struct {
	CompanyId      int    `description:"公司ID"`
	PermissionName string `description:"权限名称"`
}

// 公司权限结构体
type CompanyPermissionPower struct {
	CompanyId              int    `description:"公司ID"`
	UserType               int    `description:"用户类型   //1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //3、分行业套餐客户（开通对应行业的正式客户） //4、仅开通专家套餐的正式客户 //5、开通对应行业套餐或专家套餐的试用客户"`
	Status                 string `description:"客户状态"`
	PermissionName         string `description:"权限名称"`
	PermissionNameZhengShi string `description:"权限名称（正式）"`
	HavePower              bool   `description:"是否有权限"`
}

// GetCompanyPermissionByCompanyIds 根据公司ID获取公司对应的权限
func GetCompanyPermissionByCompanyIds(companyIds []int) (items []*CompanyPermission, err error) {
	lenCompanyId := len(companyIds)
	if lenCompanyId == 0 {
		return
	}
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT b.remark ORDER BY b.sort ASC SEPARATOR ',' ) AS permission_name,
			a.company_id 
		FROM
			company_report_permission AS a
			INNER JOIN chart_permission AS b ON a.chart_permission_id = b.chart_permission_id
			INNER JOIN company_product AS c ON a.company_id = c.company_id 
			AND a.product_id = c.product_id 
		WHERE
			a.company_id IN  (` + utils.GetOrmInReplace(lenCompanyId) + `)
			AND c.is_suspend = 0 
			AND b.cygx_auth = 1
		GROUP BY
			a.company_id `
	o := orm.NewOrm()
	_, err = o.Raw(sql, companyIds).QueryRows(&items)
	return
}

// GetCompanyPermissionZhenShiByCompanyIds 根据公司ID获取正式公司对应的权限
func GetCompanyPermissionZhenShiByCompanyIds(companyIds []int) (items []*CompanyPermission, err error) {
	lenCompanyId := len(companyIds)
	if lenCompanyId == 0 {
		return
	}
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT b.remark ORDER BY b.sort ASC SEPARATOR ',' ) AS permission_name,
			a.company_id 
		FROM
			company_report_permission AS a
			INNER JOIN chart_permission AS b ON a.chart_permission_id = b.chart_permission_id
			INNER JOIN company_product AS c ON a.company_id = c.company_id 
			AND a.product_id = c.product_id 
		WHERE
			a.company_id IN  (` + utils.GetOrmInReplace(lenCompanyId) + `)
			AND c.is_suspend = 0 
			AND b.cygx_auth = 1 
			AND c.STATUS IN ( '正式' ) 
			AND a.STATUS IN ( '正式' ) 
		GROUP BY
			a.company_id `
	o := orm.NewOrm()
	_, err = o.Raw(sql, companyIds).QueryRows(&items)
	return
}

type YidongActivitySignup struct {
	YidongActivityId string `description:"易董的活动ID"`
	Mobile           string `description:"手机号"`
	RealName         string `description:"用户实际名称"`
	CompanyName      string `description:"公司名称"`
	CountryCode      string `description:"手机国家区号"`
	ActivityJoinType string `description:"活动入会类型01报名审核后可入会 02预约即可入会 03仅定向邀请人员可入会"`
}

// GetCompanyByUserSignUp 获取客户ID列表
func GetCompanyByUserSignUp(condition string, pars []interface{}) (items []*company.CompanyNameAndId, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
	s.company_id
FROM
	cygx_activity_signup AS s
	INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id
	INNER JOIN cygx_activity_type AS t ON t.activity_type_id = a.activity_type_id 
WHERE
	1 = 1 
	AND s.is_meeting = 1 
	AND t.activity_type = 1 `
	if condition != `` {
		sql += condition
	}
	sql += ` GROUP BY s.company_id `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

type UserSignUpLossResp struct {
	Mobile       string `description:"手机号"`
	RealName     string `description:"姓名"`
	TotalMeeting int    `description:"参会次数"`
}

type UserSignUpLossListResp struct {
	CompanyId   int    `description:"公司Id"`
	CompanyName string `description:"公司名称"`
	SellerName  string `description:"销售名称"`
	List        []*UserSignUpLossResp
}

// GetUserSignUpList 获取用户报名列表
func GetUserSignUpList(condition string, pars []interface{}) (items []*UserSignUpLossResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
	s.real_name,
	s.mobile 
FROM
	cygx_activity_signup_detail AS s
	INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id
	INNER JOIN cygx_activity_type AS t ON t.activity_type_id = a.activity_type_id
WHERE
	1 = 1 
	AND s.is_meeting = 1 
	AND t.activity_type = 1  `
	if condition != `` {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

type UserSignUpMeetLossListResp struct {
	Mobile   string              `description:"手机号"`
	RealName string              `description:"姓名"`
	List     []*AttendanceDetail `description:"预约客户"`
}

type ActivitySignupTempMsgReq struct {
	ActivityIds  string `description:"活动id，用,隔开"`
	SendGroup    string `description:"发送对象，1全部 2永续 3大套餐 4行业套餐 5其他行业正式 6试用 7已参与互动 用,隔开"`
	FirstText    string `description:"首段提示文字"`
	ActivityName string `description:"活动名称"`
	Content      string `description:"变更内容"`
}

type SendGroup struct {
	Id   int
	Name string
}

type SendGroupStr struct {
	Id   string
	Name string
}

type PermissionList struct {
	CompanyId  int
	Permission string
}

// 获取正式权限
func GetCompanyPermissionByUsersZhengShi(companyIds string) (items []*PermissionList, err error) {
	sql := ` SELECT a.company_id, b.remark  AS permission
			FROM company_report_permission AS a
			INNER JOIN chart_permission AS b ON a.chart_permission_id=b.chart_permission_id
			INNER JOIN company_product AS c ON a.company_id=c.company_id AND a.product_id=c.product_id
			WHERE  a.company_id IN (` + companyIds + `)
			AND c.is_suspend=0
            AND b.cygx_auth=1
			AND c.status IN('正式')
			AND a.status IN('正式') `
	o := orm.NewOrm()
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取某一活动某个机构已经报名的数量
func GetActivitySignupCompanyCount(activityId, companyId int) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sqlCount := `SELECT COUNT(1) AS count FROM cygx_activity_signup WHERE is_cancel=0 AND do_fail_type = 0 AND activity_id=? AND company_id=? `
	err = o.Raw(sqlCount, activityId, companyId).QueryRow(&count)
	return
}

func GetCompanyPermissionByUserTrip(companyId int) (permission string, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT b.remark ORDER BY b.sort ASC SEPARATOR ',' ) AS permission 
		FROM
			company_report_permission AS a
			INNER JOIN chart_permission AS b ON a.chart_permission_id = b.chart_permission_id
			INNER JOIN company_product AS c ON a.company_id = c.company_id 
			AND a.product_id = c.product_id 
		WHERE
			a.company_id = ? 
			AND c.is_suspend = 0 
			AND b.cygx_auth = 1 
			AND a.is_upgrade = 1 
			AND c.STATUS IN ( '正式' ) 
			OR ( a.company_id = ? AND c.is_suspend = 0 AND b.cygx_auth = 1 AND c.STATUS IN ( '永续' ) ) 
			OR ( a.company_id = ? AND c.is_suspend = 0 AND b.cygx_auth = 1 AND b.chart_permission_name = '策略' AND c.STATUS IN ( '正式' ) )`
	err = o.Raw(sql, companyId, companyId, companyId).QueryRow(&permission)
	return
}

// GetCygxCygxActivitySignupList 获取报名列表信息
func GetActivitySignupList(condition string, pars []interface{}) (items []*CygxActivitySignup, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			*
		FROM
			cygx_activity_signup AS v
		WHERE
			1 = 1 	` + condition
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// GetCygxCygxActivitySignupList 获取报名列表信息
func GetActivitySignupInnerActivityList(condition string, pars []interface{}) (items []*CygxActivitySignup, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			*
		FROM
			cygx_activity_signup AS v 
			INNER JOIN cygx_activity as a ON v.activity_id = a.activity_id
		WHERE
			1 = 1 	` + condition
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}
