package cygx

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/services/elastic"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 专项调研
type ActivitySpecialCoAntroller struct {
	controllers.BaseAuthController
}

// @Title 专项调研内容的保存与发布
// @Description 专项调研内容的保存与发布接口
// @Param	request	body cygx.ActivitySpecialRep true "type json string"
// @Success 200 操作成功
// @router /special/PreserveAndPublish [post]
func (this *ActivitySpecialCoAntroller) 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.ActivitySpecialRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	activityId := req.ActivityId
	industrialManagementIdS := req.IndustrialManagementIdS
	industrialSubjectIdS := req.IndustrialSubjectIdS
	temporaryLabel := req.TemporaryLabel
	temporarySubject := req.TemporarySubject
	permissionName := req.PermissionName
	specialType := req.SpecialType
	city := req.City
	isShowSubjectName := req.IsShowSubjectName
	customerTypeIds := req.CustomerTypeIds
	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, ",")
	}
	item := new(cygx.CygxActivitySpecial)
	var industrialActivityItems []*cygx.CygxIndustrialActivityGroupManagement
	var subjectActivityItems []*cygx.CygxIndustrialActivityGroupSubject
	var industrialNames string
	var industrialSubjectNames string

	if specialType != 1 && specialType != 2 {
		br.Msg = "请选择调研形式！"
		return
	}
	if specialType == 2 && city == "" {
		br.Msg = "请输入调研城市！"
		return
	}

	//如果临时标签是空的话，就去关联产业跟标的
	if temporaryLabel == "" {
		if industrialManagementIdS == "" {
			br.Msg = "请选择产业"
			return
		}
		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
			}
			industrialActivityItem.CreateTime = time.Now()
			industrialActivityItem.IndustrialManagementId = industrialManagementId
			industrialActivityItem.ActivityId = activityId
			industrialActivityItem.Source = 2
			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 = 2
				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
			}
			if temporarySubject != "" {
				industrialSubjectNames += "/" + strings.Replace(temporarySubject, ",", "/", -1)
			}
		} else {
			industrialSubjectNames = ""
			if temporarySubject != "" {
				industrialSubjectNames = strings.Replace(temporarySubject, ",", "/", -1)
			}
		}
	} else {
		industrialActivityItems = make([]*cygx.CygxIndustrialActivityGroupManagement, 0)
		subjectActivityItems = make([]*cygx.CygxIndustrialActivityGroupSubject, 0)
	}
	//List := []*cygx.ChartPermissionRepMore{{PermissionName: "医药"}, {PermissionName: "消费"}, {PermissionName: "科技"}, {PermissionName: "智造"}, {PermissionName: "研选"}}
	//var haveCheck bool
	//for _, v := range List {
	//	if permissionName == v.PermissionName {
	//		haveCheck = true
	//	}
	//}
	//if !haveCheck {
	//	br.Msg = "行业名称：" + permissionName + "不存在"
	//	return
	//}
	//if strings.Contains(permissionName, "研选") {
	//	permissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
	//}
	charInfo, errCategory := cygx.GetCategoryInfoByName(permissionName)
	if errCategory != nil {
		br.Msg = "请选择所属行业"
		br.ErrMsg = "获取所属行业信息失败,Err:" + errCategory.Error()
		return
	}
	item.ChartPermissionId = charInfo.ChartPermissionId
	item.ChartPermissionName = req.PermissionName
	item.CustomerTypeIds = req.CustomerTypeIds
	item.PublishStatus = req.DoType
	item.ResearchTheme = req.ResearchTheme
	item.ActivityTimeText = req.ActivityTimeText
	item.TemporaryLabel = req.TemporaryLabel
	item.TemporarySubject = req.TemporarySubject
	//item.Scale = req.Scale
	item.TripImgLink = req.TripImgLink
	item.IndustrialName = industrialNames
	item.IndustrialSubjectName = industrialSubjectNames
	item.SpecialType = specialType
	item.AdminId = AdminUser.AdminId
	item.AdminName = AdminUser.RealName
	if specialType == 1 {
		item.City = ""
	} else {
		item.City = city
	}
	item.IsShowSubjectName = isShowSubjectName
	item.PublishDate = time.Now().Format(utils.FormatDateTime)
	if req.TemporaryLabel != "" {
		item.Label = req.TemporaryLabel
	} else {
		if isShowSubjectName == 1 {
			item.Label = industrialSubjectNames
			if industrialSubjectNames == "" {
				br.Msg = "请选择关联标的"
			}
		} else {
			item.Label = industrialNames
		}
	}
	item.LastUpdatedTime = time.Now()
	item.CreateTime = time.Now()
	if req.ActivityId > 0 {
		activityInfo, errInfo := cygx.GetAddActivityInfoSpecialById(req.ActivityId)
		if errInfo != nil {
			br.Msg = "活动不存在"
			br.ErrMsg = "活动ID错误，ActivityId：" + strconv.Itoa(req.ActivityId)
			return
		}
		//校验活动后台管理员、销售是否有修改权限
		havePower, popupMsg, err := cygxService.CheckActivitySpecialUpdatePower(AdminUser.AdminId, activityInfo)
		if err != nil {
			br.Msg = "获取管理员身份信息失败"
			br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
			return
		}
		if !havePower {
			br.Msg = popupMsg
			return
		}
		item.ActivityId = req.ActivityId
		//如果点发布PublishStatus = 1 如果点保存，PublishStatus则为之前的状态 发布人还是之前的发布人
		if item.PublishStatus == 0 {
			item.PublishStatus = activityInfo.PublishStatus
		}

		updateParams := make(map[string]interface{})
		updateParams["ChartPermissionId"] = item.ChartPermissionId
		updateParams["ChartPermissionName"] = item.ChartPermissionName
		updateParams["CustomerTypeIds"] = item.CustomerTypeIds
		updateParams["PublishStatus"] = item.PublishStatus
		updateParams["ResearchTheme"] = item.ResearchTheme
		updateParams["ActivityTimeText"] = item.ActivityTimeText
		updateParams["Label"] = item.Label
		updateParams["TemporaryLabel"] = item.TemporaryLabel
		updateParams["TemporarySubject"] = item.TemporarySubject
		//updateParams["Scale"] = item.Scale
		updateParams["TripImgLink"] = item.TripImgLink
		updateParams["IndustrialName"] = item.IndustrialName
		updateParams["IndustrialSubjectName"] = item.IndustrialSubjectName
		updateParams["LastUpdatedTime"] = time.Now()
		updateParams["SpecialType"] = item.SpecialType
		updateParams["City"] = item.City
		updateParams["IsShowSubjectName"] = item.IsShowSubjectName
		if req.DoType == 1 {
			updateParams["IsOffline"] = 0
			updateParams["PublishDate"] = time.Now()
		}
		err = cygx.EditActivitySpecial(updateParams, item, industrialActivityItems, subjectActivityItems)
		if err != nil {
			br.Msg = "发布失败"
			br.ErrMsg = "发布失败,Err:" + err.Error()
			return
		}
	} else {
		newId, err := cygx.AddActivitySpecial(item, industrialActivityItems, subjectActivityItems)
		if err != nil {
			br.Msg = "发布失败"
			br.ErrMsg = "发布失败,Err:" + err.Error()
			return
		}
		activityId = int(newId)
	}
	//模板消息推送
	if req.DoType == 1 {
		go services.SendWxMsgWithCygxActivitySpecial(activityId)
		//go cygxService.UpdateResourceData(activityId, "activityspecial", "add", time.Now().Format(utils.FormatDateTime))
	}
	go cygxService.UpdateActivitySpecialResourceData(activityId) //写入首页最新  cygx_resource_data 表
	go elastic.AddComprehensiveActivitySpecial(activityId)       // Es添加活动
	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已发布，传2查询所有，3已下线，4：已确定行程"
// @Param   ChartPermissionId   query   string  false     "行业id"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   IsTrip   query   bool  false       "是否是确定行程"
// @Success 200 {object} cygx.GetCygxActivityListSpecialRep
// @router /special/list [get]
func (this *ActivitySpecialCoAntroller) 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")
	keyWord := this.GetString("KeyWord")
	isTrip, _ := this.GetBool("IsTrip", false)
	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{}
	if keyWord != "" {
		condition += ` AND (art.research_theme LIKE '%` + keyWord + `%' )  `
	}
	//行业名称
	if chartPermissionId > 0 {
		condition += ` AND art.chart_permission_id  =  '` + strconv.Itoa(chartPermissionId) + `'`
	}
	if isTrip {
		if publishStatus == 0 || publishStatus == 1 {
			condition += ` AND art.publish_status = ` + strconv.Itoa(publishStatus)
		}
	} else {
		if publishStatus == 0 {
			condition += ` AND art.days = 0  AND art.publish_status = 0 AND  art.is_offline =0 `
		}
		if publishStatus == 1 {
			condition += ` AND art.days = 0   AND art.publish_status = 1 `
		}
	}

	if publishStatus == 3 {
		condition += ` AND art.is_offline =1 `
	}
	if publishStatus == 4 || isTrip {
		condition += ` AND art.days > 0  `
	}

	total, err := cygx.GetActivitySpecialCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if isTrip {
		condition += ` ORDER BY art.activity_time DESC `
	} else {
		condition += ` ORDER BY art.last_updated_time DESC `
	}

	list, errList := cygx.GetActivityListSpecialAll(condition, pars, startSize, pageSize)
	if errList != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errList.Error()
		return
	}
	list = cygxService.HandleActivityListSpecial(list, isTrip)
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.GetCygxActivityListSpecialRep)
	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.ActivitySpecialDetail
// @router /special/detail [get]
func (this *ActivitySpecialCoAntroller) 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.GetAddActivityInfoSpecialById(activityId)
	if err != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，ActivityId：" + strconv.Itoa(activityId)
		return
	}
	industrialList, err := cygx.GetIndustrialActivityGroupManagementList(activityId, 2)
	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, 2)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取活动关联的标的列表信息失败，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
			return
		}
	}
	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, ",")

		nameStr, err := cygx.GetCustomerName(activityInfo.CustomerTypeIds)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取用户可见范围失败,Err:" + err.Error()
			return
		}
		activityInfo.CustomerName = nameStr
	}
	dateYmdList, err := cygxService.GetCygxActivitySpecialDay(activityId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = " 处理时间格式失败，GetCygxActivitySpecialDay，Err:" + err.Error()
		return
	}
	activityInfo.ListIndustrial = industrialList
	activityInfo.ListSubject = subjectList
	activityInfo.DateYmdList = dateYmdList
	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 /special/PublishAndCancel [post]
func (this *ActivitySpecialCoAntroller) 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.CygxActivitySpecial)
	activityInfo, errInfo := cygx.GetAddActivityInfoSpecialById(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.CheckActivitySpecialUpdatePower(AdminUser.AdminId, activityInfo)
	if err != nil {
		br.Msg = "获取管理员身份信息失败"
		br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
		return
	}
	if !havePower {
		br.Msg = popupMsg
		return
	}
	updateParams := make(map[string]interface{})
	if activityInfo.PublishStatus == 0 {
		item.PublishStatus = 1
		updateParams["PublishDate"] = time.Now()
	} else {
		item.PublishStatus = 0
		// 取消专项调研返点
		//go cygxService.ActivitySpecialPublishAndCancel(activityInfo)
	}
	updateParams["PublishStatus"] = item.PublishStatus
	item.ActivityId = req.ActivityId
	err = cygx.UpdateActivitySpecial(updateParams, item)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	//模板消息推送
	if item.PublishStatus == 1 {
		go services.SendWxMsgWithCygxActivitySpecial(activityId)
		//go cygxService.UpdateResourceData(activityId, "activityspecial", "add", time.Now().Format(utils.FormatDateTime))
	} else {
		go cygxService.DetermineTripCancel(activityId)
		//go cygxService.UpdateResourceData(activityId, "activityspecial", "delete", time.Now().Format(utils.FormatDateTime))
	}
	go cygxService.UpdateActivitySpecialResourceData(activityId) //写入首页最新  cygx_resource_data 表
	go elastic.AddComprehensiveActivitySpecial(activityId)       // Es添加活动
	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 /special/delete [post]
func (this *ActivitySpecialCoAntroller) 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.GetAddActivityInfoSpecialById(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.CheckActivitySpecialUpdatePower(AdminUser.AdminId, activityInfo)
	if err != nil {
		br.Msg = "获取管理员身份信息失败"
		br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
		return
	}
	if !havePower {
		br.Msg = popupMsg
		return
	}
	err = cygx.DeleteActivitySpecial(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   ActivityId   query   int  true       "活动ID"
// @Success Ret=200 {object} cygx.CygxActivitySpecialSignupListResp
// @router /special/interested/list [get]
func (this *ActivitySpecialCoAntroller) InterestedList() {
	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
	}
	_, err := cygx.GetAddActivityInfoSpecialById(activityId)
	if err != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，ActivityId：" + strconv.Itoa(activityId)
		return
	}
	list, errList := cygx.GetCygxActivitySpecialSignupList(activityId)
	if errList != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errList.Error()
		return
	}
	resp := new(cygx.CygxActivitySpecialSignupListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 动感兴趣人员列表表格下载
// @Description 动感兴趣人员列表表格下载接口
// @Param   ActivityId   query   int  true     "活动ID"
// @Success 200 导出成功
// @router /special/export [get]
func (this *ActivitySignupCoAntroller) SpecialExport() {
	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
	}
	activityId, _ := this.GetInt("ActivityId")
	//signupType := this.GetString("SignupType")

	activityInfo, err := cygx.GetAddActivityInfoSpecialById(activityId)
	if err != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，ActivityId：" + strconv.Itoa(activityId)
		return
	}
	list, errList := cygx.GetCygxActivitySpecialSignupList(activityId)
	if errList != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errList.Error()
		return
	}

	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("名单")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	var isAdmin bool
	adminInfo, errAdmin := system.GetSysUserById(AdminUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		isAdmin = true
	}
	//标头
	rowTitle := sheet.AddRow()

	if isAdmin {
		cellA := rowTitle.AddCell()
		cellA.Value = "姓名"
		cellB := rowTitle.AddCell()
		cellB.Value = "手机号"
		cellC := rowTitle.AddCell()
		cellC.Value = "公司名称"
		cellD := rowTitle.AddCell()
		cellD.Value = "所属销售"
		for _, item := range list {
			row := sheet.AddRow()
			cellA := row.AddCell()
			cellA.Value = item.RealName
			cellB := row.AddCell()
			cellB.Value = item.Mobile
			cellC := row.AddCell()
			cellC.Value = item.CompanyName
			cellD := row.AddCell()
			cellD.Value = item.SellerName
		}
	} else {
		cellA := rowTitle.AddCell()
		cellA.Value = "姓名"
		cellB := rowTitle.AddCell()
		cellB.Value = "公司名称"
		cellC := rowTitle.AddCell()
		cellC.Value = "所属销售"
		for _, item := range list {
			row := sheet.AddRow()
			cellA := row.AddCell()
			cellA.Value = item.RealName
			cellB := row.AddCell()
			cellB.Value = item.CompanyName
			cellC := row.AddCell()
			cellC.Value = item.SellerName
		}
	}

	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	downloadFileName := activityInfo.ResearchTheme + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	//添加操作日志记录
	br.Success = true
	br.Ret = 200
	br.Msg = "导出成功"
	br.IsAddLog = true
}

// @Title 专项调研客户感兴趣总览
// @Description 专项调研客户感兴趣总览接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} cygx.CygxActivitySpecialSignupRespList
// @router /special/signup/list [get]
func (this *ActivitySpecialCoAntroller) ActivitySignupList() {
	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")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var isCanDownload bool
	var pars []interface{}
	if sysUser.Role == "admin" || sysUser.Role == "researcher" {
		isCanDownload = true
	}

	if isCanDownload == false {
		if sysUser.RoleTypeCode == "rai_group" {
			//组长查看本组所有组员
			condition += ` AND s.company_id IN (SELECT company_id FROM user_seller_relation WHERE seller_id IN (SELECT  admin_id FROM admin WHERE group_id = (SELECT group_id FROM admin WHERE admin_id = ` + strconv.Itoa(sysUser.AdminId) + ` ) )) `
		} else {
			//组员查看自己
			condition += ` AND s.company_id IN (SELECT company_id FROM user_seller_relation WHERE seller_id  = ` + strconv.Itoa(sysUser.AdminId) + `) `
		}
	}
	//condition += ` AND  s.create_time < ? `
	//pars = append(pars, time.Now().Format(utils.FormatDate))
	total, err := cygx.GetCygxActivitySpecialSignupCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += ` GROUP BY s.id ORDER BY s.create_time DESC  `
	list, errList := cygx.GetCygxActivitySpecialSignupListAll(condition, pars, startSize, pageSize)
	if errList != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errList.Error()
		return
	}
	if len(list) == 0 {
		list = make([]*cygx.CygxActivitySpecialSignupResp, 0)
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.CygxActivitySpecialSignupRespList)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 确定行程编辑
// @Description 确定行程编辑接口
// @Param	request	body cygx.ActivitySpecialRep true "type json string"
// @Success 200 操作成功
// @router /special/trip/PreserveAndPublish [post]
func (this *ActivitySpecialCoAntroller) TripPreserveAndPublish() {
	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.ActivitySpecialDateRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	activityId := req.ActivityId
	industrialManagementIdS := req.IndustrialManagementIdS
	industrialSubjectIdS := req.IndustrialSubjectIdS
	temporaryLabel := req.TemporaryLabel
	permissionName := req.PermissionName
	specialType := req.SpecialType
	city := req.City
	isShowSubjectName := req.IsShowSubjectName
	temporarySubject := req.TemporarySubject
	dateYmdList := req.DateYmdList
	item := new(cygx.CygxActivitySpecial)
	customerTypeIds := req.CustomerTypeIds
	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 specialType != 1 && specialType != 2 {
		br.Msg = "请选择调研形式！"
		return
	}
	if specialType == 2 && city == "" {
		br.Msg = "请输入调研城市！"
		return
	}
	if req.Days < 1 {
		br.Msg = "请选择调研天数！"
		return
	}
	if req.Host == "" {
		br.Msg = "请输入主持人！"
		return
	}
	if req.PersonInCharge == "" {
		br.Msg = "请输入纪要负责人！"
		return
	}
	if len(dateYmdList) < 1 {
		br.Msg = "请选择调研日期！"
		return
	}

	req.Days = len(dateYmdList)
	industrialActivityItems, subjectActivityItems, err, industrialNames, industrialSubjectNames := cygxService.HandleIndustrialLabel(temporaryLabel, industrialManagementIdS, industrialSubjectIdS, activityId)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "cygxService.HandleIndustrialLabel，Err:" + err.Error()
		return
	}

	//var items []*cygx.CygxActivity
	var dateYmdListOld []*cygx.CygxActivitySpecialDayResp
	dateYmdListOld, err = cygx.GetCygxActivitySpecialDayByActivityId(activityId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = " 处理时间格式失败，GetCygxActivitySpecialDay，Err:" + err.Error()
		return
	}
	activityTimeTextByDay, activityTime, activityTimeEnd, dateList, e := cygxService.HandleDateYmdList(dateYmdList)

	if e != nil {
		br.Msg = "时间格式有误！"
		br.ErrMsg = "cygxService.HandleIndustrialLabel，Err:" + e.Error()
		return
	}

	if strings.Contains(permissionName, "研选") {
		permissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
	}
	charInfo, errCategory := cygx.GetCategoryInfoByName(permissionName)
	if errCategory != nil {
		br.Msg = "请选择所属行业"
		br.ErrMsg = "获取所属行业信息失败,Err:" + errCategory.Error()
		return
	}
	item.ChartPermissionId = charInfo.ChartPermissionId
	item.ChartPermissionName = req.PermissionName
	item.CustomerTypeIds = req.CustomerTypeIds
	item.ResearchTheme = req.ResearchTheme
	item.TemporaryLabel = req.TemporaryLabel
	item.TemporarySubject = req.TemporarySubject
	item.Scale = req.Scale
	item.TripImgLink = req.TripImgLink
	item.IndustrialName = industrialNames
	item.IndustrialSubjectName = industrialSubjectNames
	item.SpecialType = specialType
	if specialType == 1 {
		item.City = ""
	} else {
		item.City = city
	}
	item.IsShowSubjectName = isShowSubjectName
	if req.TemporaryLabel != "" {
		item.Label = req.TemporaryLabel
	} else {
		if isShowSubjectName == 1 {
			if temporarySubject != "" {
				item.Label = strings.Replace(temporarySubject, ",", "/", -1)
			} else {
				if industrialSubjectNames == "" {
					br.Msg = "请选择关联标的"
					return
				}
				item.Label = industrialSubjectNames
			}
		} else {
			item.Label = industrialNames
		}
	}

	activityInfo, errInfo := cygx.GetAddActivityInfoSpecialById(req.ActivityId)
	if errInfo != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，ActivityId：" + strconv.Itoa(req.ActivityId)
		return
	}
	//校验活动后台管理员、销售是否有修改权限
	havePower, popupMsg, err := cygxService.CheckActivitySpecialUpdatePower(AdminUser.AdminId, activityInfo)
	if err != nil {
		br.Msg = "获取管理员身份信息失败"
		br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
		return
	}
	if !havePower {
		br.Msg = popupMsg
		return
	}
	item.ActivityId = activityInfo.ActivityId
	updateParams := make(map[string]interface{})
	updateParams["ChartPermissionId"] = item.ChartPermissionId
	updateParams["ChartPermissionName"] = item.ChartPermissionName
	updateParams["CustomerTypeIds"] = item.CustomerTypeIds
	updateParams["ResearchTheme"] = item.ResearchTheme
	updateParams["Label"] = item.Label
	updateParams["TemporaryLabel"] = item.TemporaryLabel
	updateParams["TemporarySubject"] = item.TemporarySubject
	updateParams["Scale"] = item.Scale
	updateParams["IndustrialName"] = item.IndustrialName
	updateParams["IndustrialSubjectName"] = item.IndustrialSubjectName
	updateParams["LastUpdatedTime"] = time.Now()
	updateParams["SpecialType"] = item.SpecialType
	updateParams["City"] = item.City
	updateParams["IsShowSubjectName"] = item.IsShowSubjectName
	updateParams["Days"] = req.Days
	updateParams["Host"] = req.Host
	updateParams["LimitPeopleNum"] = req.LimitPeopleNum
	updateParams["PersonInCharge"] = req.PersonInCharge
	updateParams["TripImgLinkFix"] = req.TripImgLinkFix
	updateParams["ActivityTimeTextByDay"] = activityTimeTextByDay
	updateParams["ActivityTime"] = activityTime
	updateParams["ActivityTimeEnd"] = activityTimeEnd
	err = cygx.EditActivitySpecial(updateParams, item, industrialActivityItems, subjectActivityItems)
	if err != nil {
		br.Msg = "发布失败"
		br.ErrMsg = "发布失败,Err:" + err.Error()
		return
	}
	// 批量插入日程时间
	err = cygxService.AddActivitySpecial(dateList, activityId)
	if err != nil {
		br.Msg = "发布失败"
		br.ErrMsg = "发布失败,时间格式有误Err:" + err.Error()
		return
	}
	if activityInfo.Days == 0 {
		cygxService.DetermineTripBeInterested(activityId)
		cygxService.SendWxMsgWithCygxActivitySpecialSubscribeNoInterested(activityId)
	} else {
		var changeMsg string
		if activityInfo.SpecialType != req.SpecialType {
			if req.SpecialType == 1 {
				changeMsg = "调研形式由【线下】变为【线上】"
			} else {
				changeMsg = "调研形式由【线上】变为【线下】"
			}
			cygxService.DetermineTripChange(activityId, "SpecialType", changeMsg)
		}

		if activityInfo.City != req.City && req.City != "" && activityInfo.SpecialType == req.SpecialType {
			changeMsg = "调研形式由【" + activityInfo.City + "】变为【" + req.City + "】"
			cygxService.DetermineTripChange(activityId, "City", changeMsg)
		}
		//判断时间是否有改动，处理字符串
		mapdateYmd := make(map[string]string)
		mapdateYmdTxt := make(map[string]string)
		for k, v := range dateList {
			resultTime := utils.StrTimeToTime(v) //时间字符串格式转时间格式
			timeStrYmd := resultTime.Format(utils.FormatDateTime)
			timeStrYmdTxt := resultTime.Format(utils.FormatDate)
			timeStrHm := resultTime.Format(utils.FormatTimeHm)
			mapdateYmd[timeStrYmd] += timeStrYmd
			if k%2 == 0 {
				mapdateYmdTxt[timeStrYmdTxt] += timeStrHm
			} else {
				mapdateYmdTxt[timeStrYmdTxt] += "~" + timeStrHm + ", "
			}
		}
		for k, v := range mapdateYmdTxt {
			v = strings.TrimRight(v, ", ")
			changeMsg += k + "  " + v + ";"
		}
		changeMsg = strings.TrimRight(changeMsg, ";")
		var changedate bool
		for _, v := range dateYmdListOld {
			if _, ok := mapdateYmd[v.DayTime.Format(utils.FormatDateTime)]; !ok {
				changedate = true
			}
		}
		if len(dateList) != len(dateYmdListOld) || changedate {
			changeMsg = strings.TrimRight(changeMsg, ",")
			cygxService.DetermineTripChange(activityId, "dateList", changeMsg)
		}
	}
	go elastic.AddComprehensiveActivitySpecial(activityId) // Es添加活动
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 活动下线与重新发布
// @Description 活动的发布与取消发布接口
// @Param	request	body cygx.ActivityIdRep true "type json string"
// @Success 200 操作成功
// @router /special/Offline [post]
func (this *ActivitySpecialCoAntroller) Offline() {
	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.CygxActivitySpecial)
	activityInfo, errInfo := cygx.GetAddActivityInfoSpecialById(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.CheckActivitySpecialUpdatePower(AdminUser.AdminId, activityInfo)
	if err != nil {
		br.Msg = "获取管理员身份信息失败"
		br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
		return
	}
	if !havePower {
		br.Msg = popupMsg
		return
	}
	updateParams := make(map[string]interface{})
	if activityInfo.IsOffline == 0 {
		item.IsOffline = 1
		item.PublishStatus = 0
	} else {
		item.IsOffline = 0
		item.PublishStatus = 1
		updateParams["PublishDate"] = time.Now()
	}
	updateParams["PublishStatus"] = item.PublishStatus
	updateParams["IsOffline"] = item.IsOffline
	item.ActivityId = req.ActivityId
	err = cygx.UpdateActivitySpecial(updateParams, item)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	//模板消息推送
	//if item.PublishStatus == 1 {
	//	go cygxService.UpdateResourceData(activityId, "activityspecial", "add", time.Now().Format(utils.FormatDateTime))
	//	//go services.SendWxMsgWithCygxActivitySpecial(activityId)
	//} else {
	//	go cygxService.UpdateResourceData(activityId, "activityspecial", "delete", time.Now().Format(utils.FormatDateTime))
	//}
	go cygxService.UpdateActivitySpecialResourceData(activityId) //写入首页最新  cygx_resource_data 表
	go elastic.AddComprehensiveActivitySpecial(activityId)       // Es添加活动
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}
