package models

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

// 活动详情
type CygxActivity struct {
	ActivityId                int       `orm:"column(activity_id);pk";description:"活动ID 等于0新增活动，大于0修改活动"`
	ActivityTypeId            int       `description:"活动类型id"`
	ActivityTypeName          string    `description:"活动类型名称"`
	ChartPermissionId         int       `description:"行业id"`
	ChartPermissionName       string    `description:"行业名称"`
	ChartPermissionNames      string    `description:"行业名称辅助字段，区分研选子分类"`
	IsShowHz                  int       `description:"是否同时在弘则展示  1是，0否"`
	ChartPermissionIdDeputy   int       `description:"行业id"`
	ChartPermissionNameDeputy string    `description:"副行业名称"`
	Body                      string    `description:"内容"`
	CreateTime                time.Time `description:"创建时间"`
	IsLimitPeople             int       `description:"是否限制人数 1是，0否"`
	LimitPeopleNum            int       `description:"限制的人数数量"`
	CustomerTypeIds           string    `description:"活动可见的客户类型，多个ID用 , 隔开"`
	PublishStatus             int       `description:"发布状态 1已发布，0未发布"`
	LastUpdatedTime           time.Time `description:"更新时间"`
	ActivityTime              string    `description:"活动时间"`
	ActivityTimeText          string    `description:"活动时间带文字"`
	DistinguishedGuest        string    `description:"嘉宾"`
	Host                      string    `description:"主持人"`
	MainlandTell              string    `description:"大陆拨入号"`
	HongKongTell              string    `description:"香港拨入号"`
	TaiwanTell                string    `description:"台湾拨入号"`
	AmericaTell               string    `description:"美国拨入号"`
	ParticipationCode         string    `description:"参会密码"`
	Theme                     string    `description:"主题"`
	Expert                    string    `description:"专家"`
	ActivityName              string    `description:"活动名称"`
	ActivityNameTask          string    `description:"活动名称定时任务同步的时候使用"`
	OnlineParticipation       string    `description:"网络参会"`
	ReportLink                string    `description:"报告链接"`
	City                      string    `description:"城市"`
	Address                   string    `description:"活动地址"`
	Highlights                string    `description:"活动亮点"`
	Remarks                   string    `description:"备注"`
	Speaker                   string    `description:"主讲人"`
	ArticleId                 int       `description:"关联报告id"`
	Label                     string    `description:"标签"`
	LinkParticipants          string    `description:"链接参会"`
	AppAttendance             string    `description:"App参会"`
	ConferencePassword        string    `description:"会议密码"`
	TemporaryLabel            string    `description:"临时标签"`
	IsMakerShow               int       `description:"是否仅决策人可见 0，否 、1，是"`
	VisibleRange              int       `description:"可见范围 1，仅本组可见 、2，全部客户可见"`
	Scale                     string    `description:"管理规模，空不填，1：:50亿以下，2：50~100亿，3：100亿以上。多个用, 隔开"`
	IsShowSubjectName         int       `description:"小程序内是否展示标的名称 1是 ，0 否 默认0 "`
	IsHideAppointment         int       `description:"是否隐藏预约纪要按钮 1是 ，0 否 默认0 "`
	AdminId                   int       `description:"销售/管理员ID"`
	AdminName                 string    `description:"销售/管理员姓名"`
	IsCanAppointmentMinutes   int       `description:"是否可预约纪要 1是 ，0 否 默认0 "`
	YidongActivityId          string    `description:"易董活动ID"`
	YidongActivityUrl         string    `description:"易董活动跳转地址"`
	YidongActivityEndTime     string    `description:"易董活动截止时间"`
	ActivityJoinType          string    `description:"活动入会类型01报名审核后可入会 02预约即可入会 03仅定向邀请人员可入会"`
	YidongSignUpEnd           string    `description:"易董活动截止时间"` // 报名结束时间，适应于报名审核后可入会，为空表示不限制报名时间
	YidongSignUpStart         string    `description:"易董活动截止时间"` // 报名开始时间，适应于报名审核后可入会，为空表示不限制报名时间
	IsExternalLabel           int       `description:"是否为外部资源 1是，0否"`
	YidongActivityIdByCygx    string    `description:"通过查研观向建会易董返回的活动ID"`
	JmcjRoadshowTitle         string    `description:"进门财经的活动标题"`
	JmcjActivityId            string    `description:"进门财经的活动ID"`
}

type ActivityCheck struct {
	CheckPermission   bool   `description:"权限是否通过校验"`
	HasPermission     int    `description:"操作方式，1:有该行业权限,正常展示，2：无该行业权限，3：潜在客户，未提交过申请，4：潜在客户,已提交过申请"`
	PopupMsg          string `description:"权限弹窗信息"`
	CancelPopupMsg    string `description:"取消报名时间弹窗信息"`
	SellerMobile      string `description:"销售电话"`
	SellerName        string `description:"销售姓名"`
	Mobile            string `description:"手机号"`
	IsResearch        bool   `description:"是否属于研选"`
	IsResearchSpecial bool   `description:"是否属于特殊的研选"`
	CheckTime         bool   `description:"时间是否通过校验"`
	CheckEmail        bool   `description:"邮箱是否通过校验"`
	CheckPoints       bool   `description:"扣点是否通过校验"`
	CompanyPoints     string `description:"公司剩余点数"`
	ActivityPoints    string `description:"本场活动要扣除的点数"`
}

type Activity struct {
	ActivityTypeId   int    `description:"活动类型id"`
	ActivityTypeName string `description:"活动名称"`
	TemplateP        string `description:"活动模板，带P标签"`
	Template         string `description:"活动模板"`
	ShowType         string `description:"人数限制类型，1不展示限制，2可选限制，3强制限制"`
}
type ActivityIdRep struct {
	ActivityId  int `description:"活动id"`
	PlaySeconds int `description:"播放时长"`
}

type ActivitySingnupRep struct {
	ActivityId int `description:"活动id"`
	SignupType int `description:"报名方式，1预约外呼，2自主拨入，3我要报名"`
}

type ActivityCcustomerType struct {
	CustomerTypeId  int    `description:"活动类型id"`
	CustomerName    string `description:"活动名称"`
	PermissionValue string `description:"用户权限对应的值"`
}

type ActivityCcustomerTypeList struct {
	List []*ActivityCcustomerType
}

// 列表
func GetActivityCcustomerTypeList() (items []*ActivityCcustomerType, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_customer_type ORDER BY sort DESC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 活动添加、修改入参
type ActivityRep struct {
	ActivityTypeId    int    `description:"活动类型id"`
	ChartPermissionId int    `description:"行业id"`
	Body              string `description:"内容"`
	LimitPeopleNum    int    `description:"限制的人数数量"`
	CustomerTypeIds   string `description:"活动可见的客户类型，多个ID用 , 隔开"`
	ActivityId        int    `description:"活动ID 等于0新增活动，大于0修改活动"`
	DoType            int    `description:"操作类型 0，保存 、1，发布"`
}

type ActivityArticleResp struct {
	ReportLink string `description:"报告链接"`
	ArticleId  int    `description:"报告id（报告链接跳转使用）"`
	Title      string `description:"报告id（报告链接跳转使用）"`
}

// 活动详情
type ActivityDetail struct {
	ActivityId                int                        `orm:"column(activity_id);pk";description:"活动ID "`
	ActivityTypeId            int                        `description:"活动类型id"`
	PublishStatus             int                        `description:"发布状态，0未发布，1已发布"`
	ActivityTypeName          string                     `description:"活动类型名称"`
	ChartPermissionId         int                        `description:"行业id"`
	ChartPermissionName       string                     `description:"行业名称"`
	ChartPermissionNames      string                     `description:"行业名称辅助字段，区分研选子分类"`
	Body                      string                     `description:"内容"`
	CreateTime                string                     `description:"创建时间"`
	IsLimitPeople             int                        `description:"是否限制人数 1是，0否"`
	LimitPeopleNum            int                        `description:"限制的人数数量"`
	LastUpdatedTime           string                     `description:"更新时间"`
	ActivityTime              string                     `description:"活动时间"`
	ActivityTimeText          string                     `description:"活动时间带文字"`
	DistinguishedGuest        string                     `description:"嘉宾"`
	Host                      string                     `description:"主持人"`
	Speaker                   string                     `description:"主讲人"`
	MainlandTell              string                     `description:"大陆拨入号"`
	HongKongTell              string                     `description:"香港拨入号"`
	TaiwanTell                string                     `description:"台湾拨入号"`
	AmericaTell               string                     `description:"美国拨入号"`
	ParticipationCode         string                     `description:"参会密码"`
	Theme                     string                     `description:"主题"`
	ThemeText                 string                     `description:"主题纯文本"`
	Expert                    string                     `description:"专家"`
	ExpertText                string                     `description:"专家纯文本"`
	ActivityName              string                     `description:"活动名称"`
	OnlineParticipation       string                     `description:"网络参会"`
	ReportLink                string                     `description:"报告链接"`
	City                      string                     `description:"城市"`
	Address                   string                     `description:"活动地址"`
	Highlights                string                     `description:"活动亮点"`
	HighlightsText            string                     `description:"活动亮点纯文本"`
	Remarks                   string                     `description:"备注"`
	ShowType                  string                     `description:"人数限制类型，1不展示限制，2可选限制，3强制限制"`
	IsSignup                  int                        `description:"是否已报名 1是 ，0 否"`
	IsAppointment             int                        `description:"是否已预约纪要 1是 ，0 否"`
	SignupNum                 int                        `description:"已报名人数"`
	SignupType                int                        `description:"报名方式，1预约外呼，2自主拨入，3我要报名"`
	ActiveState               string                     `description:"活动进行状态 未开始：1、进行中2、已结束3"`
	IsCancelMeetingReminder   int                        `description:"是否取消会议提醒 1展示取消会议提醒 ，0展示会议提醒"`
	ArticleId                 int                        `description:"报告id（报告链接跳转使用）"`
	CustomerTypeIds           string                     `description:"活动可见的客户类型，多个ID用 , 隔开"`
	IsShowSustainable         bool                       `description:"是否展示限免标签"`
	Description               string                     `description:"研选内容说明"`
	IsResearch                bool                       `description:"是否属于研选"`
	IsResearchSpecial         bool                       `description:"是否属于特殊的研选"`
	LinkParticipants          string                     `description:"链接参会"`
	AppAttendance             string                     `description:"App参会"`
	ConferencePassword        string                     `description:"会议密码"`
	Scale                     string                     `description:"管理规模，空不填，1：:50亿以下，2：50~100亿，3：100亿以上。多个用, 隔开"`
	IsShowAppointment         bool                       `description:"是否展示预约纪要"`
	IsHideAppointment         int                        `description:"是否隐藏预约纪要按钮  1是，0 否"`
	IsCClassMeeting           bool                       `description:"是否是c类电话会"`
	ArticleList               []*ActivityArticleResp     // 下面是列表添加的部分结构体
	IsBrackets                int                        `description:"是否有方括号 1是 ，0 否"`
	Label                     string                     `description:"主题标签"`
	ImgUrl                    string                     `description:"图片链接"`
	ImgUrlText                string                     `description:"图片链接文字"`
	ActivityType              int                        `description:"活动线上线下类型 1线上，0 线下"`
	JmcjRoadshowTitle         string                     `description:"进门财经手动匹配的活动名称"`
	Listndustrial             []*IndustrialManagementRep `description:"活动关联的产业信息"`
	IsShowOutboundCall        bool                       `description:"是否展示预约外呼"`
	IsShowMeetingReminder     bool                       `description:"是否展示会议提醒"`
	IsShowHelpSsk             bool                       `description:"是否展示帮我带问"`
	IsShowSignup              bool                       `description:"是否展示我要报名"`
	IsShowDetails             bool                       `description:"是否展示查看详情按钮"`
	TemporaryLabel            string                     `description:"临时标签"`
	IsCanAppointmentMinutes   int                        `description:"是否可预约纪要 1是 ，0 否 默认0 "`
	YidongActivityId          string                     `description:"易董活动ID"`
	YidongActivityUrl         string                     `description:"易董活动跳转地址"`
	AudioLink                 bool                       `description:"是否展示回放按钮"`
	VoiceList                 *CygxActivityVoiceReq      `description:"音频数据"`
	AdminId                   int                        `description:"管理员、销售ID "`
	IsMakerShow               int                        `description:"是否仅决策人可见 0，否 、1，是"`
	VisibleRange              int                        `description:"可见范围 1，仅本组可见 、2，全部客户可见"`
	VideoDetail               *CygxActivityVideoListResp `description:"视频数据"`
	FileType                  int                        `description:"类型: 1-音频; 2-视频"`
	SourceType                int                        `description:"活动来源。 1：活动 、2：专项产业调研"`
	TripImgLink               string                     `description:"专项产业调研行程链接"`
	ActivityTimeEnd           string                     `description:"专项产业调研活动预期结束时间"`
	IsCollect                 bool                       `description:"是否收藏"`
	IsShowFollowButton        bool                       `description:"是否展示关注取关按钮"`
	IsFollowButton            bool                       `description:"是否关注"`
	IsYidongConduct           bool                       `description:"是否属于易董办会 1：是 、0：否"`
	IsCanOutboundCall         int                        `description:"是否提供外呼 1：是 、0：否"`
	TencentConferenceNumber   string                     `description:"腾讯会议号"`
	YidongActivityIdByCygx    string                     `description:"通过查研观向建会易董返回的活动ID"`
	IsShowSigninButton        bool                       `description:"是否展示签到码按钮"`
	IsShowSignUpDetail        bool                       `description:"是否展示报名详情按钮"`
	SigninImg                 string                     `description:"签到码图片"`
	IsNeedEmail               int                        `description:"是否需要提供邮箱 1是，0否"`
	SiginupDeadline           string                     `description:"报名截止时间"`
	IsExternalLabel           bool                       `description:"是否为外部资源"`
	IsResearchPoints          bool                       `description:"是否为研选扣点"`
	CancelDeadline            string                     `description:"取消报名截止时间"`
	ImgUrlBgYx                string                     `description:"研选背景图片"`
	ChartPermissionNameDeputy string                     `description:"副行业名称"`
	TopTime                   int                        `description:"置顶时间"`
	IsZoom                    int                        `description:"是否是Zoom模版  1是，0否"`
	MeetingId                 string                     `description:"会议ID"`
}
type ListArticleActivity struct {
	Title   string `description:"文章标题"`
	ArtleId int    `description:"产业id"`
}

type ActivityImgUrlMapResp struct {
	ImgUrl     string `description:"图片链接"`
	ImgUrlText string `description:"图片链接文字"`
}

type CygxActivityResp struct {
	HaqveJurisdiction bool   `description:"是否有权限"`
	OperationMode     string `description:"操作方式 Apply:立即申请、Call:拨号 为空则为有权限"`
	HasPermission     int    `description:"操作方式，1:有该行业权限,正常展示，2：无该行业权限，3：潜在客户，未提交过申请，4：潜在客户,已提交过申请，5：有IFCC、无权益"`
	PopupMsg          string `description:"权限弹窗信息"`
	MsgType           string `description:"Type ： 类型 , Industry ： 行业"`
	SellerMobile      string `description:"销售电话"`
	SellerName        string `description:"销售姓名"`
	IsResearch        bool   `description:"是否属于研选"`
	IsResearchSpecial bool   `description:"是否属于特殊的研选"`
	Detail            *ActivityDetail
}

// 通过纪要ID获取活动详情
func GetAddActivityInfoById(ActivityId int) (item *ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity  WHERE activity_id=? AND publish_status = 1 `
	err = o.Raw(sql, ActivityId).QueryRow(&item)
	return
}

// 通过纪要ID获取活动详情
func GetAddActivityInfoByActivityId(ActivityId int) (item *ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity  WHERE activity_id=?  `
	err = o.Raw(sql, ActivityId).QueryRow(&item)
	return
}

// 获取活动详情
func GetAddActivityDetailByActivityId(ActivityId int) (item *ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT a.*,t.activity_type FROM cygx_activity AS a 
			INNER JOIN cygx_activity_type  as t ON t.activity_type_id = a.activity_type_id  WHERE activity_id=?  `
	err = o.Raw(sql, ActivityId).QueryRow(&item)
	return
}

// 通过活动名称获取活动详情
func GetAddActivityInfoByTitle(title, startDate, endDate string) (item *ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity  WHERE  activity_time > '` + startDate + `' AND activity_time < '` + endDate + `' AND (activity_name_task LIKE '%` + title + `%' OR  jmcj_roadshow_title LIKE '%` + title + `%')   AND activity_id  NOT IN (1328)  LIMIT 1 `
	err = o.Raw(sql).QueryRow(&item)
	return
}

// 通过纪要ID获取活动详情
func GetAddActivityInfoByIdShow(uid, ActivityId int) (item *ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT a.*,t.activity_type,t.img_url_text,t.img_url_bg_yx,( SELECT COUNT( 1 ) FROM cygx_activity_signup AS s WHERE s.activity_id = a.activity_id AND s.user_id = ?   AND s.is_cancel = 0  AND s.do_fail_type = 0) AS is_signup,
			( SELECT COUNT( DISTINCT user_id ) FROM cygx_activity_signup AS s WHERE s.activity_id = a.activity_id  AND s.is_cancel = 0 AND s.do_fail_type = 0) AS signup_num,
			( SELECT COUNT( 1 ) FROM cygx_activity_meeting_reminder AS m WHERE m.activity_id = a.activity_id AND m.user_id = ?  AND m.is_cancel = 0 ) AS is_cancel_meeting_reminder,
			( SELECT COUNT( 1 ) FROM cygx_activity_appointment AS ap WHERE ap.activity_id = a.activity_id AND ap.user_id = ? ) AS is_appointment
			FROM cygx_activity AS a 
			INNER JOIN cygx_activity_type  as t ON t.activity_type_id = a.activity_type_id
			WHERE a.activity_id=? AND a.publish_status = 1 `
	err = o.Raw(sql, uid, uid, uid, ActivityId).QueryRow(&item)
	return
}

// 活动列表
type CygxActivityList struct {
	ActivityId              int    `orm:"column(activity_id);pk";description:"活动ID 等于0新增活动，大于0修改活动"`
	ActivityTypeId          int    `description:"活动类型id"`
	ActivityName            string `description:"活动名称"`
	ActivityTypeName        string `description:"活动类型名称"`
	Speaker                 string `description:"主讲人"`
	SignupType              int    `description:"报名方式，1预约外呼，2我要报名"`
	ChartPermissionId       int    `description:"行业id"`
	ChartPermissionName     string `description:"行业名称"`
	IsLimitPeople           int    `description:"是否限制人数 1是，0否"`
	LimitPeopleNum          int    `description:"限制的人数数量"`
	ActivityTime            string `description:"活动时间"`
	ActivityTimeText        string `description:"活动时间带文字"`
	City                    string `description:"城市"`
	Address                 string `description:"活动地址"`
	DistinguishedGuest      string `description:"嘉宾"`
	Expert                  string `description:"专家"`
	IsSignup                int    `description:"是否已报名 1是 ，0 否"`
	IsAppointment           int    `description:"是否已预约纪要 1是 ，0 否"`
	IsShowAppointment       bool   `description:"是否展示预约纪要"`
	SignupNum               int    `description:"已报名人数"`
	ActiveState             string `description:"活动进行状态 未开始：1、进行中2、已结束3"`
	IsCancelMeetingReminder int    `description:"是否取消会议提醒 1展示取消会议提醒 ，0展示会议提醒"`
	IsBrackets              int    `description:"是否有方括号 1是 ，0 否"`
	Label                   string `description:"主题标签"`
	IsShowSustainable       bool   `description:"是否展示限免标签"`
	ImgUrl                  string `description:"图片链接"`
	ImgUrlText              string `description:"图片链接文字"`
	ActivityType            int    `description:"活动线上线下类型 1线上，0 线下"`
	IsHideAppointment       int    `description:"是否隐藏预约纪要按钮  1是，0 否"`
	JmcjRoadshowTitle       string `description:"进门财经手动匹配的活动名称"`
	IsCClassMeeting         bool   `description:"是否是c类电话会"`
}

type GetCygxActivityListRep struct {
	Paging                 *paging.PagingItem `description:"分页数据"`
	List                   []*ActivityDetail
	Label                  string `description:"主题"`
	ImgUrl                 string `description:"图片路径"`
	IsResearch             bool   `description:"是否属于研选"`
	IsJump                 bool   `description:"是否跳转"`
	IndustrialManagementId int    `description:"产业ID"`
	IndustryNewLabel       bool   `description:"产业是否新标签"`
	IsShowResearchPoints   bool   `description:"是否展示研选扣点搜索"`
}

// 列表
func GetActivityListAll(condition string, pars []interface{}, uid, startSize, pageSize, playBack int) (items []*ActivityDetail, err error) {
	var sqlJiontable string
	if playBack == 1 {
		//sqlJiontable = ` INNER JOIN cygx_activity_voice AS ac ON ac.activity_id = art.activity_id `
	}
	o := orm.NewOrm()
	sql := `SELECT art.* ,t.activity_type,t.img_url_text,
		( SELECT COUNT( 1 ) FROM cygx_activity_signup AS s WHERE s.activity_id = art.activity_id AND s.user_id = ?   AND s.is_cancel = 0  AND s.do_fail_type = 0) AS is_signup,
		( SELECT COUNT( DISTINCT user_id ) FROM cygx_activity_signup AS s WHERE s.activity_id = art.activity_id   AND s.is_cancel = 0  AND s.do_fail_type = 0) AS signup_num,
		( SELECT COUNT( 1 ) FROM cygx_activity_meeting_reminder AS m WHERE m.activity_id = art.activity_id AND m.user_id = ?  AND m.is_cancel = 0  ) AS is_cancel_meeting_reminder,
		( SELECT COUNT( 1 ) FROM cygx_activity_appointment AS ap WHERE ap.activity_id = art.activity_id AND ap.user_id = ? ) AS is_appointment
		FROM cygx_activity as art
		INNER JOIN cygx_activity_type  as t ON t.activity_type_id = art.activity_type_id` + sqlJiontable + ` WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, uid, uid, uid, startSize, pageSize).QueryRows(&items)
	return
}

// 列表
func GetActivityListByDateTime(startDate, endDate, activityIds, activityIdsLongTime string) (items []*CygxActivityList, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity WHERE activity_time > '` + startDate + `' AND activity_time < '` + endDate + `' `
	activityIds = strings.TrimRight(activityIds, ",")
	if activityIds != "" {
		sql += ` AND activity_id  NOT IN (` + activityIds + `,1328 )  `
	}
	sql += `  OR activity_id IN (` + activityIdsLongTime + `)`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取我的日程数量
func GetSpecialScheduleCount(uid int) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := `
SELECT COUNT( 1 ) AS count FROM
			cygx_activity_special AS art
			INNER JOIN cygx_activity_special_trip AS my ON my.activity_id = art.activity_id 
		WHERE
			1 = 1 AND my.user_id = ? AND my.is_cancel = 0`
	err = o.Raw(sqlCount, uid).QueryRow(&count)
	return
}

// 获取数量
func GetActivityCount(condition string, playBack int, pars []interface{}, filter int) (count int, err error) {
	var sqlJiontable string
	if playBack == 1 {
		//sqlJiontable = ` INNER JOIN cygx_activity_voice AS ac ON ac.activity_id = art.activity_id `
	}

	if filter == 1 {
		sqlJiontable = ` INNER JOIN cygx_activity_video AS av ON av.activity_id = art.activity_id `
	} else if filter == 2 {
		sqlJiontable = ` INNER JOIN cygx_activity_voice AS ac ON ac.activity_id = art.activity_id `
	}
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_activity as art ` + sqlJiontable + ` WHERE 1= 1  `
	if condition != "" {
		sqlCount += condition
	}
	o := orm.NewOrm()
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

// 获取我的日程数量
func GetScheduleCount(condition string, uid int) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := `SELECT COUNT( 1 ) AS count 
				FROM cygx_my_schedule AS m
				INNER JOIN cygx_activity AS art ON art.activity_id = m.activity_id 
				WHERE
				user_id = ?`
	if condition != "" {
		sqlCount += condition
	}
	err = o.Raw(sqlCount, uid).QueryRow(&count)
	return
}

// 我的日程列表
func GetScheduleList(condition string, pars []interface{}, uid, startSize, pageSize int) (items []*ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT art.*,t.activity_type,t.img_url_text,
			( SELECT COUNT( 1 ) FROM cygx_activity_signup AS s WHERE s.activity_id = art.activity_id AND s.user_id = ? AND s.is_cancel = 0 AND s.do_fail_type = 0) AS is_signup,
            ( SELECT COUNT( DISTINCT user_id ) FROM cygx_activity_signup AS s WHERE s.activity_id = art.activity_id AND  s.is_cancel = 0  AND s.do_fail_type = 0) AS signup_num ,
			( SELECT COUNT( 1 ) FROM cygx_activity_appointment AS ap WHERE ap.activity_id = art.activity_id AND ap.user_id = ? ) AS is_appointment,
			( SELECT COUNT( 1 ) FROM cygx_activity_meeting_reminder AS m WHERE m.activity_id = art.activity_id AND m.is_cancel = 0 AND m.user_id = ? ) AS is_cancel_meeting_reminder
            FROM cygx_activity AS art
			INNER JOIN cygx_my_schedule as my ON my.activity_id = art.activity_id 
			INNER JOIN cygx_activity_type  as t ON t.activity_type_id = art.activity_type_id
            WHERE 1=1 AND my.user_id = ? `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY art.active_state ASC,art.activity_time ASC  LIMIT ?,?`
	_, err = o.Raw(sql, pars, uid, uid, uid, uid, startSize, pageSize).QueryRows(&items)
	return
}

// 我的日程列表 活动以及专项调研一起
func GetScheduleAndSpecilList(condition string, pars []interface{}, conditionSpecil string, parsSpecil []interface{}, startSize, pageSize int) (items []*ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			art.activity_id,
			art.activity_time_text,
			art.activity_name,
			art.chart_permission_id,
			art.active_state,
			t.activity_type,
			art.chart_permission_name,
			art.distinguished_guest,
			art.expert,
			art.speaker,
			"" AS trip_img_link,
			"" AS activity_time_end,
			art.yidong_activity_id,
			art.is_can_appointment_minutes,
			art.activity_type_id,
			art.limit_people_num,
			art.is_limit_people,
			1 AS source_type,
			art.activity_time, 
			art.city,
			art.is_external_label,
			art.siginup_deadline,
			art.is_research_points,
			art.is_zoom,
			art.cancel_deadline
		FROM
			cygx_activity AS art
			INNER JOIN cygx_my_schedule AS my ON my.activity_id = art.activity_id
			INNER JOIN cygx_activity_type AS t ON t.activity_type_id = art.activity_type_id
		WHERE
			1 = 1 `
	if condition != `` {
		sql += condition
	}
	sql += ` UNION ALL
		SELECT
			art.activity_id,
			art.activity_time_text_by_day AS activity_time_text,
			art.research_theme AS activity_name,
			art.chart_permission_id,
			"",
			art.special_type AS activity_type,
			art.chart_permission_name,
			"",
			"",
			"",
			art.trip_img_link_fix AS trip_img_link,
			art.activity_time_end,
			"",
			"",
			"",
			"",
			"",
			2 AS source_type,
			art.activity_time,
			"",
			"",
			"",
			"",
			"",
			""
		FROM
			cygx_activity_special AS art
			INNER JOIN cygx_activity_special_trip AS my ON my.activity_id = art.activity_id 
		WHERE
			1 = 1`
	if conditionSpecil != "" {
		sql += conditionSpecil
	}
	sql += ` ORDER BY activity_time DESC   LIMIT ?,?`
	_, err = o.Raw(sql, pars, parsSpecil, startSize, pageSize).QueryRows(&items)
	return
}

// 获取数量
func GetActivityCountById(activityId int) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := `SELECT COUNT(1) AS count  FROM cygx_activity WHERE activity_id = ?`
	err = o.Raw(sqlCount, activityId).QueryRow(&count)
	return
}

// 删除数据
func DeleteActivity(activityId int) (err error) {
	o := orm.NewOrm()
	sql := ` DELETE FROM cygx_activity WHERE activity_id = ?`
	_, err = o.Raw(sql, activityId).Exec()
	return
}

// 修改活动状态至进行中
func UpdateActivitySattusToHaveInHand() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("修改活动状态至进行中失败"+err.Error(), 2)
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "修改活动状态至进行中失败 ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	o := orm.NewOrm()
	resultTime_30 := time.Now().Add(-time.Minute * 60).Format("2006-01-02 15:04:05") // 线上活动也改成60分钟之后结束了 2023.5.8
	resultTime_60 := time.Now().Add(-time.Minute * 60).Format("2006-01-02 15:04:05")
	var sqlOr string
	var condition string
	condition += ` AND activity_time < NOW()`
	sqlOr = condition
	condition += ` AND (activity_type_id IN ( 1, 2, 3, 7 ) AND  activity_time > ` + "'" + resultTime_30 + "'" + ")"
	condition += ` OR(activity_type_id IN ( 4, 5, 6, 8 ) AND  activity_time > ` + "'" + resultTime_60 + "'" + sqlOr + ")"
	msql := " UPDATE cygx_activity SET active_state = 2, top_time = 0  WHERE 1 = 1 " + condition
	_, err = o.Raw(msql).Exec()
	return
}

// 修改活动状态至已结束
func UpdateActivitySattusToComplete() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("修改活动状态至已结束"+err.Error(), 2)
			go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "修改活动状态至已结束 ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	o := orm.NewOrm()
	resultTime_30 := time.Now().Add(-time.Minute * 60).Format("2006-01-02 15:04:05") // 线上活动也改成60分钟之后结束了 2023.5.8
	resultTime_60 := time.Now().Add(-time.Minute * 60).Format("2006-01-02 15:04:05")
	//var sqlOr string
	var condition string
	//condition += ` AND activity_time < NOW()`
	//sqlOr = condition
	condition += ` AND (activity_type_id IN ( 1, 2, 3, 7 ) AND  activity_time < ` + "'" + resultTime_30 + "'" + ")"
	condition += ` OR(activity_type_id IN ( 4, 5, 6 ,8 ) AND  activity_time < ` + "'" + resultTime_60 + "'" + ")"
	msql := " UPDATE cygx_activity SET active_state = 3 WHERE 1 = 1 " + condition
	_, err = o.Raw(msql).Exec()
	return
}

// 活动详情
type WxMsgCygxActivityList struct {
	Id                      int    `description:"报名ID"`
	UserId                  int    `description:"用户ID"`
	ActivityId              int    `description:"活动ID 等于0新增活动，大于0修改活动"`
	ActivityTypeId          int    `description:"活动类型id"`
	ActivityName            string `description:"活动名称"`
	ActivityTypeName        string `description:"活动类型名称"`
	Speaker                 string `description:"主讲人"`
	SignupType              int    `description:"报名方式，1预约外呼，2我要报名"`
	ChartPermissionId       int    `description:"行业id"`
	ChartPermissionName     string `description:"行业名称"`
	IsLimitPeople           int    `description:"是否限制人数 1是，0否"`
	LimitPeopleNum          int    `description:"限制的人数数量"`
	ActivityTime            string `description:"活动时间"`
	ActivityTimeText        string `description:"活动时间带文字"`
	City                    string `description:"城市"`
	Address                 string `description:"活动地址"`
	DistinguishedGuest      string `description:"嘉宾"`
	Expert                  string `description:"专家"`
	IsSignup                int    `description:"是否已报名 1是 ，0 否"`
	SignupNum               int    `description:"已报名人数"`
	ActiveState             string `description:"活动进行状态 未开始：1、进行中2、已结束3"`
	IsCancelMeetingReminder int    `description:"是否取消会议提醒 1展示取消会议提醒 ，0展示会议提醒"`
	IsBrackets              int    `description:"是否有方括号 1是 ，0 否"`
	OpenId                  string `description:"OenId"`
	FailType                int    `description:"失败原因，0，未失败，1总人数已满，2单机构超限制，3，爽约次数超限"`
}

// 列表 3o分钟
func GetActivitySendMsgListAll(endDate string) (items []*WxMsgCygxActivityList, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	s.id,
	s.user_id,
	s.fail_type,
	cr.open_id,
	a.*
FROM
	cygx_activity AS a
	INNER JOIN cygx_activity_signup AS s ON s.activity_id = a.activity_id
	INNER JOIN cygx_user_record AS cr ON cr.cygx_bind_account = s.mobile 
WHERE
	1 = 1 
	AND s.is_send_wx_msg = 0 
	AND s.do_fail_type = 0 
	AND a.publish_status = 1
	AND a.activity_time <= ? AND a.activity_time >= NOW() 
	AND s.is_cancel = 0
	AND( a.activity_type_id IN (4,5,6,8) OR (a.activity_type_id = 3 AND a.is_limit_people = 1 )) 	GROUP BY s.id`
	_, err = o.Raw(sql, endDate).QueryRows(&items)
	return
}

// 买方研选会前一小时需要推送的Openid
func GetActivitySendMsgListAllMfyx(endDate string) (items []*WxMsgCygxActivityList, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	s.id,
	s.user_id,
	s.fail_type,
	cr.open_id,
	a.activity_name,
	a.activity_id,
	a.activity_time
FROM
	cygx_activity AS a
	INNER JOIN cygx_activity_signup AS s ON s.activity_id = a.activity_id
	INNER JOIN cygx_mfyx_gzh_user_record AS cr ON cr.cygx_bind_account = s.mobile 
WHERE
	1 = 1 
	AND s.is_send_wx_msg = 0 
	AND s.do_fail_type = 0 
	AND a.publish_status = 1
  	AND a.chart_permission_id = 31 
	AND a.activity_time = ? AND a.activity_time >= NOW() 
	AND s.is_cancel = 0
	AND a.activity_type_id IN (5,8) 	GROUP BY s.id`
	_, err = o.Raw(sql, endDate).QueryRows(&items)
	return
}

// 列表 15分钟提醒
func GetActivitySendMsgListAllMeeting(endDate string) (items []*WxMsgCygxActivityList, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	m.id,
	cr.open_id,
	a.* 
FROM
	cygx_activity AS a
	INNER JOIN cygx_activity_meeting_reminder AS m ON m.activity_id = a.activity_id
	INNER JOIN user_record AS c ON c.bind_account = m.mobile 
	INNER JOIN cygx_user_record AS cr ON cr.union_id = c.union_id 
WHERE
	1 = 1 
	AND m.is_send_wx_msg = 0 
	AND a.publish_status = 1 
	AND a.activity_time <= ? AND a.activity_time >= NOW() 
	AND m.is_cancel = 0 
	AND c.create_platform = 4
	AND (
	a.activity_type_id IN ( 1, 2 ) 
	OR ( a.activity_type_id = 3 AND a.is_limit_people = 0 ))
	GROUP BY m.id`
	_, err = o.Raw(sql, endDate).QueryRows(&items)
	return
}

// 修改是否推送消息状态
func UPdateSendedMsgStatus(signupIds string) (err error) {
	sql := ` UPDATE cygx_activity_signup SET  is_send_wx_msg= 1  WHERE id IN(` + signupIds + `)`
	o := orm.NewOrm()
	_, err = o.Raw(sql).Exec()
	return
}

// 修改是否推送消息状态
func UPdateSendedYiDongSignUp(activityId int) (err error) {
	sql := ` UPDATE cygx_activity SET  is_yidong_sign_up= 1  WHERE activity_id = ? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, activityId).Exec()
	return
}

// 修改是否推送消息状态
func UPdateSendedMsgMeetingStatus(signupIds string) (err error) {
	sql := ` UPDATE cygx_activity_meeting_reminder SET  is_send_wx_msg= 1  WHERE id IN(` + signupIds + `)`
	o := orm.NewOrm()
	_, err = o.Raw(sql).Exec()
	return
}

// 获取满足推送的活动ID数量
func GetCountActivityIdToSendFile(endDate string) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	COUNT(1) count
FROM
	cygx_activity AS a
	INNER JOIN cygx_activity_signup AS s ON s.activity_id = a.activity_id 
WHERE
	1 = 1 
	AND s.signup_type = 1 
	AND s.fail_type = 0 
	AND a.is_send_file_toemail = 0 
	AND a.activity_time <= ? AND a.activity_time >= NOW() 	GROUP BY a.activity_id `
	err = o.Raw(sql, endDate).QueryRow(&count)
	return
}

// 获取满足推送的活动ID
func GetActivityIdToSendFile(endDate string) (items []*ActivityIdRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			* 
		FROM
			cygx_activity AS a
			INNER JOIN cygx_activity_signup AS s ON s.activity_id = a.activity_id 
			INNER JOIN cygx_activity_type AS t ON a.activity_type_id = t.activity_type_id
		WHERE
			1 = 1 
			AND s.signup_type = 1 
			AND a.yidong_activity_id = '' 
			AND t.activity_type = 1
			AND s.fail_type = 0 
			AND a.is_send_file_toemail = 0 
		 	AND a.publish_status = 1
			AND a.activity_time <= ? AND a.activity_time >= NOW() 	GROUP BY a.activity_id `
	_, err = o.Raw(sql, endDate).QueryRows(&items)
	return
}

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

type ActivityMsgExportRep struct {
	AskId       int    `description:"活动带问ID"`
	UserId      int    `description:"用户ID"`
	RealName    string `description:"姓名"`
	CompanyName string `description:"公司名称"`
	CompanyId   int    `description:"公司ID"`
	Content     string `description:"内容"`
	CreateTime  string `description:"提交时间"`
}

func GetSignupExport(activityId int) (item []*SignupExportRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			s.outbound_mobile,
			s.country_code,
			a.is_limit_people,
			s.real_name,
			s.seller_name,
			s.company_id,
			s.company_name 
		FROM
			cygx_activity_signup AS s
			JOIN cygx_activity AS a ON a.activity_id = s.activity_id 
			WHERE a.activity_id = ?  AND s.do_fail_type = 0 AND s.signup_type = 1  GROUP BY s.id `
	_, err = o.Raw(sql, activityId).QueryRows(&item)
	return
}

// 修改文件是否推送状态
func UPdateActivityIdToSendFile(activityId int) (err error) {
	sql := ` UPDATE cygx_activity SET  is_send_file_toemail= 1  WHERE activity_id = ?`
	o := orm.NewOrm()
	_, err = o.Raw(sql, activityId).Exec()
	return
}

// 活动详情
type CygxActivityLabelList struct {
	KeyWord           string `orm:"column(label)";description:"主题"`
	Timesort          string `description:"最大时间"`
	Mintimesort       string `description:"最小时间"`
	ImgUrlBg          string `description:"背景图片"`
	ActivityId        int    `description:"活动ID "`
	IsShowSubjectName int    `description:"小程序内是否展示标的名称 1是 ，0否 默认0 "`
	Resource          int    `description:"位置 ，1：活动 ，2：专项产业调研"`
	TemporaryLabel    string `description:"临时标签"`
	IsNew             bool   `description:"是否为新：活动存在关联的的产业所关联的报告均在3个月内/无报告则标记新"`
	YidongActivityId  string `description:"易董活动ID"`
	IsExternalLabel   bool   `description:"是否为外部资源"`
	IsResearchPoints  bool   `description:"是否为研选扣点"`
	TripStatus        int    `description:"行程进行状态 1：预报名，2：确定行程"`
	City              string `description:"城市"`
	Days              int    `description:"天数"`
	ActivityTypeId    int    `description:"活动类型id"`
	IsResearch        bool   `description:"是否属于研选"`
	ChartPermissionId int    `description:"行业id"`
}

// 主题列表
func GetActivityLabelListAll(condition, sortTime string, pars []interface{}, startSize, pageSize int) (items []*CygxActivityLabelList, err error) {
	o := orm.NewOrm()
	sql := `SELECT	activity_id,activity_type_id, label,temporary_label,is_show_subject_name, MAX( art.activity_time ) AS timesort, MIn( art.activity_time ) AS mintimesort , yidong_activity_id,city,is_external_label,is_research_points,chart_permission_id
		FROM cygx_activity as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY art.activity_id ORDER BY ` + sortTime + ` ,art.activity_id DESC  LIMIT ?,? `

	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 主题列表
func GetActivityLabelListCity() (items []*CygxActivity, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			activity_id,
			activity_type_id,
			activity_time,
			label,
			temporary_label,
			is_show_subject_name,
			yidong_activity_id,
			city 
		FROM
			cygx_activity AS art 
		WHERE
			1 = 1 
			AND art.active_state IN ( 1, 2 ) 
			AND city != '' 
		ORDER BY
			activity_time ASC  `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

type GetCygxActivityLabelListRep struct {
	Label  string `description:"主题"`
	ImgUrl string `description:"图片路径"`
	List   []*CygxActivityLabelList
}

// 获取研选系列专家电话会，会前1小时，满足推送的活动ID数量
func GetCountActivityResearchToSendFile(condition, endDate string) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	COUNT(1) count
FROM
	cygx_activity AS a
	INNER JOIN cygx_activity_help_ask AS k ON k.activity_id = a.activity_id 
WHERE
	1 = 1 ` + condition + `
	AND a.is_send_ask_msg = 0 
	AND a.activity_time <= ? 
	AND a.activity_time >= NOW()`
	err = o.Raw(sql, endDate).QueryRow(&count)
	return
}

// 获取研选系列专家电话会，会前1小时，满足推送的活动ID
func GetActivityResearchToSendFile(condition, endDate string) (items []*ActivityIdRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	* 
FROM
	cygx_activity AS a
	INNER JOIN cygx_activity_help_ask AS k ON k.activity_id = a.activity_id 
WHERE
	1 = 1 ` + condition + `
	AND a.is_send_ask_msg = 0 
	AND a.activity_time <= ? 
	AND a.activity_time >= NOW() 
GROUP BY
	a.activity_id `
	_, err = o.Raw(sql, endDate).QueryRows(&items)
	return
}

func GetActivityMsgExport(activityId int) (item []*ActivityMsgExportRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			k.*
			FROM
			cygx_activity_help_ask AS k
			WHERE
			k.activity_id = ? 
			GROUP BY
			k.ask_id`
	_, err = o.Raw(sql, activityId).QueryRows(&item)
	return
}

// 修改文件带问消息是否推送状态
func UPdateActivityMsgToSendFile(activityId int) (err error) {
	sql := ` UPDATE cygx_activity SET  is_send_ask_msg= 1  WHERE activity_id = ?`
	o := orm.NewOrm()
	_, err = o.Raw(sql, activityId).Exec()
	return
}

type AskEmailRep struct {
	Name                string `description:"姓名"`
	Email               string `description:"邮箱"`
	Mobile              string `description:"手机号"`
	ChartPermissionName string `description:"行业名称"`
}

func GetAskEmail() (item []*AskEmailRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity_ask_email`
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 主题列表
func GetActivityLabelSpecialListAll(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxActivityLabelList, err error) {
	o := orm.NewOrm()
	sql := `SELECT	label,activity_id,is_show_subject_name,days
		FROM cygx_activity_special as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += `  LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type GetCygxActivitySpecialDetailListResp struct {
	IsFollow        bool               `description:"是否关注新调研通知"`
	IsBindingMobile bool               `description:"是否绑定了手机号"`
	Paging          *paging.PagingItem `description:"分页数据"`
	List            []*CygxActivitySpecialDetail
}

type CygxActivitySpecialResp struct {
	HaqveJurisdiction bool   `description:"是否有权限"`
	OperationMode     string `description:"操作方式 Apply:立即申请、Call:拨号 为空则为有权限"`
	HasPermission     int    `description:"操作方式，1:有该行业权限,正常展示，2：无该行业权限，3：潜在客户，未提交过申请，4：潜在客户,已提交过申请，5：有IFCC、无权益"`
	PopupMsg          string `description:"权限弹窗信息"`
	MsgType           string `description:"Type ： 类型 , Industry ： 行业"`
	SellerMobile      string `description:"销售电话"`
	SellerName        string `description:"销售姓名"`
	IsFollow          bool   `description:"是否关注新调研通知"`
	Detail            *CygxActivitySpecialDetail
}

// 获取专项调研活动列表
func GetCygxActivitySpecialDetailList(condition string, pars []interface{}, uid, startSize, pageSize int) (items []*CygxActivitySpecialDetail, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
	art.*,
	(
	SELECT
		COUNT( 1 ) 
	FROM
		cygx_activity_special_signup AS s 
	WHERE
		s.activity_id = art.activity_id 
		AND s.user_id = ?
	) AS is_signup
FROM
	cygx_activity_special AS art
WHERE
	1 = 1 `
	if condition != "" {
		sql += condition
	}
	sql += `  LIMIT ?,? `
	_, err = o.Raw(sql, uid, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 通过活动ID获取活动详情
func GetCygxActivitySpecialDetailById(uid, ActivityId int) (item *CygxActivitySpecialDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT *,( SELECT COUNT( 1 ) FROM cygx_activity_special_signup AS s WHERE s.activity_id = a.activity_id AND s.user_id = ? ) AS is_signup 
FROM
	cygx_activity_special AS a 
WHERE
	activity_id = ?
	AND publish_status = 1 	AND is_offline = 0  `
	err = o.Raw(sql, uid, ActivityId).QueryRow(&item)
	return
}

// 通过活动ID获取活动详情
func GetCygxActivitySpecialDetail(ActivityId int) (item *CygxActivitySpecialDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity_special  WHERE activity_id=? AND publish_status = 1 `
	err = o.Raw(sql, ActivityId).QueryRow(&item)
	return
}

func UpdateCygxActivityName(activityId int, Name string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_activity SET activity_name_task = ? WHERE activity_id=?  `
	_, err = o.Raw(sql, Name, activityId).Exec()
	return
}

// 获取已发布但是为开始活动的权限
func GetActivityWeekPermission() (permission string, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT chart_permission_name SEPARATOR ',' ) AS permission 
		FROM
			cygx_activity 
		WHERE
			active_state = 1`
	err = o.Raw(sql).QueryRow(&permission)
	return
}

// 列表
func GetIndustrialActivityGroupManagementList(activityId int) (items []*IndustrialManagementRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			m.chart_permission_id,
			m.industrial_management_id,
			m.industry_name 
			FROM
			cygx_industrial_activity_group_management AS am
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = am.industrial_management_id
			WHERE
			am.activity_id = ? AND am.source = 1`
	_, err = o.Raw(sql, activityId).QueryRows(&items)
	return
}

// GetActivityListByYiDong 获取易董同步过来的活动列表
func GetActivityListByYiDong() (items []*CygxActivity, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM cygx_activity WHERE yidong_activity_id != '' `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// GetActivityListByYiDong 获取易董同步过来的活动列表
func GetActivityListByYiDongByCygx() (items []*CygxActivity, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM cygx_activity WHERE yidong_activity_id_by_cygx != '' `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// AddCygxActivity 添加活动
func AddCygxActivity(item *CygxActivity) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

// 列表
func GetActivityListByYidong(condition string) (items []*ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity WHERE 1 = 1 
	AND ( yidong_activity_id != '' OR yidong_activity_id_by_cygx != '' )  AND publish_status = 1  `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

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

// UpdateCygxActivitySubmitMeetingByActivityId  ，修改活动提交到会状态
func UpdateCygxActivitySubmitMeetingByActivityId(activityId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_activity SET is_submit_meeting = 1 WHERE activity_id  = ? `
	_, err = o.Raw(sql, activityId).Exec()
	return
}

// UpdateCygxActivitySubmitMeetingByYidong  ，跟易董返回的用户状态修改活动以提交到会状态
func UpdateCygxActivitySubmitMeetingByYidong(yidongActivityId string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_activity SET is_submit_meeting = 1 WHERE yidong_activity_id=? OR  yidong_activity_id_by_cygx = ? `
	_, err = o.Raw(sql, yidongActivityId, yidongActivityId).Exec()
	return
}

// UpdateActivityshowSubject 根据易董推过来的匹配信息，判断临时标签是否展示
func UpdateActivityshowSubject(activityId int) (err error) {
	sql := ` UPDATE cygx_activity SET  is_show_subject_name= 1 , temporary_label = ''  WHERE activity_id = ?`
	o := orm.NewOrm()
	_, err = o.Raw(sql, activityId).Exec()
	return
}

// GetActivitySpecialSearcheList 活动与专项调研的搜索
func GetActivitySpecialSearcheList(condition string, pars []interface{}, conditionSpecil string, parsSpecil []interface{}, startSize, pageSize int) (items []*ActivityDetail, total int, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			art.activity_id,
			art.activity_time_text,
			art.activity_name,
			art.chart_permission_id,
			art.active_state,
			t.activity_type,
			t.img_url_text,
			art.chart_permission_name,
			art.distinguished_guest,
			art.expert,
			art.speaker,
			"" AS trip_img_link,
			"" AS activity_time_end,
			art.yidong_activity_id,
			art.is_can_appointment_minutes,
			art.activity_type_id,
			art.limit_people_num,
			art.is_limit_people,
			art.city,
			1 AS source_type,
			art.is_yidong_conduct,
			art.activity_time,
			art.is_external_label,
			art.siginup_deadline,
			art.is_research_points,
			art.cancel_deadline
		FROM
			cygx_activity AS art
			INNER JOIN cygx_activity_type AS t ON t.activity_type_id = art.activity_type_id
		WHERE
			1 = 1 `
	if condition != `` {
		sql += condition
	}
	sql += ` UNION ALL
		SELECT
			art.activity_id,
			art.activity_time_text_by_day AS activity_time_text,
			art.research_theme AS activity_name,
			art.chart_permission_id,
			"",
			art.special_type AS activity_type,
			"",
			art.chart_permission_name,
			"",
			"",
			"",
			art.trip_img_link_fix AS trip_img_link,
			art.activity_time_end,
			"",
			"",
			"",
			"",
			"",
			"",
			2 AS source_type,
			"",
			art.activity_time,
			"",
			"",
			"",
			""
		FROM
			cygx_activity_special AS art
		WHERE
			1 = 1 `
	if conditionSpecil != "" {
		sql += conditionSpecil
	}
	totalSql := `SELECT COUNT(1) total FROM (` + sql + `) z `
	err = o.Raw(totalSql, pars, parsSpecil).QueryRow(&total)
	if err != nil {
		return
	}
	sql += ` ORDER BY activity_time DESC   LIMIT ?,?`
	_, err = o.Raw(sql, pars, parsSpecil, startSize, pageSize).QueryRows(&items)
	return
}

// 列表
func GetActivityListNew(condition string, pars []interface{}, uid, startSize, pageSize, playBack, filter int, typeName string) (items []*ActivityDetail, err error) {
	var sqlJiontable string
	if playBack == 1 {
		//sqlJiontable = ` INNER JOIN cygx_activity_voice AS ac ON ac.activity_id = art.activity_id `
	}
	if filter == 1 {
		sqlJiontable = ` INNER JOIN cygx_activity_video AS av ON av.activity_id = art.activity_id `
	} else if filter == 2 {
		sqlJiontable = ` INNER JOIN cygx_activity_voice AS ac ON ac.activity_id = art.activity_id `
	}

	o := orm.NewOrm()
	sql := `SELECT art.* ,t.activity_type,t.img_url_text,t.img_url_bg_yx,
		( SELECT COUNT( 1 ) FROM cygx_activity_signup AS s WHERE s.activity_id = art.activity_id AND s.user_id = ?   AND s.is_cancel = 0  AND s.do_fail_type = 0) AS is_signup,
		( SELECT COUNT( DISTINCT user_id ) FROM cygx_activity_signup AS s WHERE s.activity_id = art.activity_id   AND s.is_cancel = 0  AND s.do_fail_type = 0) AS signup_num,
		( SELECT COUNT( 1 ) FROM cygx_activity_meeting_reminder AS m WHERE m.activity_id = art.activity_id AND m.user_id = ?  AND m.is_cancel = 0  ) AS is_cancel_meeting_reminder,
		( SELECT COUNT( 1 ) FROM cygx_activity_appointment AS ap WHERE ap.activity_id = art.activity_id AND ap.user_id = ? ) AS is_appointment
		FROM cygx_activity as art
		INNER JOIN cygx_activity_type  as t ON t.activity_type_id = art.activity_type_id ` + sqlJiontable + ` WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` LIMIT ?,?`

	if typeName != "" {
		typeSlice := strings.Split(typeName, ",")
		tempCondition := ""
		for _, s := range typeSlice {
			if s == "1" {
				tempCondition += "'专家电话会',"
			} else if s == "2" {
				tempCondition += "'分析师电话会',"
			} else if s == "1,2" {
				tempCondition += "'专家电话会','分析师电话会',"
			}
		}
		tempCondition = strings.TrimRight(tempCondition, ",")
		sql = `SELECT * FROM(` + sql + `) AS t WHERE t.activity_type_name IN (` + tempCondition + `)`
	}
	_, err = o.Raw(sql, uid, uid, uid, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 列表
func GetActivityListHomeNew(condition string, startSize, pageSize int) (items []*ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT activity_id
		FROM cygx_activity as art
		INNER JOIN cygx_activity_type  as t ON t.activity_type_id = art.activity_type_id WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
	return
}

// 主题列表
func GetActivityLabelListAllNoLimit(condition, sortTime string, pars []interface{}, conditionSpecial string) (items []*CygxActivityLabelList, err error) {
	o := orm.NewOrm()
	sql := `SELECT	activity_id, label,temporary_label,is_show_subject_name, art.activity_time,	1 AS resource, yidong_activity_id 
		FROM cygx_activity as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += `  UNION ALL `
	sql += ` SELECT
			art.activity_id,
			art.label,
			art.temporary_label,
			is_show_subject_name,
			art.activity_time,
			2 AS resource,
			'' AS yidong_activity_id 
		FROM
			cygx_activity_special AS art   WHERE 1= 1 ` + conditionSpecial

	sql += ` GROUP BY label,resource  ORDER BY ` + sortTime + ` , activity_id DESC `

	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

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

// 批量修改弘则活动与进门财经的一个活动关联
func UpdateJmcjActivityIdGroup(items map[int]string) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw("UPDATE cygx_activity SET jmcj_activity_id = ? WHERE activity_id = ? AND jmcj_activity_id= '' ").Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for k, v := range items {
		_, err = p.Exec(v, k)
		if err != nil {
			return
		}
	}
	return
}

// UpdateActivityVmpRobotMeetingId 建立活动跟上海那边机器人助手参会信息的关联
func UpdateActivityVmpRobotMeetingId(vmpRobotMeetingId, activityId int) (err error) {
	sql := ` UPDATE cygx_activity SET   vmp_robot_meeting_id = ?  WHERE activity_id = ?`
	o := orm.NewOrm()
	_, err = o.Raw(sql, vmpRobotMeetingId, activityId).Exec()
	return
}

func GetYxActivitySendMsgListAll(endDate string) (items []*WxMsgCygxActivityList, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	s.id,
	s.user_id,
	s.fail_type,
	cr.open_id,
	a.*
FROM
	cygx_activity AS a
	INNER JOIN cygx_activity_signup AS s ON s.activity_id = a.activity_id
	INNER JOIN cygx_user_record AS cr ON cr.cygx_bind_account = s.mobile 
WHERE
	1 = 1 
	AND s.is_send_wx_msg = 0 
	AND s.do_fail_type = 0 
	AND a.publish_status = 1
	AND a.chart_permission_id = 31
	AND a.activity_time <= ? AND a.activity_time >= NOW() 
	AND s.is_cancel = 0
	GROUP BY s.id`
	_, err = o.Raw(sql, endDate).QueryRows(&items)
	return
}

// 获取买方研选这边的openid
func GetMfyxActivitySendMsgListAll(endDate string) (items []*WxMsgCygxActivityList, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	s.id,
	s.user_id,
	s.fail_type,
	cr.open_id,
	a.*
FROM
	cygx_activity AS a
	INNER JOIN cygx_activity_signup AS s ON s.activity_id = a.activity_id
	INNER JOIN cygx_mfyx_gzh_user_record AS cr ON cr.cygx_bind_account = s.mobile 
WHERE
	1 = 1 
	AND s.is_send_wx_msg = 0 
	AND s.do_fail_type = 0 
	AND a.publish_status = 1
	AND a.chart_permission_id = 31
	AND a.activity_time <= ? AND a.activity_time >= NOW() 
	AND s.is_cancel = 0
	GROUP BY s.id`
	_, err = o.Raw(sql, endDate).QueryRows(&items)
	return
}

// UpdateCygxActivityyidongActivityId  ，建立与易董的活动关联
func UpdateCygxActivityyidongActivityId(yidongActivityId, activityTime, yidongTitle string) (err error) {
	yidongTitle = "%" + yidongTitle + "%"
	o := orm.NewOrm()
	sql := ` UPDATE cygx_activity SET yidong_activity_id_by_cygx = ?  WHERE yidong_activity_id= '' AND   yidong_activity_id_by_cygx = ''  AND jmcj_activity_id= ''  AND  active_state = 3  AND  activity_time =?  AND activity_name_task LIKE  ?    `
	_, err = o.Raw(sql, yidongActivityId, activityTime, yidongTitle).Exec()
	return
}

// 获取所有未开始、进行中的活动ID
func GetActivityIdListNoEnd() (items []*CygxActivity, err error) {
	o := orm.NewOrm()
	sql := `SELECT activity_id  FROM cygx_activity WHERE  active_state IN (1,2) `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取活动详情
func GetAddActivityDetailByActivityIdinitCrm16_5(ActivityId []int) (items []*ActivityDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT a.*,t.activity_type FROM cygx_activity AS a 
			INNER JOIN cygx_activity_type  as t ON t.activity_type_id = a.activity_type_id  WHERE activity_id IN (` + utils.GetOrmInReplace(len(ActivityId)) + `) `
	_, err = o.Raw(sql, ActivityId).QueryRows(&items)
	return
}
