package cygx

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/services/elastic"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// 活动
type ActivityCoAntroller struct {
	controllers.BaseAuthController
}

// @Title 活动客户列表
// @Description 活动客户列表接口
// @Param   IsZxdy   query   bool  false     "是否展示专项调研类型"
// @Success 200 {object} cygx.ActivityCcustomerTypeList
// @router /activity/customerTypelist [get]
func (this *ActivityCoAntroller) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	isZxdy, _ := this.GetBool("IsZxdy", false)
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	resp := new(cygx.ActivityCcustomerTypeList)
	var condition string
	if !isZxdy {
		condition += ` AND  is_activity = 1 `
	} else {
		condition += ` AND  is_apecial = 1 `
	}
	list, err := cygx.GetActivityCcustomerTypeList(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 活动内容的保存与发布
// @Description 活动内容的保存与发布接口
// @Param	request	body cygx.ActivityRep true "type json string"
// @Success 200 操作成功
// @router /activity/PreserveAndPublish [post]
func (this *ActivityCoAntroller) PreserveAndPublish() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.ActivityRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	//处理识图建会的会议信息列表 因为活动发布处理的业务逻辑过多，方便后期统一维护这里 根据 list 数据类型自己拼接 活动的 body  查研观向 11.12
	listImgToText := req.ListImgToText

	if len(listImgToText) > 0 {
		var errmsg string
		req, err, errmsg = cygxService.MakeActivityReqText(listImgToText)
		if err != nil {
			br.Msg = "识图建会失败！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
		if errmsg != "" {
			br.Msg = "识图建会失败，" + errmsg
			br.ErrMsg = "识图建会失败，" + errmsg
			return
		}
	}
	if req.Body == "" {
		br.Msg = "内容不可为空"
		return
	}

	//return
	//不限制人数的，强制改为全部客户可见
	if req.LimitPeopleNum == 0 {
		req.VisibleRange = 2
		req.IsMakerShow = 0
		req.Scale = ""
		req.CustomerTypeIds = ""
	}
	if req.IsResearchPoints == 0 {
		req.SiginupDeadline = ""
	}
	activityId := req.ActivityId
	labelType := req.LabelType
	labelList := req.List
	activityTypeId := req.ActivityTypeId
	scale := req.Scale
	voiceList := req.VoiceList
	videoDetail := req.VideoDetail
	isBClass := req.IsBClass
	isResearchPoints := req.IsResearchPoints
	vivoPointsSet := req.VivoPointsSet
	isShowHz := req.IsShowHz
	isResearch := req.IsResearch //是否是研选类型的活动
	if isResearch {
		req.PermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
	}
	var items []*cygx.CygxActivity
	//temporaryLabel := req.TemporaryLabel
	industrialManagementIdS := req.IndustrialManagementIdS
	industrialSubjectIdS := req.IndustrialSubjectIdS
	body := req.Body
	customerTypeIds := req.CustomerTypeIds

	if req.VisibleRange != 1 {
		req.VisibleRange = 2
	}
	//公司调研电话会，增加【外部资源】勾选项，其他的强制过滤
	if req.ActivityTypeId != 3 {
		req.IsExternalLabel = 0
	}
	isExternalLabel := req.IsExternalLabel
	pointsSet := req.PointsSet
	isNeedEmail := req.IsNeedEmail
	siginupDeadline := req.SiginupDeadline
	if customerTypeIds != "" {
		condition := ` AND  customer_type_id IN  (` + customerTypeIds + `)`
		listValue, err := cygx.GetActivityCcustomerTypeList(condition)
		if err != nil {
			br.Msg = "活动可见套餐类型错误，请核实"
			return
		}
		req.CustomerTypeIds = ""
		for _, v := range listValue {
			req.CustomerTypeIds += v.PermissionValue + ","
		}
		req.CustomerTypeIds = strings.TrimRight(req.CustomerTypeIds, ",")
	}

	if len(voiceList) > 0 && videoDetail != nil {
		br.Msg = "音频与视频只能上传一个"
		return
	}
	body = strings.Replace(body, "&nbsp; ", "", -1)
	body = strings.Replace(body, "&nbsp;", "", -1)
	slice := strings.Split(body, "<hr>")

	if activityId == 0 {
		if activityTypeId == 1 {
			if labelType != 1 && labelType != 2 {
				br.Msg = "请选择主题标签"
				return
			}
		}
	}

	var industrialActivityItemsList [][]*cygx.CygxIndustrialActivityGroupManagement
	var subjectActivityItemsList [][]*cygx.CygxIndustrialActivityGroupSubject
	var industryAndSubjectNameItems []*cygx.IndustryAndSubjectName
	var industrialNames string
	var industrialSubjectNames string
	industryIds := make([]int, 0)

	for _, vLabel := range labelList {
		var industrialActivityItems []*cygx.CygxIndustrialActivityGroupManagement
		var subjectActivityItems []*cygx.CygxIndustrialActivityGroupSubject
		if vLabel.IndustrialManagementIdS != "" {
			industrialManagementIdS = vLabel.IndustrialManagementIdS
			industrialSubjectIdS = vLabel.IndustrialSubjectIdS
			if industrialManagementIdS == "" {
				br.Msg = "请选择产业"
				return
			}
			industrialManagementIdS = strings.Replace(industrialManagementIdS, " ", "", -1)
			industrialManagementList := strings.Split(industrialManagementIdS, ",")
			for _, v := range industrialManagementList {
				industrialActivityItem := new(cygx.CygxIndustrialActivityGroupManagement)
				industrialManagementId, err := strconv.Atoi(v)
				if err != nil {
					br.Msg = "参数解析异常！"
					br.ErrMsg = "产业ID不规范，Err:" + err.Error() + industrialManagementIdS
					return
				}
				industryIds = append(industryIds, industrialManagementId)
				industrialActivityItem.CreateTime = time.Now()
				industrialActivityItem.IndustrialManagementId = industrialManagementId
				industrialActivityItem.ActivityId = activityId
				industrialActivityItem.Source = 1
				industrialActivityItems = append(industrialActivityItems, industrialActivityItem)
			}

			if industrialSubjectIdS != "" {
				industrialSubjectIdList := strings.Split(industrialSubjectIdS, ",")
				for _, v := range industrialSubjectIdList {
					subjectActivityItem := new(cygx.CygxIndustrialActivityGroupSubject)
					industrialSubjectId, err := strconv.Atoi(v)
					if err != nil {
						br.Msg = "参数解析异常！"
						br.ErrMsg = "标的ID不规范，Err:" + err.Error() + industrialManagementIdS
						return
					}
					subjectActivityItem.CreateTime = time.Now()
					subjectActivityItem.IndustrialSubjectId = industrialSubjectId
					subjectActivityItem.ActivityId = activityId
					subjectActivityItem.Source = 1
					subjectActivityItems = append(subjectActivityItems, subjectActivityItem)
				}
			}

			//产业名称
			if industrialManagementIdS != "" {
				industrialNames, err = cygx.GetindustrialManagementNames(industrialManagementIdS)
				if err != nil {
					br.Msg = "参数解析异常！"
					br.ErrMsg = "产业ID不规范，Err:" + err.Error() + industrialManagementIdS
					return
				}
			}
			//标的名称
			if industrialSubjectIdS != "" {
				industrialSubjectNames, err = cygx.GetindustrialSubjectNames(industrialSubjectIdS)
				if err != nil {
					br.Msg = "参数解析异常！"
					br.ErrMsg = "标的ID不规范，Err:" + err.Error() + industrialSubjectIdS
					return
				}
			} else {
				industrialSubjectNames = ""
			}
		}

		if len(industrialActivityItems) == 0 {
			industrialActivityItems = make([]*cygx.CygxIndustrialActivityGroupManagement, 0)
		}

		if len(subjectActivityItems) == 0 {
			subjectActivityItems = make([]*cygx.CygxIndustrialActivityGroupSubject, 0)
		}

		industrialActivityItemsList = append(industrialActivityItemsList, industrialActivityItems)
		subjectActivityItemsList = append(subjectActivityItemsList, subjectActivityItems)
		//合并产业以及标的的名称
		industryAndSubjectNameItem := new(cygx.IndustryAndSubjectName)
		industryAndSubjectNameItem.IndustryNames = industrialNames
		industryAndSubjectNameItem.SubjectNames = industrialSubjectNames
		industryAndSubjectNameItem.TemporaryLabel = vLabel.TemporaryLabel
		industrialNames = ""
		industrialSubjectNames = ""
		industryAndSubjectNameItems = append(industryAndSubjectNameItems, industryAndSubjectNameItem)
	}

	if labelType == 1 || labelType == 0 {
		if len(slice) > len(industrialActivityItemsList) {
			for k := range slice {
				if k > 0 {
					if len(industrialActivityItemsList) > 0 {
						industrialActivityItemsList = append(industrialActivityItemsList, industrialActivityItemsList[0])
					}
					if len(subjectActivityItemsList) > 0 {
						subjectActivityItemsList = append(subjectActivityItemsList, subjectActivityItemsList[0])
					}
					if len(industryAndSubjectNameItems) > 0 {
						industryAndSubjectNameItems = append(industryAndSubjectNameItems, industryAndSubjectNameItems[0])
					}
				}
			}
		}
	}
	if labelType == 2 {
		if len(slice) != len(labelList) {
			br.Msg = "活动和主题个数不符，请核实"
			return
		}
	}
	permissionName := req.PermissionName
	//List := cygxService.GetActChartPermissionList()
	//var haveCheck bool
	//for _, v := range List {
	//	if permissionName == v.PermissionName {
	//		haveCheck = true
	//	}
	//}
	//if !haveCheck {
	//	br.Msg = "行业名称：" + permissionName + "不存在"
	//	return
	//}
	if strings.Contains(permissionName, utils.CHART_PERMISSION_NAME_YANXUAN) {
		permissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
	}
	//charInfo, errCategory := cygx.GetCategoryInfoById(req.ChartPermissionId)
	charInfo, errCategory := cygx.GetCategoryInfoByName(permissionName)
	if errCategory != nil {
		br.Msg = "请选择所属行业"
		br.ErrMsg = "获取所属行业信息失败,Err:" + errCategory.Error()
		return
	}
	if charInfo.PermissionName == "宏观经济" {
		charInfo.PermissionName = "宏观"
	}

	activityTypeInfo, errType := cygx.GetActivityTypeDetailById(activityTypeId)
	if errType != nil {
		br.Msg = "请选择活动类型"
		br.ErrMsg = "获取活动类型信息失败,Err:" + errType.Error()
		return
	}
	var activeState int
	var checkYidong bool
	if req.ActivityId > 0 {
		activityInfo, errInfo := cygx.GetAddActivityInfoById(req.ActivityId)
		if errInfo != nil {
			br.Msg = "活动不存在"
			br.ErrMsg = "活动ID错误，ActivityId：" + strconv.Itoa(req.ActivityId)
			return
		}
		if activityInfo.ActiveState > 1 {
			activeState = activityInfo.ActiveState
		}
		if activityInfo.YidongActivityId != "" {
			checkYidong = true
		}
		//校验活动后台管理员、销售是否有修改权限
		havePower, popupMsg, err := cygxService.CheckActivityUpdatePower(AdminUser.AdminId, activityInfo)
		if err != nil {
			br.Msg = "获取管理员身份信息失败"
			br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
			return
		}
		if !havePower {
			br.Msg = popupMsg
			return
		}
	}

	var itemPointsSet = new(cygx.CygxActivityPointsSet)
	var itemPointsSetOld = new(cygx.CygxActivityPointsSetRsq)
	if activityId > 0 {
		itemPointsSetOld, err = cygx.GetCygxActivityPointsSetDetail(activityId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取信息失败"
			br.ErrMsg = "GetCygxActivityPointsSetDetail，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
			return
		}
	}
	//校验研选扣点内容,对于已结束的活动不做点数校验
	if isResearchPoints == 1 {
		errMsg, itemResp, err := cygxService.CheckActivityPointsSet(pointsSet, activityId)
		if errMsg != "" {
			br.Msg = errMsg
			return
		}
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "操作失败,Err:" + err.Error()
			return
		}
		itemPointsSet = itemResp
	}
	for k, v := range slice {
		//如果内容不存在 时间：字段则不予处理
		if strings.Contains(v, "时间：") || strings.Contains(v, "时间:") {
			slicebr := strings.Split(v, "<br")
			//浏览器兼容处理
			if len(slicebr) > 5 {
				v = strings.Replace(v, "br", "p", -1)
			}
			v = strings.Replace(v, "<p><br></p>", "", -1) //删除空标签，兼容标题顶部空格、换行
			v = strings.Replace(v, "<p><p></p>", "", -1)
			v = strings.Replace(v, "<p></p>", "", -1)
			v = strings.Replace(v, "<p><p>", "", -1)
			v = strings.Replace(v, "<br>", "", -1)
			v = strings.Replace(v, "<p id=\"isPasted\"></p>", "", -1)
			item, errstr := cygxService.ActivityBodyAnalysis(v, activeState, req)
			if len(errstr) > 0 {
				br.Msg = errstr
				br.IsSendEmail = false
				return
			}
			var temporaryLabel string
			if len(labelList) == 1 {
				temporaryLabel = labelList[0].TemporaryLabel
			} else {
				temporaryLabel = labelList[k].TemporaryLabel
			}
			item.TemporaryLabel = temporaryLabel
			item.IsBClass = isBClass

			if item.ReportLink != "" {
				articleIdLink, err := cygxService.GetReportLinkToArticleid(item.ReportLink)
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "解析报告链接ID失败，Err:" + err.Error()
					return
				}
				item.ArticleId = articleIdLink
			}
			//if k == 0 && item.Label == "" {
			//	br.Msg = "请填写活动标签"
			//	return
			//}
			item.AdminId = AdminUser.AdminId
			item.AdminName = AdminUser.RealName
			item.Body = v
			item.ChartPermissionName = charInfo.PermissionName
			item.ChartPermissionNames = req.PermissionName
			item.ChartPermissionId = charInfo.ChartPermissionId
			item.ActivityTypeName = activityTypeInfo.ActivityTypeName
			item.ActivityTypeId = activityTypeInfo.ActivityTypeId
			item.CustomerTypeIds = req.CustomerTypeIds
			item.LimitPeopleNum = req.LimitPeopleNum
			item.IsMakerShow = req.IsMakerShow
			item.VisibleRange = req.VisibleRange
			item.PublishDate = time.Now()
			item.IsYidongConduct = req.IsYidongConduct
			item.IsCanOutboundCall = req.IsCanOutboundCall
			item.IsNeedEmail = isNeedEmail
			item.AreaType = req.AreaType

			if len(listImgToText) > 0 {
				resultTime := utils.StrTimeToTime(item.ActivityTime)                                       //时间字符串格式转时间格式
				item.SiginupDeadline = resultTime.AddDate(0, 0, -1).Format(utils.FormatDate) + " 15:30:00" //批量建会报名截止之前默认：活动前一天15:30:00
			} else {
				item.SiginupDeadline = siginupDeadline
			}

			if isResearchPoints == 1 {
				item.IsResearchPoints = 1
			}
			//当不限制人数的时候，强制改为全部客户可见
			//if req.LimitPeopleNum == 0 {
			//	item.VisibleRange = 2
			//}
			////除了C类电话会其他类型的会议，强制改为全部客户可见
			//if req.ActivityTypeId != 7 {
			//	item.VisibleRange = 2
			//}
			item.CreateTime = time.Now()
			item.LastUpdatedTime = time.Now()
			item.Scale = scale
			item.IsExternalLabel = isExternalLabel
			item.IsAllCustomerType = req.IsAllCustomerType
			item.IsShowHz = isShowHz
			item.ChartPermissionIdDeputy = charInfo.ChartPermissionId
			item.ChartPermissionNameDeputy = charInfo.PermissionName
			if len(labelList) == 1 {
				item.IsCanAppointmentMinutes = labelList[0].IsCanAppointmentMinutes
			} else {
				item.IsCanAppointmentMinutes = labelList[k].IsCanAppointmentMinutes
			}
			if item.ActivityName == "" {
				br.Msg = "请填写活动名称"
				return
			}
			if item.ActivityTime == "" {
				br.Msg = "请填写活动时间"
				return
			}
			//过滤标题中的符号，同步进门财经的时候使用
			newActivityName := item.ActivityName
			newActivityName = strings.Replace(newActivityName, "【", "", -1)
			newActivityName = strings.Replace(newActivityName, "】", "", -1)
			newActivityName = strings.Replace(newActivityName, "-", "", -1)
			newActivityName = strings.Replace(newActivityName, "—", "", -1)
			newActivityName = strings.Replace(newActivityName, " ", "", -1)
			newActivityName = strings.Replace(newActivityName, ":", "", -1)
			item.ActivityNameTask = newActivityName

			if !checkYidong {
				if activityTypeId == 1 {
					if item.Expert == "" {
						br.Msg = "请填写专家信息"
						return
					}
					if item.Host == "" {
						br.Msg = "请填写主持人信息"
						return
					}
				}
				if activityTypeId == 2 {
					if item.Speaker == "" {
						br.Msg = "请填写主讲人信息"
						return
					}
				}
				if activityTypeId == 3 {
					if item.DistinguishedGuest == "" {
						br.Msg = "请填写嘉宾信息"
						return
					}
					if item.Host == "" {
						br.Msg = "请填写主持人信息"
						return
					}
				}
				if activityTypeId == 4 {
					if item.DistinguishedGuest == "" {
						br.Msg = "请填写嘉宾信息"
						return
					}
					if item.Host == "" {
						br.Msg = "请填写主持人信息"
						return
					}
					if req.LimitPeopleNum == 0 {
						br.Msg = "请填写参会限制人数"
						return
					}
				}
				if activityTypeId == 5 {
					if item.Expert == "" {
						br.Msg = "请填写专家信息"
						return
					}
					if req.LimitPeopleNum == 0 {
						br.Msg = "请填写参会限制人数"
						return
					}
				}
				if activityTypeId == 6 {
					if item.Speaker == "" {
						br.Msg = "请填写主讲人信息"
						return
					}
					if req.LimitPeopleNum == 0 {
						br.Msg = "请填写参会限制人数"
						return
					}
				}
			}
			if req.LimitPeopleNum > 0 {
				item.IsLimitPeople = 1
			}
			if req.DoType == 1 {
				item.PublishStatus = 1
			}
			//当临时标的不为空的时候，标签为临时标的，否则为所选产业跟标的的组合
			if temporaryLabel != "" {
				item.Label = temporaryLabel
			} else {
				var labelNewStr string
				industrialNames = industryAndSubjectNameItems[k].IndustryNames
				industrialSubjectNames = industryAndSubjectNameItems[k].SubjectNames
				if industrialNames == "" && industrialSubjectNames != "" {
					labelNewStr = industrialSubjectNames
				} else if industrialNames != "" && industrialSubjectNames != "" {
					labelNewStr = industrialNames + "-" + industrialSubjectNames
				} else if industrialNames != "" && industrialSubjectNames == "" {
					labelNewStr = industrialNames
				}
				item.Label = labelNewStr
				if len(labelList) == 1 {
					item.IsShowSubjectName = labelList[0].IsShowSubjectName
				} else {
					item.IsShowSubjectName = labelList[k].IsShowSubjectName
				}
			}
			if item.ActivityTypeId == 2 {
				if item.ReportLink == "" {
					if labelList[k].IndustrialSubjectIdS != "" {
						item.ReportLink, err = cygxService.ActivityReportLink(item, labelList[k].IndustrialSubjectIdS)
						if err != nil {
							br.Msg = "发布失败"
							br.ErrMsg = "发布失败自动获取报告链接失败,Err:" + err.Error()
							return
						}
					}
				} else {
					sliceArt := strings.Split(item.ReportLink, "/")
					if len(sliceArt) > 0 {
						articleId, err := strconv.Atoi(sliceArt[len(sliceArt)-1])
						if err != nil {
							br.Msg = "报告链接格式错误！"
							return
						}
						detailArt, err := cygx.GetArticleIdInfoByArticleId(articleId)
						if err != nil {
							br.Msg = "内容不存在"
							br.ErrMsg = "操作失败,Err:" + err.Error()
							return
						}
						//类型ID 医药(医享会：28 、药调研：301)、消费【渠道新声：32】、科技【科技前言：79】、智造【匠心智造：84】
						if detailArt.CategoryId != 28 && detailArt.CategoryId != 301 && detailArt.CategoryId != 32 && detailArt.CategoryId != 79 && detailArt.CategoryId != 84 {
							item.IsHideAppointment = 1
						}
					}

				}
			}

			items = append(items, item)

			var errAct error
			if req.ActivityId == 0 {

			} else {
				if len(slice) > 1 {
					br.Msg = "文本格式错误，请删除多余活动"
					return
				}
				item.ActivityId = req.ActivityId
				activityInfo, errInfo := cygx.GetAddActivityInfoById(req.ActivityId)
				if activityInfo == nil {
					br.Msg = "活动不存在"
					br.ErrMsg = "活动ID错误，ActivityId：" + strconv.Itoa(req.ActivityId)
					return
				}
				if errInfo != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "操作失败,Err:" + errInfo.Error()
					return
				}
				if item.PublishStatus == 0 {
					item.PublishStatus = activityInfo.PublishStatus
				}

				if req.DoType == 1 {
					item.AdminId = AdminUser.AdminId
					item.AdminName = AdminUser.RealName
					item.PublishDate = time.Now()
					item.IsCancel = 0
				} else {
					item.AdminId = activityInfo.AdminId
					item.AdminName = activityInfo.AdminName
					item.PublishDate = utils.StrTimeToTime(activityInfo.PublishDate)
				}
				//音频 目前只有一个
				itemVoice := new(cygx.CygxActivityVoice)
				//var itemVoiceList []*cygx.CygxActivityVoice
				var sourceVivo string // 音视频文件类型
				if len(voiceList) > 0 {
					for _, vo := range voiceList {
						itemVoice.ActivityId = activityId
						itemVoice.VoiceName = vo.Name
						itemVoice.VoiceUrl = vo.Url
						itemVoice.VoicePlaySeconds = vo.PlaySeconds
						itemVoice.BackgroundImg = req.BackgroundImg
						itemVoice.ShareImg = req.ShareImg
						itemVoice.CreateTime = time.Now()
						sourceVivo = utils.CYGX_OBJ_ACTIVITYVOICE
					}
				}
				//视频
				itemVideo := new(cygx.CygxActivityVideo)
				if videoDetail != nil {
					itemVideo.VideoName = videoDetail.VideoName
					itemVideo.ActivityId = activityId
					itemVideo.VideoDuration = videoDetail.VideoDuration
					itemVideo.VideoUrl = videoDetail.VideoUrl
					itemVideo.BackgroundImg = req.BackgroundImg
					itemVideo.ShareImg = req.ShareImg
					itemVideo.ModifyDate = time.Now().Format(utils.FormatDateTime)
					itemVideo.CreateTime = time.Now().Format(utils.FormatDateTime)
					sourceVivo = utils.CYGX_OBJ_ACTIVITYVIDEO
				}
				//删除原有的视频数据
				//if itemVideo.VideoUrl != "" {
				//videoDetail, err := cygx.GetCygxActivityVideoReqDetail(activityId)
				//if err != nil && err.Error() != utils.ErrNoRow() {
				//	br.Msg = "获取信息失败"
				//	br.ErrMsg = "GetCygxActivityVideoReqDetail，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
				//	return
				//}
				//if videoDetail != nil {
				//	go cygxService.UpdateResourceData(videoDetail.VideoId, "activityvideo", "delete", time.Now().Format(utils.FormatDateTime))
				//}
				//}
				//处理音视频上传
				err = cygxService.UpdateActivityVideoAndVoice(activityInfo, itemVoice, itemVideo)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取信息失败"
					br.ErrMsg = "UpdateActivityVideoAndVoice，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
					return
				}

				err = cygxService.UpdateActivityVivoPointsSet(activityInfo, vivoPointsSet, itemPointsSet, sourceVivo)
				if err != nil {
					br.Msg = "获取信息失败"
					br.ErrMsg = "UpdateActivityVideoAndVoice，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
					return
				}
				//if itemVoice.VoiceUrl != "" {
				//voiceReqList, err := cygx.GetCygxActivityVoiceReqList(activityId)
				//if err != nil && err.Error() != utils.ErrNoRow() {
				//	br.Msg = "获取信息失败"
				//	br.ErrMsg = "GetCygxActivityVoiceReqList，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
				//	return
				//}
				//if len(voiceReqList) > 0 {
				//	for _, voice := range voiceReqList {
				//		go cygxService.UpdateResourceData(voice.ActivityVoiceId, "activityvoice", "delete", time.Now().Format(utils.FormatDateTime))
				//	}
				//}
				//}
				//如果活动信息有如下变更则做消息推送
				err = cygx.EditActivity(item, activityInfo.PublishStatus, industrialActivityItemsList, subjectActivityItemsList, itemPointsSet)
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "操作失败,Err:" + err.Error()
					return
				}
				////更新活动音频
				//if int(voiceIdNew) > 0 {
				//	go cygxService.UpdateResourceData(int(voiceIdNew), "activityvoice", "add", activityInfo.ActivityTime)
				//}
				////更新活动视频
				//if int(videoIdNew) > 0 {
				//	go cygxService.UpdateResourceData(int(videoIdNew), "activityvideo", "add", activityInfo.ActivityTime)
				//}

				errAct = err
				if activityInfo.PublishStatus == 1 && activityInfo.ActivityTimeText != item.ActivityTimeText {
					go services.SendWxMsgWithCygxActivityUpdateTime(req.ActivityId, activityInfo.ActivityTimeText, item.ActivityTimeText, "timeType")
					if activityInfo.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
						activityTime, err := time.Parse(utils.FormatDateTime, item.ActivityTime)
						if err != nil {
							br.Msg = "转换失败"
							br.ErrMsg = "转换失败,Err:" + err.Error()
							return
						}
						activityTimeStr := activityTime.Format(utils.FormatDateTimeMinute2)
						go services.SendWxCategoryMsgWithCygxActivityUpdateTime(req.ActivityId, activityInfo.ActivityTimeText, activityTimeStr, "timeType")
					}
				}
				oldExpert, _ := cygx.GetReportContentTextSub(activityInfo.Expert)
				newExpert, _ := cygx.GetReportContentTextSub(item.Expert)
				if activityInfo.PublishStatus == 1 && oldExpert != newExpert {
					go services.SendWxMsgWithCygxActivityUpdateTime(req.ActivityId, oldExpert, newExpert, "expertType")
					if activityInfo.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
						go services.SendWxCategoryMsgWithCygxActivityUpdateTime(req.ActivityId, activityInfo.ActivityTimeText, newExpert, "expertType")
					}
				}
				if activityInfo.PublishStatus == 1 && activityInfo.Address != item.Address {
					go services.SendWxMsgWithCygxActivityUpdateTime(req.ActivityId, activityInfo.Address, item.Address, "addressType")
					if activityInfo.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
						go services.SendWxCategoryMsgWithCygxActivityUpdateTime(req.ActivityId, activityInfo.ActivityTimeText, item.Address, "addressType")
					}
				}
				if activityInfo.PublishStatus == 1 && activityInfo.ParticipationCode != item.ParticipationCode {
					go services.SendWxMsgWithCygxActivityUpdateTime(req.ActivityId, activityInfo.ParticipationCode, item.ParticipationCode, "participationCode")
					if activityInfo.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
						go services.SendWxCategoryMsgWithCygxActivityUpdateTime(req.ActivityId, activityInfo.ActivityTimeText, item.ParticipationCode, "participationCode")
					}
				}

				if activityInfo.PublishStatus == 1 && activityInfo.Theme != item.Theme {
					go services.SendWxMsgWithCygxActivityUpdateTime(req.ActivityId, activityInfo.Theme, item.Theme, "Theme")
					if activityInfo.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
						go services.SendWxCategoryMsgWithCygxActivityUpdateTime(req.ActivityId, activityInfo.ActivityTimeText, item.Theme, "Theme")
					}
				}

				//对于限制人数的活动，如果修改改了可见范围，对于新增的那一部分做新的推送
				if req.DoType == 0 && activityInfo.PublishStatus == 1 && activityInfo.ActiveState == 1 && activityInfo.LimitPeopleNum != "0" {
					if activityInfo.CustomerTypeIds != req.CustomerTypeIds || activityInfo.Scale != req.Scale || activityInfo.IsMakerShow != req.IsMakerShow || activityInfo.VisibleRange != req.VisibleRange {
						go cygxService.DoActivityOnenIdWxTemplateMsg(activityId)
					}
				}
				//已结束或者进行中的活动修改时间后，修改活动状态以及重新发送邮件附件
				if activeState != 0 && activeState != 1 {
					resultTime := utils.StrTimeToTime(item.ActivityTime) //时间字符串格式转时间格式
					if time.Now().Before(resultTime) {
						err := cygx.EditActivityStatus(req.ActivityId)
						if err != nil {
							br.Msg = "发布失败"
							br.ErrMsg = "发布失败,Err:" + err.Error()
							return
						}
					}
				}
				//修改活动人数限制之后，对于因为人数已满而失败的用户，推送模板消息
				if activityInfo.PublishStatus == 1 && activityInfo.IsLimitPeople != 0 && activityInfo.LimitPeopleNum != strconv.Itoa(req.LimitPeopleNum) {
					go cygxService.SendWxMsgWithCygxActivityUpdateLimitPeople(req.ActivityId)
					if activityInfo.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
						go services.SendWxCategoryMsgWithCygxActivityUpdateLimitPeople(activityId)
					}
				}
				go cygxService.YiDongSaveRoadshowDetail(activityId)

				//如果活动名称有变更就生成新的签到码
				if activityInfo.ActivityName != item.ActivityName || activityInfo.SigninImg == "" {
					go cygxService.MakeActivitySigninImg(req.ActivityId)
				}
				//如果活动之前是发布的状态，那么就对公司的扣点进行更新（涉及到新老公司的扣点返点，不放在Redis统一处理了）
				if activityInfo.PublishStatus == 1 {
					go cygxService.UpdateYanXuanActivityPointsBillOldComapny(activityInfo, AdminUser.AdminId, itemPointsSet, itemPointsSetOld) //活动发布以及取消发布处理研选扣点
				}

				//如果活动之前是未发布的状态，现在又发布了那么就对公司的扣点进行更新
				//if req.DoType == 1 && activityInfo.PublishStatus == 0 {
				//	go cygxService.YanXuanActivityPointsBillActivityPublishAndCancel(activityId, AdminUser.AdminId, 1) //活动发布以及取消发布处理研选扣点
				//}
			}
			if errAct != nil {
				br.Msg = "发布失败"
				br.ErrMsg = "发布失败,Err:" + errAct.Error()
				return
			}

			//go cygxService.YanXuanActivityPointsBillActivityEdit(activityId, AdminUser.AdminId) //活动编辑处理研选扣点
		}
	}
	if req.ActivityId == 0 {
		_, activityIdArr, err := cygx.AddActivity(items, industrialActivityItemsList, subjectActivityItemsList, itemPointsSet)
		if err != nil {
			br.Msg = "发布失败"
			br.ErrMsg = "发布失败,Err:" + err.Error()
			return
		}
		//如果是添加多条活动那么就推送多次
		for _, v := range activityIdArr {
			if req.DoType == 1 {
				//go func() {
				//同时添加多个活动的时候，避免协程开的过多
				go cygxService.DoActivityOnenIdWxTemplateMsg(v)
				//cygxService.UpdateResourceData(v, "activity", "add", time.Now().Format(utils.FormatDateTime))
				go cygxService.UpdateActivityResourceData(v) //写入首页最新  cygx_resource_data 表
				go cygxService.YiDongSaveRoadshowDetail(v)
				go cygxService.YanXuanActivityPointsBillActivityPublishAndCancel(v, AdminUser.AdminId, 1) //活动发布以及取消发布处理研选扣
				go elastic.AddComprehensiveActivity(v)
				go cygxService.MakeActivityMomentsImg(v) //生成活动分享到朋友圈的图片
				//}()
			}
			go cygxService.MakeActivitySigninImg(v)
		}
	} else {
		if req.DoType == 1 {
			go cygxService.DoActivityOnenIdWxTemplateMsg(req.ActivityId)
			//go cygxService.UpdateResourceData(req.ActivityId, "activity", "add", time.Now().Format(utils.FormatDateTime))
			go cygxService.YanXuanActivityPointsBillActivityPublishAndCancel(activityId, AdminUser.AdminId, 1) //活动发布以及取消发布处理研选扣点
		}
		cygxService.UpdateActivityResourceData(req.ActivityId) //写入首页最新  cygx_resource_data 表
		go cygxService.MakeActivityMomentsImg(req.ActivityId)  //生成活动分享到朋友圈的图片
		//如果二次编辑的时候，取消了易董办会选项，那么就对易董发送取消发布到广场的通知
		if req.IsYidongConduct == 0 {
			go cygxService.YiDongUpdateActivityStatus(activityId)
		}
	}
	// 查研观向7.4-更新产业布局时间
	if len(industryIds) > 0 {
		go cygxService.UpdateIndustryLayoutTime(industryIds, false)
	}
	//添加操作日志记录
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 活动列表
// @Description 获取活动列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   PublishStatus   query   int  false       "发布状态 ，0未发布，1已发布，3已取消，传2查询所有"
// @Param   ChartPermissionId   query   string  false     "行业id"
// @Param   ActivityTypeId   query   string  false     "活动类型id"
// @Param   StartDate   query   string  false       "开始时间 ，列如2021-03-06 "
// @Param   EndDate   query   string  false       "结束时间，列如2021-03-06 "
// @Param   PublishStartDate   query   string  false       "发布开始时间 ，列如2021-03-06 "
// @Param   PublishEndDate   query   string  false       "发布结束时间，列如2021-03-06 "
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   ActiveState   query   string  false       "活动进行状态 未开始：NotStarted、进行中HaveInHand、已结束Complete"
// @Param   IsResearch   query   bool  true       "是否为研选"
// @Success 200 {object} cygx.GetCygxActivityListRep
// @router /activity/list [get]
func (this *ActivityCoAntroller) ActivityList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	publishStatus, _ := this.GetInt("PublishStatus")
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	ActivityTypeId, _ := this.GetInt("ActivityTypeId")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	publishStartDate := this.GetString("PublishStartDate")
	publishEndDate := this.GetString("PublishEndDate")
	keyWord := this.GetString("KeyWord")
	activeState := this.GetString("ActiveState")
	activityLabel := this.GetString("ActivityLabel")   // 查研观向7.4-活动标签
	isResearch, _ := this.GetBool("IsResearch", false) // 是否为研选 查研观向11.0 （研选活动独立显示）
	if activeState != "HaveInHand" && activeState != "Complete" {
		activeState = "NotStarted"
	}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}
	//condition += ` FROM cygx_activity as art WHERE 1= 1 `
	if keyWord != "" {
		condition += ` AND (art.activity_name LIKE '%` + keyWord + `%' )  `
	}
	if isResearch {
		chartPermissionId = utils.CHART_PERMISSION_ID_YANXUAN
	} else {
		condition += ` AND art.chart_permission_id  !=  '` + strconv.Itoa(utils.CHART_PERMISSION_ID_YANXUAN) + `'`
	}
	//行业名称
	if chartPermissionId > 0 {
		condition += ` AND art.chart_permission_id  =  '` + strconv.Itoa(chartPermissionId) + `'`
	}

	if startDate != "" {
		condition += ` AND art.activity_time >= ` + "'" + startDate + " 00:00:00'"
	}
	if endDate != "" {
		condition += ` AND art.activity_time <= ` + "'" + endDate + " 23:59:59'"
	}

	//发布时间状态的筛选
	if publishStartDate != "" {
		condition += ` AND art.publish_date >= ` + "'" + publishStartDate + " 00:00:00'"
		publishStatus = 1
	}
	if publishEndDate != "" {
		condition += ` AND art.publish_date <= ` + "'" + publishEndDate + " 23:59:59'"
		publishStatus = 1
	}
	if publishStatus == 0 {
		condition += ` AND art.publish_status = 0 AND  art.is_cancel = 0 `
	} else if publishStatus == 1 {
		condition += ` AND art.publish_status =  1 `
	} else if publishStatus == 3 {
		condition += ` AND art.publish_status = 0 AND  art.is_cancel = 1 `
	}
	if ActivityTypeId > 0 {
		condition += ` AND art.activity_type_id  =  '` + strconv.Itoa(ActivityTypeId) + `'`
	}
	if activeState == "NotStarted" {
		condition += ` AND art.active_state  =1 `
	} else if activeState == "HaveInHand" {
		condition += ` AND art.active_state  =2 `
	} else {
		condition += ` AND art.active_state  =3 `
	}
	// 活动标签
	if activityLabel != "" {
		condition += ` AND (art.label LIKE '%` + activityLabel + `%' )  `
	}

	//本组可见的活动对，非产品技术部 做权限限制
	if sysUser.DepartmentId != 3 {
		conditionPermission, err := cygxService.GetAdminActivityPermission(sysUser, condition)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetAdminActivityPermission Err:" + err.Error()
			return
		}
		condition += ` AND art.visible_range != 1  `
		condition += conditionPermission
		pars = append(pars, pars)
	}
	//1专家电话会、2分析师电话会、3公司调研电话会、4公司线下调研、5专家线下沙龙、6分析师线下沙龙
	total, err := cygx.GetActivityCount(condition, pars)

	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if activeState == "NotStarted" {
		condition += ` ORDER BY art.top_time DESC , art.activity_time ASC `
	} else {
		condition += ` ORDER BY art.activity_time DESC `
	}
	list, errList := cygx.GetActivityListAll(condition, pars, startSize, pageSize)
	if errList != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errList.Error()
		return
	}
	var activityIds string
	for k, v := range list {
		if v.ChartPermissionNames != "" {
			list[k].ChartPermissionName = v.ChartPermissionNames
		}
		if v.IsCancel == 1 {
			v.PublishStatus = 3
		}
		activityIds += strconv.Itoa(v.ActivityId) + ","
	}
	activityIds = strings.TrimRight(activityIds, ",")
	mapIndustrial := make(map[int]string)
	mapSubject := make(map[string]string)
	mapUpload := make(map[int]bool)
	if activityIds != "" {
		industrialList, err := cygx.GetIndustrialActivityGroupListByactivityIds(activityIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetIndustrialActivityGroupListByactivityIds Err:" + err.Error()
			return
		}
		subjectList, err := cygx.GetSubjectActivityGroupListByactivityIds(activityIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetSubjectActivityGroupListByactivityIds Err:" + err.Error()
			return
		}
		//合并活动对应的多个标的
		for _, v := range subjectList {
			mapSubject[fmt.Sprint(v.ActivityId, "_", v.IndustrialManagementId)] += v.SubjectName + "/"
		}
		//活动对应的产业
		for _, v := range industrialList {
			var labelSubject string
			labelSubject = mapSubject[fmt.Sprint(v.ActivityId, "_", v.IndustrialManagementId)]
			if labelSubject != "" {
				mapIndustrial[v.ActivityId] += v.IndustryName + "--" + strings.TrimRight(labelSubject, "/") + "，"
			} else {
				mapIndustrial[v.ActivityId] += v.IndustryName + "，"
			}
		}
		var conditionupload string
		var pars []interface{}
		conditionupload = " AND activity_id IN (" + activityIds + ")  "
		listVideo, err := cygx.GetActivityVideoList(conditionupload, pars)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		if len(listVideo) > 0 {
			for _, v := range listVideo {
				mapUpload[v.ActivityId] = true
			}
		}

		listVoice, err := cygx.GetActivityVoiceList(conditionupload, pars)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		if len(listVoice) > 0 {
			for _, v := range listVoice {
				mapUpload[v.ActivityId] = true
			}
		}

	}
	for k, v := range list {
		if mapIndustrial[v.ActivityId] != "" && v.TemporaryLabel == "" {
			list[k].Label = strings.TrimRight(mapIndustrial[v.ActivityId], "，")
		}
		if v.YidongActivityId != "" {
			list[k].ActivityTypeName += utils.YI_DONG_NAME
			if v.ChartPermissionNameDeputy != "" && v.ChartPermissionNameDeputy != v.ChartPermissionName {
				v.ChartPermissionName = v.ChartPermissionNameDeputy // 易董同步过来的活动展示副权限  v11.0
			}
		}
		if v.IsYidongConduct == 1 {
			list[k].ActivityTypeName += utils.YI_DONG_NAME_TWO
		}
		list[k].IsUpload = mapUpload[v.ActivityId]
		//是否展示签到码
		if (v.ActivityTypeId == 5 || v.ActivityTypeId == 6 || v.ActivityTypeId == 8) && v.SigninImg != "" && v.ActiveState == 1 && v.PublishStatus == 1 {
			list[k].IsShowSigninButton = true
		}
	}
	if len(list) == 0 {
		list = make([]*cygx.CygxActivityList, 0)
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.GetCygxActivityListRep)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  活动详情
// @Description 获取活动详情接口
// @Param   ActivityId   query   int  true       "活动ID"
// @Success Ret=200 {object} cygx.ActivityDetail
// @router /activity/detail [get]
func (this *ActivityCoAntroller) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	activityId, _ := this.GetInt("ActivityId")
	if activityId < 1 {
		br.Msg = "请输入活动ID"
		return
	}
	activityInfo, err := cygx.GetAddActivityInfoById(activityId)
	if err != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
		return
	}

	detail, errDetail := cygx.GetActivityTypeDetailById(activityInfo.ActivityTypeId)
	if errDetail != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + errDetail.Error()
		return
	}
	industrialList, err := cygx.GetIndustrialActivityGroupManagementList(activityId, 1)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取活动关联的产业列表信息失败，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
		return
	}
	var subjectList []*cygx.SubjectActivityGroupManagementRep
	if len(industrialList) > 0 {
		subjectList, err = cygx.GetSubjectActivityGroupManagementList(activityId, 1)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取活动关联的标的列表信息失败，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
			return
		}
	}

	VoiceReqList, err := cygx.GetCygxActivityVoiceReqList(activityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "GetCygxActivityVoiceReqList，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
		return
	}
	if len(VoiceReqList) == 0 {
		VoiceReqList = make([]*cygx.CygxActivityVoiceReq, 0)
	} else {
		for _, v := range VoiceReqList {
			activityInfo.BackgroundImg = v.BackgroundImg
			activityInfo.ShareImg = v.ShareImg
		}
	}
	VideoDetail, err := cygx.GetCygxActivityVideoReqDetail(activityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "GetCygxActivityVideoReqDetail，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
		return
	}
	if VideoDetail != nil {
		activityInfo.BackgroundImg = VideoDetail.BackgroundImg
		activityInfo.ShareImg = VideoDetail.ShareImg
	}

	totalVivo, err := cygx.GetCygxActivityVivoPointsSetCountByActivityId(activityId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "GetCygxActivityVivoPointsSetCountByActivityId，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
	}

	if totalVivo > 0 {
		vivoPointsSetDetail, err := cygx.GetCygxActivityVivoPointsSetByActivityId(activityId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取信息失败,Err:" + err.Error()
			return
		}
		vivoPointsSetDetail.IsPay = 1
		activityInfo.VivoPointsSet = *vivoPointsSetDetail
	}

	if activityInfo.CustomerTypeIds != "" {
		customerTypeIdslist := strings.Split(activityInfo.CustomerTypeIds, ",")
		var permissionValueStr string
		for _, v := range customerTypeIdslist {
			permissionValueStr += "'" + v + "',"
		}
		permissionValueStr = strings.TrimRight(permissionValueStr, ",")
		condition := ` AND  permission_value IN  (` + permissionValueStr + `)`
		listValue, err := cygx.GetActivityCcustomerTypeList(condition)
		if err != nil {
			br.Msg = "活动可见套餐类型错误，请核实"
			br.ErrMsg = "GetActivityCcustomerTypeList，Err:" + err.Error()
			return
		}
		activityInfo.CustomerTypeIds = ""
		for _, v := range listValue {
			activityInfo.CustomerTypeIds += strconv.Itoa(v.CustomerTypeId) + ","
		}
		activityInfo.CustomerTypeIds = strings.TrimRight(activityInfo.CustomerTypeIds, ",")
	}

	if activityInfo.SiginupDeadline == utils.EmptyDateTimeStr {
		activityInfo.SiginupDeadline = ""
	}
	PointsSetDetail, err := cygx.GetCygxActivityPointsSetDetail(activityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "GetCygxActivityPointsSetDetail，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
		return
	}
	if PointsSetDetail != nil {
		if PointsSetDetail.CancelDeadlineType == "0" {
			PointsSetDetail.CancelDeadlineType = ""
		}
		activityInfo.PointsSet = PointsSetDetail
	} else {
		activityInfo.PointsSet = new(cygx.CygxActivityPointsSetRsq)
	}
	//可见范围 1，仅本组可见 、2，全部客户可见 没设置本组可见的，强制设置为全部客户可见
	if activityInfo.VisibleRange == 0 {
		activityInfo.VisibleRange = 2
	}

	////如果是已结束的活动，而且封面图片为空，那么就给一个默认的图片
	//if activityInfo.ActiveState == 3 && activityInfo.BackgroundImg == "" {
	//	// 获取默认图配置 目前音频视频用的是同一个封面图，暂时不做区分处理
	//	audioMap, _, audioShareMap, _, err := cygxService.GetMicroRoadShowDefaultImgConfig()
	//	if err != nil && err.Error() != utils.ErrNoRow() {
	//		br.Msg = "获取信息失败"
	//		br.ErrMsg = "GetMicroRoadShowDefaultImgConfig，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
	//		return
	//	}
	//	activityInfo.BackgroundImg = audioMap[activityInfo.ChartPermissionId]
	//	activityInfo.ShareImg = audioShareMap[activityInfo.ChartPermissionId]
	//}

	//activityInfo.CancelDeadlineType = cygxService.ActivityCancelDeadlineType(activityInfo) //处理活动取消报名截止时间类型展示
	activityInfo.VoiceList = VoiceReqList
	activityInfo.VideoDetail = VideoDetail
	activityInfo.ShowType = detail.ShowType
	activityInfo.ListIndustrial = industrialList
	activityInfo.ListSubject = subjectList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = activityInfo
}

// @Title 活动的发布与取消发布
// @Description 活动的发布与取消发布接口
// @Param	request	body cygx.ActivityIdRep true "type json string"
// @Success 200 操作成功
// @router /activity/PublishAndCancel [post]
func (this *ActivityCoAntroller) PublishAndCancel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.ActivityIdRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	activityId := req.ActivityId
	item := new(cygx.CygxActivity)
	activityInfo, errInfo := cygx.GetAddActivityInfoById(activityId)
	if activityInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "活动ID错误,不存在activityId：" + strconv.Itoa(activityId)
		return
	}
	if errInfo != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + errInfo.Error()
		return
	}
	//校验活动后台管理员、销售是否有修改权限
	havePower, popupMsg, err := cygxService.CheckActivityUpdatePower(AdminUser.AdminId, activityInfo)
	if err != nil {
		br.Msg = "获取管理员身份信息失败"
		br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
		return
	}
	if !havePower {
		br.Msg = popupMsg
		return
	}
	//if activityInfo.ActiveState != 1 {
	//	br.Msg = "活动已经开始，无法修改"
	//	return
	//}
	if activityInfo.PublishStatus == 0 {
		item.PublishStatus = 1
		item.IsCancel = 0
		go cygxService.DoActivityOnenIdWxTemplateMsg(activityId)
		//go cygxService.UpdateResourceData(activityId, "activity", "add", time.Now().Format(utils.FormatDateTime))

	} else {
		item.PublishStatus = 0
		item.IsCancel = 1
	}
	if activityInfo.PublishStatus == 1 {
		go services.SendWxMsgWithCygxActivity(req.ActivityId)
		//同步活动到最新数据表
		//go cygxService.UpdateResourceData(req.ActivityId, "activity", "delete", "")
		if activityInfo.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
			go services.SendWxCategoryMsgWithCygxActivity(req.ActivityId)
		}
	}
	item.ActivityId = req.ActivityId
	if item.PublishStatus == 1 {
		item.AdminId = AdminUser.AdminId
		item.AdminName = AdminUser.RealName
		item.PublishDate = time.Now()

	} else {
		item.AdminId = activityInfo.AdminId
		item.AdminName = activityInfo.AdminName
		item.PublishDate = utils.StrTimeToTime(activityInfo.PublishDate)
	}
	err = cygx.ActivityPublishAndCancel(item)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	if item.PublishStatus == 1 {
		//易董那边重新发布，重新建会
		go cygxService.YiDongSaveRoadshowDetail(activityId)
	} else {
		//易董那边取消发布并删除
		go cygxService.YiDongUpdateActivityPublish(activityId)
	}
	go cygxService.YanXuanActivityPointsBillActivityPublishAndCancel(activityId, AdminUser.AdminId, item.PublishStatus) //活动发布以及取消发布处理研选扣点
	go elastic.AddComprehensiveActivity(activityId)                                                                     // 同步Es添加活动
	go cygxService.UpdateActivityResourceData(activityId)                                                               //写入首页最新  cygx_resource_data 表
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true //添加操作日志记录
}

// @Title 删除活动
// @Description 删除活动接口
// @Param   request	body cygx.ActivityIdRep true "type json string"
// @Success Ret=200
// @router /activity/delete [post]
func (this *ActivityCoAntroller) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.ActivityIdRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	activityId := req.ActivityId
	if activityId < 1 {
		br.Msg = "请输入活动ID"
		return
	}
	activityInfo, errInfo := cygx.GetAddActivityInfoById(activityId)
	if activityInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "活动ID错误,不存在activityId：" + strconv.Itoa(activityId)
		return
	}
	if errInfo != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + errInfo.Error()
		return
	}
	//校验活动后台管理员、销售是否有修改权限
	havePower, popupMsg, err := cygxService.CheckActivityUpdatePower(AdminUser.AdminId, activityInfo)
	if err != nil {
		br.Msg = "获取管理员身份信息失败"
		br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
		return
	}
	if !havePower {
		br.Msg = popupMsg
		return
	}
	resultTime := utils.StrTimeToTime(activityInfo.ActivityTime) //时间字符串格式转时间格式
	res := time.Now().Before(resultTime)
	if res == false {
		br.Msg = "活动已结束禁止删除！"
		br.ErrMsg = "活动已结束禁止删除！"
		return
	}
	err = cygx.DeleteActivity(activityId)
	if err != nil {
		br.Msg = "删除信息失败"
		br.ErrMsg = "删除信息失败,Err:" + err.Error()
		return
	}
	//添加操作日志记录

	br.Ret = 200
	br.Success = true
	br.Msg = "已删除"
	br.IsAddLog = true
}

// @Title 获取活动行业分类
// @Description 获取活动行业分类接口
// @Param   IsHideResearch  query  bool  false  "是否隐藏买方研选(默认不隐藏)"
// @Success 200 {object} cygx.ChartPermissionRepMoreList
// @router /activity/chartPermission/list [get]
func (this *ActivityCoAntroller) ChartPermissionListAct() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}

	resp := new(cygx.ChartPermissionResp)
	list, err := cygx.GetChartPermissionAll()
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}

	for _, v := range list {
		if v.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN || v.PermissionName == utils.YAN_XUAN_KOU_DIAN_BAO_NAME {
			continue
		}
		resp.List = append(resp.List, v)
	}

	// 查研观向7.4-新增一个宏观
	macro := &cygx.ChartPermission{
		ChartPermissionId: 1,
		PermissionName:    "宏观",
	}
	resp.List = append(resp.List, macro)

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 扣点设置
// @Description 扣点设置接口
// @Success 200 {object} cygx.CygxActivityPointsSetConfigListResp
// @router /activity/pointsSet [get]
func (this *ActivityCoAntroller) PointsSet() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	conf, err := cygx.GetCygxConfigDetailByCode("activity_points_set")
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "买方研选产品介绍信息失败，Err:" + err.Error()
		return
	}
	if conf.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "买方研选产品介绍信息失败"
		return
	}
	list := new(*cygx.CygxActivityPointsSetConfigListResp)
	if err = json.Unmarshal([]byte(conf.ConfigValue), &list); err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "买方研选产品介绍信配置值解析失败, Err: " + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 权益办会机构搜索
// @Description 权益办会机构搜索
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success 200 {object} cygx.ChartPermissionRepMoreList
// @router /activity/companySearch [get]
func (this *ActivityCoAntroller) CompanySearch() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	keyWord := this.GetString("KeyWord")
	if keyWord == "" {
		br.ErrMsg = "请输入搜索关键词"
		return
	}
	resp := new(cygx.CygxActivitySearcCompanyListResp)
	list, err := cygx.GetCygxActivitySearcCompanyList(keyWord)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	if len(list) == 0 {
		list = make([]*cygx.CygxActivitySearcCompanyResp, 0)
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 报名截止时间设置
// @Description 报名截止时间设置接口
// @Success Ret=200
// @router /activity/deadlineSet [get]
func (this *ActivityCoAntroller) DeadlineSet() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	list := make([]cygx.SendGroupStr, 0)
	list = append(list, cygx.SendGroupStr{
		Id:   "1",
		Name: "同报名截止时间",
	})
	list = append(list, cygx.SendGroupStr{
		Id:   "2",
		Name: "活动开始前24小时",
	})
	list = append(list, cygx.SendGroupStr{
		Id:   "3",
		Name: "活动开始前48小时",
	})
	br.Ret = 200
	br.Success = true
	br.Data = list
}

// @Title 根据图片获取建会信息接口
// @Description 根据图片获取建会信息接口
// @Param   request	body cygx.ActivityIdRep true "type json string"
// @Success Ret=200
// @router /activity/imgToText [post]
func (this *ActivityCoAntroller) ImgToText() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.AliyunOcrImgUrlReq
	resp := new(cygx.AliyunOcrTextActivityListResp)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	imgUrl := req.ImgUrl
	if imgUrl == "" {
		br.Msg = "请上传图片"
		return
	}

	ocrResp, err := services.AliOcrByImageToText(imgUrl)
	if err != nil {
		br.Msg = "图片解析失败！"
		br.ErrMsg = "图片解析失败，Err:" + err.Error()
		return
	}
	if len(ocrResp.Ret) == 0 {
		br.Msg = "图片解析失败！"
		return
	}

	var titmeYMD string
	var titmeHM string
	var company string
	var list []*cygx.AliyunOcrTextActivityResp
	var mapTitmeYMD = make(map[int]string)
	var mapTitmeHM = make(map[int]string)
	var mapCompany = make(map[int]string)
	var lineNum int
	for k, v := range ocrResp.Ret {
		if k == 0 && !strings.Contains(v.Word, "/") {
			continue
		}
		if strings.Contains(v.Word, "/") && !strings.Contains(v.Word, "(") && !strings.Contains(v.Word, ")") {
			mapTitmeYMD[lineNum] = v.Word
			titmeYMD = v.Word
		}
		if strings.Contains(v.Word, "AM") || strings.Contains(v.Word, "PM") {
			mapTitmeHM[lineNum] = v.Word
			titmeHM = v.Word
		}
		if strings.Contains(v.Word, "(") && !strings.Contains(v.Word, ")") {
			v.Word += ")" // 图片识别的偶尔有问题，兼容一下
		}
		if strings.Contains(v.Word, "(") && strings.Contains(v.Word, ")") {
			if mapTitmeYMD[lineNum] == "" {
				mapTitmeYMD[lineNum] = mapTitmeYMD[lineNum-1]
			}
			titmeYMD = mapTitmeYMD[lineNum]
			mapCompany[lineNum] = v.Word
			company = v.Word
			lineNum++

		}
		if titmeYMD != "" && titmeHM != "" && company != "" {
			item := new(cygx.AliyunOcrTextActivityResp)
			item.TitmeYMD = titmeYMD
			item.TitmeHM = titmeHM
			item.Company = company
			list = append(list, item)
			titmeYMD = ""
			titmeHM = ""
			company = ""
		}
	}

	for _, v := range list {
		v.TitmeYMD = cygxService.ConvertActivityTitmeYMD(v.TitmeYMD)
		v.TitmeHM = cygxService.ConvertActivityTitmeHM(v.TitmeHM)
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Data = resp
	br.IsAddLog = true
}

// @Title 活动的置顶与取消置顶
// @Description 活动的发布与取消发布接口
// @Param	request	body cygx.ActivityIdRep true "type json string"
// @Success 200 操作成功
// @router /activity/tope_change [post]
func (this *ActivityCoAntroller) TopeChange() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.ActivityIdRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	activityId := req.ActivityId
	activityInfo, errInfo := cygx.GetAddActivityInfoById(activityId)
	if activityInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "活动ID错误,不存在activityId：" + strconv.Itoa(activityId)
		return
	}
	if errInfo != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + errInfo.Error()
		return
	}
	//校验活动后台管理员、销售是否有修改权限
	havePower, popupMsg, err := cygxService.CheckActivityUpdatePower(AdminUser.AdminId, activityInfo)
	if err != nil {
		br.Msg = "获取管理员身份信息失败"
		br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
		return
	}
	if !havePower {
		br.Msg = popupMsg
		return
	}
	var topTime int
	//如果有置顶时间就设为取消置顶，如果没有就写入当前置顶时间
	if activityInfo.TopTime == 0 {
		topTime = int(time.Now().Unix())
	}
	err = cygx.UpdateActivityTopTime(activityId, topTime)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true //添加操作日志记录
}
