package cygx

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

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"`
}

type ActivityIdsResp struct {
	ActivityIds []int `description:"活动ID"`
}

type ActivityList struct {
	List []*ActivityType
}

// 列表
func GetActivityList() (items []*ActivityType, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_type ORDER BY sort DESC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

type ActivityCcustomerType struct {
	CustomerTypeId  int    `description:"活动类型id"`
	CustomerName    string `description:"活动名称"`
	PermissionValue string `description:"不同客户身份所对应的权限值"`
	Explain         string `description:"说明"`
	ExplainSpecial  string `description:"专项产业调研说明"`
}

type ActivityCcustomerTypeList struct {
	List []*ActivityCcustomerType
}

// 列表
func GetActivityCcustomerTypeList(condition string) (items []*ActivityCcustomerType, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_customer_type WHERE  1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += `  ORDER BY sort DESC `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 活动添加、修改入参
type ActivityRep struct {
	ActivityTypeId          int                          `description:"活动类型id"`
	PermissionName          string                       `description:"行业名称"`
	Body                    string                       `description:"内容"`
	LimitPeopleNum          int                          `description:"限制的人数数量"`
	CustomerTypeIds         string                       `description:"活动可见的客户类型，多个ID用 , 隔开  1、永续客户; 2、大套餐客户; 3、行业套餐客户; 4、专家套餐客户; 5、试用客户;6、冻结客户；7、流失客户  "`
	ActivityId              int                          `description:"活动ID 等于0新增活动，大于0修改活动"`
	DoType                  int                          `description:"操作类型 0，保存 、1，发布"`
	IsMakerShow             int                          `description:"是否仅决策人可见 0，否 、1，是"`
	VisibleRange            int                          `description:"可见范围 1，仅本组可见 、2，全部客户可见"`
	IsYidongConduct         int                          `description:"是否属于易董办会 1：是 、0：否"`
	IsCanOutboundCall       int                          `description:"是否提供外呼 1：是 、0：否"`
	LabelType               int                          `description:"标签类型 ，1单主题标签 ，2多主题标签"`
	IndustrialManagementIdS string                       `description:"产业ID，多个用 , 隔开"`
	IndustrialSubjectIdS    string                       `description:"标的ID，多个用,隔开"`
	Scale                   string                       `description:"管理规模，空不填，1：:50亿以下，2：50~100亿，3：100亿以上。多个用, 隔开"`
	IsExternalLabel         int                          `description:"是否为外部资源 1是，0否"`
	IsBClass                int                          `description:"是否为B类电话会 1是，0否"`
	IsNeedEmail             int                          `description:"是否需要提供邮箱 1是，0否"`
	SiginupDeadline         string                       `description:"报名截止时间"`
	IsResearchPoints        int                          `description:"是否为研选扣点  1是，0否"`
	IsResearch              bool                         `description:"是否为研选"`
	IsShowHz                int                          `description:"是否同时在弘则展示  1是，0否"`
	PointsSet               *CygxActivityPointsSetRsq    `description:"研选扣点明细"`
	VivoPointsSet           CygxActivityVivoPointsSetReq `description:"研选音视频扣点设置"`
	IsAllCustomerType       int                          `description:"是否全选活动可见类型 0无 1全选"`
	List                    []*ActivityGroupIndustrialRep
	VoiceList               []*CygxActivityVoiceReq
	VideoDetail             *CygxActivityVideoReq
	ListImgToText           []*AliyunOcrTextActivityResp `description:"识图建会的会议信息列表"`
	BackgroundImg           string                       `description:"封面图片"`
	ShareImg                string                       `description:"分享图片"`
	AreaType                int                          `description:"地区，1国内，2海外，默认1"`
}

// 活动添加、修改入参
type ActivityGroupIndustrialRep struct {
	IndustrialManagementIdS string `description:"产业ID，多个用 , 隔开"`
	IndustrialSubjectIdS    string `description:"标的ID，多个用,隔开"`
	IsShowSubjectName       int    `description:"小程序内是否展示标的名称 1是 ，0 否 默认0 "`
	TemporaryLabel          string `description:"临时标签"`
	IsCanAppointmentMinutes int    `description:"是否可预约纪要 1是 ，0 否 默认0 "`
}

// 活动详情
type ActivityDetail 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:"行业名称"`
	Body                      string `description:"内容"`
	CreateTime                string `description:"创建时间"`
	IsLimitPeople             int    `description:"是否限制人数 1是，0否"`
	LimitPeopleNum            string `description:"限制的人数数量"`
	CustomerTypeIds           string `description:"活动可见的客户类型，多个ID用 , 隔开"`
	PublishStatus             int    `description:"发布状态 1已发布，0未发布"`
	LastUpdatedTime           string `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:"活动名称"`
	OnlineParticipation       string `description:"网络参会"`
	ReportLink                string `description:"报告链接"`
	City                      string `description:"城市"`
	Address                   string `description:"活动地址"`
	Highlights                string `description:"活动亮点"`
	Remarks                   string `description:"备注"`
	ShowType                  string `description:"人数限制类型，1不展示限制，2可选限制，3强制限制"`
	Speaker                   string `description:"主讲人"`
	ActiveState               int    `description:"活动进行状态 未开始：1、进行中2、已结束3"`
	IsSubmitMeeting           int    `description:"是否提交过到会情况，1是，0否"`
	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 "`
	AdminId                   int    `description:"销售/管理员ID"`
	AdminName                 string `description:"销售/管理员姓名"`
	IsHideAppointment         int    `description:"是否隐藏预约纪要按钮  1是，0 否"`
	PermissionType            int    `description:"1主观，2客观"`
	Label                     string `description:"标签"`
	ListIndustrial            []*IndustrialActivityGroupManagementRep
	ListSubject               []*SubjectActivityGroupManagementRep
	IsCanAppointmentMinutes   int    `description:"是否可预约纪要 1是 ，0 否 默认0 "`
	YidongActivityId          string `description:"易董的活动ID"`
	YidongActivityEndTime     string `description:"易董活动截止时间"`
	VoiceList                 []*CygxActivityVoiceReq
	VideoDetail               *CygxActivityVideo
	ActivityJoinType          string                     `description:"活动入会类型01报名审核后可入会 02预约即可入会 03仅定向邀请人员可入会"`
	YidongSignUpEnd           string                     `description:"易董活动截止时间"` // 报名结束时间，适应于报名审核后可入会，为空表示不限制报名时间
	YidongSignUpStart         string                     `description:"易董活动截止时间"` // 报名开始时间，适应于报名审核后可入会，为空表示不限制报名时间
	PublishDate               string                     `description:"发布时间"`
	IsYidongConduct           int                        `description:"是否属于易董办会 1：是 、0：否"`
	IsCanOutboundCall         int                        `description:"是否提供外呼 1：是 、0：否"`
	YidongActivityIdByCygx    string                     `description:"通过查研观向建会易董返回的活动ID"`
	TencentConferenceNumber   string                     `description:"腾讯会议号"`
	IsExternalLabel           int                        `description:"是否为外部资源 1是，0否"`
	SigninImg                 string                     `description:"签到码图片"`
	IsResearchPoints          int                        `description:"是否为研选扣点  1是，0否"`
	IsBClass                  int                        `description:"是否为B类电话会 1是，0否"`
	IsNeedEmail               int                        `description:"是否需要提供邮箱 1是，0否"`
	SiginupDeadline           string                     `description:"报名截止时间"`
	PointsSet                 *CygxActivityPointsSetRsq  `description:"研选扣点明细"`
	VivoPointsSet             CygxActivityVivoPointsResp `description:"音视频扣点明细"`
	IsShowHz                  int                        `description:"是否同时在弘则展示  1是，0否"`
	ChartPermissionNameDeputy string                     `description:"副行业名称"`
	BackgroundImg             string                     `description:"封面图片"`
	ShareImg                  string                     `description:"分享图片"`
	TopTime                   int                        `description:"置顶时间"`
	AreaType                  int                        `description:"地区，1国内，2海外，默认1"`
}

type ActivityDetailRep struct {
	Detail         *ActivityDetail
	ListIndustrial []*IndustrialActivityGroupManagementRep
	ListSubject    []*SubjectActivityGroupManagementRep
}

// 活动详情
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:"行业名称辅助字段，区分研选子分类"`
	Body                      string    `description:"内容"`
	CreateTime                time.Time `description:"创建时间"`
	PublishDate               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 "`
	IsYidongConduct           int       `description:"是否属于易董办会 1：是 、0：否"`
	IsCanOutboundCall         int       `description:"是否提供外呼 1：是 、0：否"`
	IsCancel                  int       `description:"是否取消，1是，0否"`
	TencentConferenceNumber   string    `description:"腾讯会议号"`
	IsExternalLabel           int       `description:"是否为外部资源 1是，0否"`
	IsBClass                  int       `description:"是否为B类电话会 1是，0否"`
	IsNeedEmail               int       `description:"是否需要提供邮箱 1是，0否"`
	SiginupDeadline           string    `description:"报名截止时间"`
	IsResearchPoints          int       `description:"是否为研选扣点  1是，0否"`
	IsAllCustomerType         int       `description:"是否全选活动可见类型 0无 1全选"`
	IsShowHz                  int       `description:"是否同时在弘则展示  1是，0否"`
	ChartPermissionIdDeputy   int       `description:"行业id"`
	ChartPermissionNameDeputy string    `description:"行业名称"`
	CancelDeadline            string    `description:"取消报名截止时间"`
	AreaType                  int       `description:"地区，1国内，2海外，默认1"`
}

type CygxActivityEditDetail struct {
	ActivityId        int    `orm:"column(activity_id);pk";description:"活动ID 等于0新增活动，大于0修改活动"`
	ActivityTypeId    int    `description:"活动类型id"`
	ChartPermissionId int    `description:"行业id"`
	Body              string `description:"内容"`
	LimitPeopleNum    int    `description:"限制的人数数量"`
	CustomerTypeIds   string `description:"活动可见的客户类型，多个ID用 , 隔开"`
}

// 添加活动
func AddActivity(items []*CygxActivity, industrialActivityItems [][]*CygxIndustrialActivityGroupManagement, subjectActivityItems [][]*CygxIndustrialActivityGroupSubject, itemPointsSet *CygxActivityPointsSet) (newId int64, activityIdArr []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()
		}
	}()
	for k, v := range items {
		fmt.Println(v.ActivityName + "____标题")
		newId, err = to.Insert(v)
		activityIdArr = append(activityIdArr, int(newId))
		if err != nil {
			return
		}
		//添加关联的产业
		if len(industrialActivityItems) > 0 {
			for k1, v1 := range industrialActivityItems {
				if len(v1) > 0 && k == k1 {
					for _, v2 := range v1 {
						v2.ActivityId = int(newId)
						_, err = to.Insert(v2)
						if err != nil {
							return
						}
					}
				}
			}
		}
		//添加关联的标的
		if len(subjectActivityItems) > 0 {
			for k1, v1 := range subjectActivityItems {
				if len(v1) > 0 && k == k1 {
					for _, v2 := range v1 {
						v2.ActivityId = int(newId)
						_, err = to.Insert(v2)
						if err != nil {
							return
						}
					}
				}
			}
		}

		{
			//添加研选扣点内容
			if itemPointsSet.PointsObject != "" {
				itemPointsSet.ActivityId = int(newId)
				itemPointsSet.Id = 0 // 二次插入的时候主键被赋值了
				_, err = to.Insert(itemPointsSet)
				if err != nil {
					return
				}
			}
		}
	}

	//newId, err = to.Insert(item)
	return
}

// 通过纪要ID获取活动详情
func GetAddActivityInfoById(ActivityId int) (item *ActivityDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			a.*,t.permission_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 EditActivity(item *CygxActivity, oldPublishStatus int, industrialActivityItems [][]*CygxIndustrialActivityGroupManagement, subjectActivityItems [][]*CygxIndustrialActivityGroupSubject, itemPointsSet *CygxActivityPointsSet) (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()
		}
	}()
	activityId := item.ActivityId
	//修改活动信息
	updateParams := make(map[string]interface{})
	updateParams["ActivityTypeId"] = item.ActivityTypeId
	updateParams["ActivityTypeName"] = item.ActivityTypeName
	updateParams["ChartPermissionId"] = item.ChartPermissionId
	updateParams["ChartPermissionName"] = item.ChartPermissionName
	updateParams["ChartPermissionNames"] = item.ChartPermissionNames
	updateParams["Body"] = item.Body
	updateParams["IsLimitPeople"] = item.IsLimitPeople
	updateParams["LimitPeopleNum"] = item.LimitPeopleNum
	updateParams["CustomerTypeIds"] = item.CustomerTypeIds
	updateParams["PublishStatus"] = item.PublishStatus
	updateParams["LastUpdatedTime"] = item.LastUpdatedTime
	updateParams["ActivityTime"] = item.ActivityTime
	updateParams["ActivityTimeText"] = item.ActivityTimeText
	updateParams["DistinguishedGuest"] = item.DistinguishedGuest
	updateParams["Host"] = item.Host
	updateParams["MainlandTell"] = item.MainlandTell
	updateParams["HongKongTell"] = item.HongKongTell
	updateParams["TaiwanTell"] = item.TaiwanTell
	updateParams["AmericaTell"] = item.AmericaTell
	updateParams["ParticipationCode"] = item.ParticipationCode
	updateParams["Theme"] = item.Theme
	updateParams["Expert"] = item.Expert
	updateParams["ActivityName"] = item.ActivityName
	updateParams["OnlineParticipation"] = item.OnlineParticipation
	updateParams["ReportLink"] = item.ReportLink
	updateParams["City"] = item.City
	updateParams["Address"] = item.Address
	updateParams["Highlights"] = item.Highlights
	updateParams["Remarks"] = item.Remarks
	updateParams["ArticleId"] = item.ArticleId
	updateParams["TemporaryLabel"] = item.TemporaryLabel
	updateParams["Speaker"] = item.Speaker
	updateParams["LinkParticipants"] = item.LinkParticipants
	updateParams["AppAttendance"] = item.AppAttendance
	updateParams["ConferencePassword"] = item.ConferencePassword
	updateParams["Label"] = item.Label
	updateParams["Scale"] = item.Scale
	updateParams["IsShowSubjectName"] = item.IsShowSubjectName
	updateParams["ActivityNameTask"] = item.ActivityNameTask
	updateParams["AdminId"] = item.AdminId
	updateParams["AdminName"] = item.AdminName
	updateParams["IsHideAppointment"] = item.IsHideAppointment
	updateParams["IsMakerShow"] = item.IsMakerShow
	updateParams["VisibleRange"] = item.VisibleRange
	updateParams["IsCanAppointmentMinutes"] = item.IsCanAppointmentMinutes
	updateParams["PublishDate"] = item.PublishDate
	updateParams["IsYidongConduct"] = item.IsYidongConduct
	updateParams["IsCanOutboundCall"] = item.IsCanOutboundCall
	updateParams["TencentConferenceNumber"] = item.TencentConferenceNumber
	updateParams["IsExternalLabel"] = item.IsExternalLabel
	updateParams["IsCancel"] = item.IsCancel
	updateParams["IsBClass"] = item.IsBClass
	updateParams["IsNeedEmail"] = item.IsNeedEmail
	updateParams["SiginupDeadline"] = item.SiginupDeadline
	updateParams["IsResearchPoints"] = item.IsResearchPoints
	updateParams["IsAllCustomerType"] = item.IsAllCustomerType
	if item.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
		updateParams["IsShowHz"] = item.IsShowHz //研选的才做修改
	}
	updateParams["ChartPermissionNameDeputy"] = item.ChartPermissionNameDeputy
	updateParams["ChartPermissionIdDeputy"] = item.ChartPermissionIdDeputy
	updateParams["CancelDeadline"] = item.CancelDeadline
	updateParams["AreaType"] = item.AreaType
	//修改活动信息
	ptrStructOrTableName := "cygx_activity"
	whereParam := map[string]interface{}{"activity_id": item.ActivityId}
	qs := to.QueryTable(ptrStructOrTableName)
	for expr, exprV := range whereParam {
		qs = qs.Filter(expr, exprV)
	}
	_, err = qs.Update(updateParams)

	//删除活动关联的产业
	sql := ` DELETE FROM cygx_industrial_activity_group_management WHERE activity_id = ?  AND source =1 `
	_, err = to.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	//删除活动关联的标的
	sql = ` DELETE FROM cygx_industrial_activity_group_subject WHERE activity_id = ?   AND source =1`
	_, err = to.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	//添加关联的产业
	if len(industrialActivityItems) > 0 {
		for _, v1 := range industrialActivityItems {
			if len(v1) > 0 {
				for _, v2 := range v1 {
					_, err = to.Insert(v2)
					if err != nil {
						return
					}
				}
			}
		}
	}
	//添加关联的标的
	if len(subjectActivityItems) > 0 {
		for _, v1 := range subjectActivityItems {
			if len(v1) > 0 {
				for _, v2 := range v1 {
					_, err = to.Insert(v2)
					if err != nil {
						return
					}
				}
			}
		}
	}

	{
		//处理研选扣点子表
		if itemPointsSet.PointsObject == "" {
			sql := ` DELETE FROM cygx_activity_points_set WHERE activity_id = ?`
			_, err = to.Raw(sql, activityId).Exec()
			if err != nil {
				return
			}
		} else {
			var countpoints int
			sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_activity_points_set  WHERE activity_id=?   `
			err = to.Raw(sqlCount, activityId).QueryRow(&countpoints)
			if err != nil {
				return
			}
			itemPointsSet.ActivityId = activityId
			if countpoints == 0 {
				_, err = to.Insert(itemPointsSet)
				if err != nil {
					return
				}
			} else {
				updateParams := make(map[string]interface{})
				updateParams["PointsObject"] = itemPointsSet.PointsObject
				updateParams["CompanyId"] = itemPointsSet.CompanyId
				updateParams["CompanyName"] = itemPointsSet.CompanyName
				updateParams["UserPointsNum"] = itemPointsSet.UserPointsNum
				updateParams["PointsType"] = itemPointsSet.PointsType
				updateParams["CompanyPointsNum"] = itemPointsSet.CompanyPointsNum
				updateParams["ModifyTime"] = itemPointsSet.ModifyTime
				updateParams["CancelDeadlineType"] = itemPointsSet.CancelDeadlineType
				//修改活动信息
				ptrStructOrTableName = "cygx_activity_points_set"
				whereParam := map[string]interface{}{"activity_id": itemPointsSet.ActivityId}
				qs := to.QueryTable(ptrStructOrTableName)
				for expr, exprV := range whereParam {
					qs = qs.Filter(expr, exprV)
				}
				_, err = qs.Update(updateParams)
				if err != nil {
					return
				}
			}
		}
	}

	return
}

// 修改
func EditActivityStatus(activityId 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()
		}
	}()
	sql := `UPDATE cygx_activity SET active_state=1, is_send_file_toemail=0 ,is_send_ask_msg = 0 WHERE activity_id=?`
	_, err = to.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	sql = `UPDATE cygx_activity_signup SET is_send_wx_msg=0 WHERE activity_id=?`
	_, err = to.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	sql = `UPDATE cygx_activity_meeting_reminder SET is_send_wx_msg=0 WHERE activity_id=?`
	_, err = to.Raw(sql, activityId).Exec()
	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:"活动类型名称"`
	ActiveState               int    `description:"活动进行状态 未开始：1、进行中2、已结束3"`
	ChartPermissionId         int    `description:"行业id"`
	ChartPermissionName       string `description:"行业名称"`
	ChartPermissionNames      string `description:"行业名称辅助字段，区分研选子分类"`
	Body                      string `description:"内容"`
	IsLimitPeople             int    `description:"是否限制人数 1是，0否"`
	LimitPeopleNum            int    `description:"限制的人数数量"`
	CustomerTypeIds           string `description:"活动可见的客户类型，多个ID用 , 隔开"`
	PublishStatus             int    `description:"发布状态 1已发布，0未发布"`
	LastUpdatedTime           string `description:"更新时间"`
	ActivityTime              string `description:"活动时间"`
	ActivityTimeText          string `description:"活动时间带文字"`
	Label                     string `description:"标签"`
	YidongActivityId          string `description:"易董的活动ID"`
	TemporaryLabel            string `description:"临时标签"`
	IsCancel                  int    `description:"是否取消，1是，0否"`
	IsUpload                  bool   `description:"是否上传"`
	IsYidongConduct           int    `description:"是否属于易董办会 1：是 、0：否"`
	IsShowSigninButton        bool   `description:"是否展示签到码按钮"`
	SigninImg                 string `description:"签到码图片"`
	ChartPermissionNameDeputy string `description:"副行业名称"`
	TopTime                   int    `description:"置顶时间"`
}

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

// 列表
func GetActivityListAll(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxActivityList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	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 GetActivityCount(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 GetActivityCountById(activityId int) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sqlCount := `SELECT COUNT(1) AS count  FROM cygx_activity WHERE activity_id = ?`
	err = o.Raw(sqlCount, activityId).QueryRow(&count)
	return
}

// 修改发布状态
func ActivityPublishAndCancel(item *CygxActivity) (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()
		}
	}()
	activityId := item.ActivityId
	sql := `UPDATE cygx_activity SET  publish_status=? , last_updated_time= ? ,admin_id =?,admin_name =? ,publish_date=?,is_cancel=? WHERE activity_id=? `
	_, err = to.Raw(sql, item.PublishStatus, time.Now(), item.AdminId, item.AdminName, item.PublishDate, item.IsCancel, activityId).Exec()
	if err != nil {
		return
	}
	return
}

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

// 更新手动匹配的活动匹配关键词，建立匹配关系
func UpdateActivityRoadshowTitle(activityId int, roadshowTitle, roadshowId string) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` UPDATE cygx_activity SET  jmcj_roadshow_title=?,jmcj_activity_id=?   WHERE activity_id=?`
	_, err = o.Raw(sql, roadshowTitle, roadshowId, activityId).Exec()
	return
}

// 列表
func GetArticleListByCategoryId(categoryIds, industrialSubjectIdS string) (items []*CygxArticle, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
				* 
			FROM
				cygx_article AS a
				INNER JOIN cygx_industrial_article_group_subject AS s ON s.article_id = a.article_id 
			WHERE
				a.category_id IN (` + categoryIds + ` ) 
				AND a.publish_status = 1 
				AND DATE_SUB( CURDATE(), INTERVAL 14 DAY ) <= date( a.publish_date ) 
				AND s.industrial_subject_id IN ( ` + industrialSubjectIdS + ` ) 
			GROUP BY
				a.article_id 
			ORDER BY
				a.publish_date DESC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 通过产业名称获取关联的ID
func GetactivityIdsByLabel(name string) (activityIds string, err error) {
	sql := ` SELECT
				GROUP_CONCAT( DISTINCT s.activity_id SEPARATOR ',' ) AS activityIds 
			FROM
				cygx_activity AS s 
			WHERE
				label LIKE '%` + name + `%' `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sql).QueryRow(&activityIds)
	return
}

// 根据易董的建会信息，修改腾讯参会信息
func UpdateCygxActivityTencentConferenceNumber(item *ActivityDetail) (err error) {
	sql := `UPDATE cygx_activity SET  tencent_conference_number=?,yidong_activity_id_by_cygx=?, body = ?  WHERE activity_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, item.TencentConferenceNumber, item.YidongActivityIdByCygx, item.Body, item.ActivityId).Exec()
	return
}

// 添加场所码
func UpdateCygxActivitySigninImg(signinImg string, activityId int) (err error) {
	sql := `UPDATE cygx_activity SET  signin_img=?  WHERE activity_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, signinImg, activityId).Exec()
	return
}

type AliyunOcrTextActivityResp struct {
	TitmeYMD string `description:"时间年月日"`
	TitmeHM  string `description:"时间时分"`
	Company  string `description:"公司名称"`
}

type AliyunOcrTextActivityListResp struct {
	List []*AliyunOcrTextActivityResp
}

// 更新活动置顶时间
func UpdateActivityTopTime(activityId, topTime int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` UPDATE cygx_activity SET  top_time=? WHERE activity_id=?`
	_, err = o.Raw(sql, topTime, activityId).Exec()
	return
}

// 添加朋友圈分享封面图片
func UpdateCygxActivityMomentsImg(momentsImg string, activityId int) (err error) {
	sql := `UPDATE cygx_activity SET  moments_img=?  WHERE activity_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, momentsImg, activityId).Exec()
	return
}
