package cygx

import (
	"encoding/json"
	"fmt"
	"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/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 到会管理
type ActivityMeetCoAntroller struct {
	controllers.BaseAuthController
}

// @Title 到会管理列表
// @Description 获取到会管理列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @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   KeyWord   query   string  false       "搜索关键词"
// @Param   MeetType   query   int  true       "会议类型 1线上、2线下"
// @Param   IsResearch   query   bool  true       "是否为研选"
// @Success 200 {object} cygx.GetCygxMeetListRep
// @router /activityMeet/list [get]
func (this *ActivityMeetCoAntroller) MeetList() {
	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")
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	ActivityTypeId := this.GetString("ActivityTypeId")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	keyWord := this.GetString("KeyWord")
	meetType, _ := this.GetInt("MeetType")
	isResearch, _ := this.GetBool("IsResearch", false) // 是否为研选 查研观向11.0 （研选活动独立显示）
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	activityIdArr := make([]int, 0)
	activityIdArrUpdateTime := make([]int, 0)
	var condition string
	var pars []interface{}
	condition += `AND  a.active_state  IN (2,3)  AND a.publish_status = 1 `
	if keyWord != "" {
		condition += ` AND (a.activity_name LIKE '%` + keyWord + `%' )  `
	}
	if meetType == 1 {
		condition += ` AND a.activity_type_id  IN (1,2,3,7)  `
	} else {
		condition += ` AND a.activity_type_id  IN (4,5,6,8) ` //默认
	}
	if ActivityTypeId != "" {
		condition += ` AND a.activity_type_id IN (` + ActivityTypeId + `) `
	}
	if isResearch {
		chartPermissionId = utils.CHART_PERMISSION_ID_YANXUAN
	} else {
		condition += ` AND a.chart_permission_id  !=  '` + strconv.Itoa(utils.CHART_PERMISSION_ID_YANXUAN) + `'`
	}
	//行业名称
	if chartPermissionId > 0 {
		condition += ` AND a.chart_permission_id  =  '` + strconv.Itoa(chartPermissionId) + `'`
	}
	if startDate != "" {
		condition += ` AND a.activity_time >= ` + "'" + startDate + " 00:00:00'"
	}
	if endDate != "" {
		condition += ` AND a.activity_time <= ` + "'" + endDate + " 23:59:59'"
	}
	total, err := cygx.GetCygxMeetCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += ` GROUP BY a.activity_id  ORDER BY a.activity_time DESC `
	list, errList := cygx.GetCygxMeetListAll(condition, pars, startSize, pageSize)
	if errList != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errList.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.GetCygxMeetListRep)
	for k, v := range list {
		if v.IsSubmitMeeting == 1 {
			list[k].OperationStyle = 2
		} else {
			list[k].OperationStyle = 1
		}
		if meetType == 2 {
			list[k].MeetPeopleNum = v.OmeetPeopleNum
		}
		if v.ActivityTypeId == 7 {
			list[k].IsCClassMeeting = true
		}
		activityIdArrUpdateTime = append(activityIdArrUpdateTime, v.ActivityId)
		//到会列表按钮展示操作
		if v.IsSubmitMeeting == 1 {
			//list[k].IsShowAttendanceDetails = true
			if meetType == 1 && v.ActivityTypeId == 7 {
				//如果C类电话会是手动提交的报名信息，就展示  修改到会情况 按钮
				if v.SubmitMeetingType == 1 {
					list[k].IsShowUpdateMeeting = true
				}
				//C类强制展示
				list[k].IsShowAttendanceDetails = true
			}
			//已经提交到会的线下会议都展示 修改到会情况 按钮
			if meetType == 2 {
				list[k].IsShowUpdateMeeting = true
			}
		} else {
			if list[k].YidongActivityId != "" {
				//list[k].ActivityTypeName += utils.YI_DONG_NAME
			} else {
				//如果是线上
				if meetType == 1 {
					list[k].IsShowHandMovement = true
					//如果 是C类电话会则做下面的处理
					if v.ActivityTypeId == 7 {
						list[k].IsShowSubmitMeeting = true
					}
				} else {
					list[k].IsShowSubmitMeeting = true
				}
			}
			if v.IsYidongConduct == 1 {
				//v.ActivityTypeName += utils.YI_DONG_NAME_TWO
				list[k].IsShowSubmitMeeting = true
				list[k].IsShowHandMovement = false
			}
		}

		if v.YidongActivityId != "" {
			ydUpdateDetil, err := cygx.GetCygxActivityYiDongUpdateTime(v.YidongActivityId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，GetCygxActivityYiDongUpdateTime Err:" + err.Error()
				return
			}
			if ydUpdateDetil != nil {
				list[k].UpdateTime = ydUpdateDetil.CreateTime
			}
			activityIdArr = append(activityIdArr, v.ActivityId)
			//易懂的到会改为true
			if v.IsSubmitMeeting == 1 {
				list[k].IsShowAttendanceDetails = true
			}

			if v.ChartPermissionNameDeputy != "" && v.ChartPermissionNameDeputy != v.ChartPermissionName {
				v.ChartPermissionName = v.ChartPermissionNameDeputy // 易董同步过来的活动展示副权限  v11.0
			}
		}

		//判断是否是易董在易董举办的会议
		if v.IsYidongConduct == 1 {
			list[k].IsShowHandMovement = false
			list[k].IsShowSubmitMeeting = false
			list[k].IsShowUpdateMeeting = false
		}
		//是否展示签到码
		if (v.ActivityTypeId == 5 || v.ActivityTypeId == 6 || v.ActivityTypeId == 8) && v.SigninImg != "" {
			list[k].IsShowSigninButton = true
		}
		list[k].MeetPeopleNum += v.PotentialPeopleNum //加上潜在客户人数
	}

	mapUpdateTime, _ := cygxService.GetActivityMeetUpdateTime(activityIdArrUpdateTime) //获取线上活动到会更新时间
	//处理易董的活动到会数量
	mapYidongMeetNum := make(map[int]int)
	if len(activityIdArr) > 0 {
		yidongList, err := cygx.GetCygxActivityYiDongMeetNum(activityIdArr)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetCygxActivityYiDongUpdateTime Err:" + err.Error()
			return
		}
		for _, v := range yidongList {
			mapYidongMeetNum[v.ActivityId] = v.Num
		}
	}
	for k, v := range list {
		if v.ChartPermissionNames != "" {
			list[k].ChartPermissionName = v.ChartPermissionNames
		}
		if v.YidongActivityId != "" {
			list[k].MeetPeopleNum = mapYidongMeetNum[v.ActivityId]
			list[k].ActivityTypeName += utils.YI_DONG_NAME
		}
		if v.IsYidongConduct == 1 {
			v.ActivityTypeName += utils.YI_DONG_NAME_TWO
		}
		v.UpdateTime = mapUpdateTime[v.ActivityId]
	}
	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 200 {object} cygx.CygxActivitySignupListRep
// @router /activityMeet/offlineListDetail [get]
func (this *ActivityMeetCoAntroller) OfflineListDetail() {
	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
	}
	activityId, _ := this.GetInt("ActivityId")
	activityInfo, _ := cygx.GetAddActivityInfoById(activityId)
	if activityInfo == nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:activityId：" + strconv.Itoa(activityId)
		return
	}
	var condition string
	condition += ` AND s.is_cancel = 0 AND s.do_fail_type =0 AND s.activity_id = ` + strconv.Itoa(activityId)
	list, err := cygx.GetCygxActivitySignup(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.CygxActivitySignupListRep)
	for k, v := range list {
		if v.IsMeeting == 1 {
			list[k].Operation = true
		}
	}
	resp.List = list
	resp.ActivityId = activityId
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 提交线下到会情况
// @Description 提交线下到会情况接口
// @Param	request	body cygx.MeetingDoRep true "type json string"
// @Success 200 操作成功
// @router /activityMeet/meetingDo [post]
func (this *ActivityMeetCoAntroller) MeetingDo() {
	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.MeetingDoRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	mapMeetingUid := make(map[int]bool)
	var userIdArr []int
	meetingUids := req.Ids
	if len(meetingUids) == 0 {
		meetingUids = "0"
	} else {
		//过滤字段
		slice := strings.Split(meetingUids, ",")
		meetingUids = ""
		for _, v := range slice {
			if v != "" {
				meetingUids += v + ","
				userId, _ := strconv.Atoi(v)
				if userId > 0 {
					userIdArr = append(userIdArr, userId)
				}
				mapMeetingUid[userId] = true
			}
		}
		meetingUids = strings.TrimRight(meetingUids, ",")
	}
	activityId := req.ActivityId
	//加入缓存机制，避免同时提交到会信息
	redisKey := fmt.Sprint("cygx:activity_meet:batch:activityId:", req.ActivityId)
	isExist := utils.Rc.IsExist(redisKey)
	if isExist {
		br.Msg = "到会详情正在处理,请勿重复提交"
		return
	} else {
		//设置1分钟缓存
		utils.Rc.SetNX(redisKey, 1, time.Second*60)
		defer func() {
			utils.Rc.Delete(redisKey)
		}()
	}
	//加入缓存机制，避免创建同一个名称的指标 end
	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
	//}
	noMeetingUids, err := cygx.GetSignupUserIds(activityId, meetingUids) //未到会的用户ID
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
		return
	}
	var allUids string
	if len(noMeetingUids) > 0 {
		allUids = noMeetingUids + "," + meetingUids
	} else {
		allUids = meetingUids
	}

	listUser, err := cygx.GetUserAndCompanyNameListByUids(allUids)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	var pars []interface{}
	var condition string
	condition = `  AND  activity_id = ?   ORDER BY create_time  DESC    `
	pars = append(pars, activityId)
	listSigin, err := cygx.GetCygxActivitySigninList(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	siginMap := make(map[int]string)

	for _, v := range listSigin {
		siginMap[v.UserId] = v.CreateTime
	}

	var items []*cygx.CygxActivityOfflineMeetingDetail
	var itemDs []*cygx.CygxActivitySignupDetail
	for _, v := range listUser {
		var item = new(cygx.CygxActivityOfflineMeetingDetail)
		item.UserId = v.UserId
		item.ActivityId = activityId
		item.CreateTime = time.Now()
		item.Mobile = v.Mobile
		item.Email = v.Email
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		if mapMeetingUid[v.UserId] {
			item.IsMeeting = 1
		}
		//保留扫码通过扫码签到人员的签到时间
		if siginMap[v.UserId] != "" {
			item.SigninTime = siginMap[v.UserId]
		} else {
			item.SigninTime = time.Now().Format(utils.FormatDateTime)
		}
		items = append(items, item)

		var itemD = new(cygx.CygxActivitySignupDetail)
		itemD.UserId = v.UserId
		itemD.RealName = v.RealName
		itemD.ActivityId = activityId
		itemD.CreateTime = time.Now()
		itemD.Mobile = v.Mobile
		itemD.CompanyId = v.CompanyId
		itemD.CompanyName = v.CompanyName
		if mapMeetingUid[v.UserId] {
			itemD.IsMeeting = 1
		}
		itemDs = append(itemDs, itemD)
	}
	err = cygx.MeetingDo(meetingUids, noMeetingUids, activityId, items)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	go cygxService.AddCygxActivityRestrictSignupByAdmin(activityId)                      // 处理爽约记录黑名单限制
	go cygxService.AddCygxActivityMeetDetailLogOffline(meetingUids, activityId)          // 处理个人以及机构到会数量
	go cygxService.AddctivitySignupDetailList(itemDs, activityId)                        // 处理个人以及机构到会数量
	go cygxService.ActivityUserLabelLogAdd(activityId, userIdArr)                        // 处理用户标签
	go cygxService.YanXuanActivityPointsBillSubmitMeeting(activityId, AdminUser.AdminId) // 处理用户到会研选扣点
	//添加操作日志记录
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 线下报名到会详情列表
// @Description 获取线下报名到会详情列表接口
// @Param   ActivityId   query   int  true     "活动ID"
// @Success 200 {object} cygx.CygxActivitySignupListRep
// @router /activityMeet/offlineMeetingList [get]
func (this *ActivityMeetCoAntroller) OfflineMeetingList() {
	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
	}
	activityId, _ := this.GetInt("ActivityId")
	activityInfo, _ := cygx.GetAddActivityInfoById(activityId)
	if activityInfo == nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:activityId：" + strconv.Itoa(activityId)
		return
	}
	var condition string
	var err error
	var list []*cygx.CygxActivitySignupList
	condition += `  AND s.activity_id = ` + strconv.Itoa(activityId)

	if activityInfo.YidongActivityId != "" {
		listMeeting, errMeeting := cygx.GetOfflineMeetingListByYidong(condition)
		list = listMeeting
		err = errMeeting
	} else {

		if activityInfo.IsSubmitMeeting == 1 {
			condition += " ORDER BY is_meeting DESC ,signin_time DESC , id DESC "
			listMeeting, errMeeting := cygx.GetOfflineMeetingList(condition)
			list = listMeeting
			err = errMeeting
		} else {
			condition += ` AND s.do_fail_type = 0 `
			listNoMeeting, errNoMeeting := cygx.GetCygxActivitySignup(condition)
			if errNoMeeting != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + errNoMeeting.Error()
				return
			}
			for k := range listNoMeeting {
				listNoMeeting[k].Channel = 1
			}
			list = listNoMeeting
			err = errNoMeeting
		}
	}

	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	var mobileArr []string
	resp := new(cygx.CygxActivitySignupListRep)
	if len(list) == 0 {
		list = make([]*cygx.CygxActivitySignupList, 0)
	} else {
		for k, v := range list {
			if v.IsMeeting == 1 {
				list[k].Operation = true
			}
			if activityInfo.YidongActivityId != "" {
				list[k].Channel = 1
			}
			if list[k].Channel == 0 && list[k].IsMeeting == 1 {
				list[k].IsAirborne = 1
			}
			mobileArr = append(mobileArr, v.Mobile)
		}
	}
	mapMobileUser := make(map[string]string)

	if len(mobileArr) > 0 {

		listUser, err := models.GetWxUserListByUserMobileHaveCompany(mobileArr)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetWxUserListByUserMobileHaveCompany Err:" + err.Error()
			return
		}
		for _, v := range listUser {
			mapMobileUser[v.Mobile] = v.RealName
		}

		for _, v := range list {
			v.RealName = mapMobileUser[v.Mobile]
		}
	}

	var pars []interface{}
	condition = `  AND  activity_id = ?   ORDER BY create_time  DESC    `
	pars = append(pars, activityId)
	listSigin, err := cygx.GetCygxActivitySigninList(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if len(listSigin) == 0 {
		resp.ListSignin = make([]*cygx.CygxActivitySignin, 0)
	} else {
		for _, v := range listSigin {
			if v.CompanyId <= 1 {
				if v.Mobile == "" {
					v.Mobile = v.Email
				}
				resp.ListSignin = append(resp.ListSignin, v)
			}
		}
		for _, v := range list {
			if v.IsMeeting == 0 {
				v.SigninTime = ""
			}
		}
		if len(resp.ListSignin) == 0 {
			resp.ListSignin = make([]*cygx.CygxActivitySignin, 0)
		}
	}
	resp.List = list
	resp.ActivityId = activityId
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 爽约记录
// @Description 获取爽约记录接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   SellerName   query   string  false       "销售姓名"
// @Success 200 {object} cygx.GetCygxBreakAppointmentListRep
// @router /activityMeet/breakAppointment [get]
func (this *ActivityMeetCoAntroller) BreakAppointment() {
	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
	}
	var condition string
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	sellerName := this.GetString("SellerName")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var pars []interface{}

	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	respDownload := new(cygx.CanDownload)
	adminInfo, errAdmin := system.GetSysUserById(sysUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		respDownload.IsCanDownload = true
	}
	var list []*cygx.CygxBreakAppointmentList
	var err error
	if respDownload.IsCanDownload == false {
		//if adminInfo.RoleTypeCode == "rai_group" {
		//	//组长查看本组所有组员
		//	condition = ` AND s.user_id IN (SELECT user_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.user_id IN (SELECT user_id FROM user_seller_relation WHERE seller_id  = ` + strconv.Itoa(sysUser.AdminId) + `) `
		//}

		//权益申请销售只能看到自己名下的客户的申请
		companyIds, err := cygxService.GetAdminLookUserCompanyIds(sysUser)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetAdminLookUserCompanyIds Err:" + err.Error()
			return
		}
		var companyIdstr []string
		for _, v := range companyIds {
			companyIdstr = append(companyIdstr, strconv.Itoa(v))
		}
		condition += ` AND s.company_id IN (` + strings.Join(companyIdstr, ",") + `) `
	}
	if keyWord != "" {
		condition += ` AND (s.company_name LIKE '%` + keyWord + `%' OR s.mobile LIKE '%` + keyWord + `%') `
	}
	if sellerName != "" {
		condition += ` 	AND s.seller_name = '` + sellerName + `' `
	}
	condition += ` AND a.is_limit_people > 0  `
	total, err := cygx.GetCygxBreakAppointmentCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list, err = cygx.GetCygxBreakAppointmentList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.IsRestrict > 0 {
			list[k].Operation = true
		}
		sellerName, err := cygx.GetCompanySellerName(v.CompanyId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取客户信息失败,Err:" + err.Error() + "CompanyId:" + strconv.Itoa(v.CompanyId)
			return
		}
		list[k].SellerName = sellerName
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.GetCygxBreakAppointmentListRep)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 销售姓名列表
// @Description 获取销售姓名列表接口
// @Success 200 {object} cygx.GetCygxSellerNameListRep
// @router /activityMeet/sellerNameList [get]
func (this *ActivityMeetCoAntroller) SellerName() {
	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
	}
	list, err := cygx.GetCygxSellerNameList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.GetCygxSellerNameListRep)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 爽约详情
// @Description 获取爽约详情列表接口
// @Param   UserId   int   string  true       "用户ID"
// @Success 200 {object} cygx.GetCygxActivityBreakAppointmentRep
// @router /activityMeet/breakAppointmentDetail [get]
func (this *ActivityMeetCoAntroller) BreakAppointmentDetail() {
	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
	}
	userId, _ := this.GetInt("UserId")
	detail, err := models.GetWxUserByUserId(userId)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	list, err := cygx.GetCygxActivityBreakAppointmentList(detail.Mobile)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.GetCygxActivityBreakAppointmentRep)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 报名限制操作
// @Description 报名限制操作接口
// @Param	request	body cygx.SignUpRestrictUid true "type json string"
// @Success 200 操作成功
// @router /activityMeet/signUpRestrictUid [post]
func (this *ActivityMeetCoAntroller) SignUpRestrict() {
	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
	}
	var req cygx.SignUpRestrictUid
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	uid := req.UserId
	total, errTotal := cygx.GetUserBreakAppointmentCount(uid)
	if errTotal != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errTotal.Error()
		return
	}
	if total == 0 {
		br.Msg = "该用户暂无爽约记录！"
		br.ErrMsg = "该用户暂无爽约记录，UserID：" + strconv.Itoa(uid)
		return
	}
	totalRestrictByUid, errRestrictByUid := cygx.GetCygxActivityRestrictSignupCount(uid)
	if errRestrictByUid != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errRestrictByUid.Error()
		return
	}
	if totalRestrictByUid == 0 {
		infoUser, err := cygx.GetUserAndCompanyNameList(uid)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		item := new(cygx.CygxActivityRestrictSignup)
		item.UserId = infoUser.UserId
		item.CreateTime = time.Now()
		item.Mobile = infoUser.Mobile
		item.Email = infoUser.Email
		item.CompanyId = infoUser.CompanyId
		item.CompanyName = infoUser.CompanyName
		item.IsRestrict = 1
		err = cygx.AddCygxActivityRestrictSignup(item)
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "新增用户失败，Err:" + err.Error()
			return
		}
	} else {
		var newIsRestrict int
		detail, err := cygx.GetCygxActivityRestrictSignupInfo(uid)
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "操作失败,Err:" + err.Error()
			return
		}
		if detail == nil {
			br.Msg = "操作失败"
			br.ErrMsg = "UserID错误,不存在UserID："
			return
		}
		if detail.IsRestrict == 0 {
			newIsRestrict = 1
		} else {
			newIsRestrict = 0
		}
		err = cygx.UpdateCygxActivityRestrictSignup(newIsRestrict, uid)
		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 200 {object} cygx.GetAppointmentListRep
// @router /activityMeet/appointmentList [get]
func (this *ActivityMeetCoAntroller) AppointmentList() {
	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
	}
	activityId, _ := this.GetInt("ActivityId")
	if activityId < 1 {
		br.Msg = "活动不存在"
		return
	}
	activityInfo, _ := cygx.GetAddActivityInfoById(activityId)
	if activityInfo == nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:activityId：" + strconv.Itoa(activityId)
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	resp := new(cygx.CanDownload)
	adminInfo, errAdmin := system.GetSysUserById(sysUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		resp.IsCanDownload = true
	}
	sqlStr := `  AND s.do_fail_type = 0`
	memberType := "Admin"

	list, err := cygx.GetCygxAppointmentList(activityId, sqlStr)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	total, errtotal := cygx.GetCygxAppointmentCount(activityId, sqlStr)
	if errtotal != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "客户总数获取失败，Err:" + errtotal.Error()
		return
	}
	myTotalsqlStr := `AND s.do_fail_type = 0  AND s.user_id IN (SELECT user_id FROM user_seller_relation WHERE seller_id  = ` + strconv.Itoa(sysUser.AdminId) + `) `
	myTotal, errmyTotal := cygx.GetCygxAppointmentCount(activityId, myTotalsqlStr)
	if errmyTotal != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "我的客户总数获取失败，Err:" + errmyTotal.Error()
		return
	}
	for k, v := range list {
		list[k].SellerName = v.PsellerName
	}
	respList := new(cygx.GetAppointmentListRep)
	//销售查看自己客户，销售组长查看组员
	if resp.IsCanDownload == false {
		mapMobile, err := cygxService.GetAdminLookUserMobile(adminInfo)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,销售对应权限，Err:" + err.Error()
			return
		}
		for _, v := range list {
			if _, ok := mapMobile[v.Mobile]; ok {
				respList.List = append(respList.List, v)
			}
		}
		if adminInfo.RoleTypeCode == "rai_group" {
			//组长查看本组所有组员
			memberType = "GroupLeader"
		} else {
			//组员查看自己
			memberType = "Sale"
		}
	} else {
		respList.List = list
	}
	if len(respList.List) == 0 {
		respList.List = make([]*cygx.CygxAppointmentList, 0)
	}

	respList.List = list
	respList.Total = total
	respList.MyTotal = myTotal
	respList.ActivityId = activityId
	respList.MemberType = memberType
	respList.IsLimitPeople = activityInfo.IsLimitPeople
	activityTypeId := activityInfo.ActivityTypeId

	if activityTypeId == 1 || activityTypeId == 2 {
		respList.ExcelType = "AppointmentCall"
	} else if activityTypeId == 5 || activityTypeId == 6 {
		respList.ExcelType = "ExpertSalon"
	} else if activityTypeId == 3 {
		respList.ExcelType = "Teleconference"
	} else if activityTypeId == 4 {
		respList.ExcelType = "OfflineResearch"
	} else if activityTypeId == 7 {
		respList.ExcelType = "CClass"
	}

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

// @Title 客户参会记录下载
// @Description 客户参会记录下载
// @Success 200 导出成功
// @router /activityMeet/meetingExport [get]
func (this *ActivityMeetCoAntroller) SignupFailExport() {
	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
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	resp := new(cygx.CanDownload)
	adminInfo, errAdmin := system.GetSysUserById(AdminUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		resp.IsCanDownload = true
	}
	var err error
	var condition string
	var items []*cygx.MeetingExportRep
	list, err := cygx.GetMeetingExportAll(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//销售查看自己客户，销售组长查看组员
	if resp.IsCanDownload == false {
		mapMobile, err := cygxService.GetAdminLookUserMobile(adminInfo)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,销售对应权限，Err:" + err.Error()
			return
		}
		for _, v := range list {
			if _, ok := mapMobile[v.Mobile]; ok {
				items = append(items, v)
			}
		}
	} else {
		items = list
	}

	//创建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
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "公司名"
	cellB := rowTitle.AddCell()
	cellB.Value = "状态"
	cellC := rowTitle.AddCell()
	cellC.Value = "姓名"
	cellD := rowTitle.AddCell()
	cellD.Value = "手机号"
	cellE := rowTitle.AddCell()
	cellE.Value = "所属销售"
	cellF := rowTitle.AddCell()
	cellF.Value = "活动名称"
	cellG := rowTitle.AddCell()
	cellG.Value = "行业"
	cellH := rowTitle.AddCell()
	cellH.Value = "活动类型"
	cellI := rowTitle.AddCell()
	cellI.Value = "活动时间"
	cellJ := rowTitle.AddCell()
	cellJ.Value = "开通权限"

	for _, item := range items {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.CompanyName
		cellB := row.AddCell()
		cellB.Value = item.Status
		cellC := row.AddCell()
		cellC.Value = item.RealName
		cellD := row.AddCell()
		cellD.Value = item.Mobile
		cellE := row.AddCell()
		cellE.Value = item.PsellerName
		cellF := row.AddCell()
		cellF.Value = item.ActivityName
		cellG := row.AddCell()
		cellG.Value = item.ChartPermissionName
		cellH := row.AddCell()
		cellH.Value = item.ActivityTypeName
		cellI := row.AddCell()
		cellI.Value = item.ActivityTimeText
		cellJ := row.AddCell()
		cellJ.Value = item.Permission
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "客户参会记录" + randStr + ".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   File   query   file  true       "文件"
// @Param   ActivityId   query   int  true     "活动ID"
// @Success 200 Ret=200 导入成功
// @router /activityMeet/import [post]
func (this *ActivityMeetCoAntroller) Import() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请重新登录"
		return
	}
	file, h, err := this.GetFile("File")
	if err != nil {
		br.Msg = "获取文件失败"
		br.ErrMsg = "获取文件失败，Err:" + err.Error()
		return
	}
	activityId, _ := this.GetInt("ActivityId")
	if activityId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "活动id为0"
		return
	}
	activityInfo, err := cygx.GetAddActivityInfoById(activityId)
	if err != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
		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 != 3 && activityInfo.ActiveState != 2 {
		br.Msg = "任务未开始，请稍后上传"
		return
	}
	uploadDir := "static/xls"
	err = os.MkdirAll(uploadDir, 766)
	if err != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
		return
	}
	path := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
	defer file.Close()
	err = this.SaveToFile("File", path)
	if err != nil {
		br.Msg = "文件保存失败"
		br.ErrMsg = "文件保存失败，Err:" + err.Error()
		return
	}
	xlFile, err := xlsx.OpenFile(path)
	if err != nil {
		br.Msg = "文件导入失败"
		br.ErrMsg = "文件导入失败，Err:" + err.Error()
		return
	}
	defer func() {
		os.Remove(path)
	}()
	//允许添加的联系人
	needAddAttendanc := make([]*cygx.CygxActivityAttendanceDetail, 0)
	var mobileStr string
	// 遍历sheet页读取
	realNameKey, mobileKey, companyNameKey, positionKey, firstMeetingTimeKey, lastMeetingTimeKey, durationKey, meetingTypeStrKey, meetingAuthenticationKey, meetingStatusStrKey := -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
	for _, sheet := range xlFile.Sheets {
		//遍历行读取
		maxRow := sheet.MaxRow
		for i := 0; i < maxRow; i++ {
			if i == 0 {
				row := sheet.Row(i)
				cells := row.Cells
				for k, cell := range cells {
					text := cell.String()
					if text == "姓名" {
						realNameKey = k
					}
					if text == "电话" {
						mobileKey = k
					}
					if text == "公司" {
						companyNameKey = k
					}
					if text == "职位" {
						positionKey = k
					}
					if text == "首次入会时间" {
						firstMeetingTimeKey = k
					}
					if text == "最后退出时间" {
						lastMeetingTimeKey = k
					}
					if text == "参与总时长(分)" {
						durationKey = k
					}
					if text == "参会方式" {
						meetingTypeStrKey = k
					}
					if text == "参会鉴权" {
						meetingAuthenticationKey = k
					}
					if text == "参会状态" {
						meetingStatusStrKey = k
					}
				}
			}
			if i == 0 {
				if mobileKey == -1 {
					br.Msg = "模板格式错误，缺少：电话"
					br.ErrMsg = "模板格式错误"
					return
				}
				if firstMeetingTimeKey == -1 {
					br.Msg = "模板格式错误，缺少：首次入会时间"
					br.ErrMsg = "模板格式错误！"
					return
				}
				if lastMeetingTimeKey == -1 {
					br.Msg = "模板格式错误，缺少：最后退出时间"
					br.ErrMsg = "模板格式错误！"
					return
				}
				if durationKey == -1 {
					br.Msg = "模板格式错误，缺少：参与总时长"
					br.ErrMsg = "模板格式错误！"
					return
				}
			}
			if i >= 1 {
				row := sheet.Row(i)
				cells := row.Cells
				var realName, mobile, companyName, position, sellerName, firstMeetingTime, lastMeetingTime, duration, meetingTypeStr, meetingAuthentication, meetingStatusStr string
				for k, cell := range cells {
					if k == realNameKey {
						realName = cell.String()
					}
					if k == mobileKey {
						mobile = cell.String()
						//if mobile != "" {
						//	fmt.Println(mobile)
						//	_, err := strconv.ParseFloat(mobile, 64)
						//	if err != nil {
						//		br.Msg = "手机号存在非数字类字符!"
						//		br.ErrMsg = "手机号存在非数字类字符！err:" + err.Error() + mobile
						//		return
						//	}
						//}
					}
					if k == companyNameKey {
						companyName = cell.String()
					}
					if k == positionKey {
						position = cell.String()
					}
					if k == firstMeetingTimeKey {
						firstMeetingTime = cell.String()
					}
					if k == lastMeetingTimeKey {
						lastMeetingTime = cell.String()
					}
					if k == durationKey {
						duration = cell.String()
					}
					if k == meetingTypeStrKey {
						meetingTypeStr = cell.String()
					}
					if k == meetingAuthenticationKey {
						meetingAuthentication = cell.String()
					}
					if k == meetingStatusStrKey {
						meetingStatusStr = cell.String()
					}
				}
				//这些字段都没有的话，系统认为excel到底了
				if duration == "" && mobile == "" && firstMeetingTime == "" {
					break
				}
				item := new(cygx.CygxActivityAttendanceDetail)
				item.ActivityId = activityId
				item.RealName = realName
				item.Mobile = mobile
				item.CompanyName = companyName
				item.SellerName = sellerName
				item.FirstMeetingTime = firstMeetingTime
				item.LastMeetingTime = lastMeetingTime
				item.Duration = duration
				item.MeetingTypeStr = meetingTypeStr
				item.MeetingAuthentication = meetingAuthentication
				item.MeetingStatusStr = meetingStatusStr
				item.Position = position
				item.CreateTime = time.Now()
				if mobile != "" {
					mobileStr += "'" + mobile + "'" + ","
					needAddAttendanc = append(needAddAttendanc, item)
				}
			}
		}
	}
	mobileStr = strings.TrimRight(mobileStr, ",")
	if mobileStr == "" {
		mobileStr = "1"
	}
	list, err := cygx.GetWxUserOutboundMobile(mobileStr)
	if err != nil {
		br.Msg = "上传失败"
		br.ErrMsg = "获取用户信息失败，Err:" + err.Error()
		return
	}
	for k, v := range needAddAttendanc {
		for _, v2 := range list {
			if v2.OutboundMobile == v.Mobile {
				needAddAttendanc[k].CompanyId = v2.CompanyId
			}
		}
	}
	err = cygx.AddAttendancDetail(needAddAttendanc, activityId, mobileStr)
	if err != nil {
		br.Msg = "上传失败"
		br.ErrMsg = "文件保存失败，Err:" + err.Error()
		return
	}

	go cygxService.AddCygxActivityRestrictSignupByAdmin(activityId)
	go cygx.AddCygxActivityMeetDetailLogOnline(needAddAttendanc, activityId)
	//添加操作日志记录

	br.Msg = "导入成功"
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
}

// @Title 线上到会详情
// @Description 获取线上到会详情接口
// @Param   ActivityId   query   int  true     "活动ID"
// @Success 200 {object} cygx.AttendanceDetailList
// @router /activityMeet/attendanceDetail [get]
func (this *ActivityMeetCoAntroller) AttendanceDetail() {
	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
	}
	activityId, _ := this.GetInt("ActivityId")
	if activityId < 1 {
		br.Msg = "活动不存在"
		return
	}
	activityInfo, _ := cygx.GetAddActivityInfoById(activityId)
	if activityInfo == nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:activityId：" + strconv.Itoa(activityId)
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	resp := new(cygx.CanDownload)
	adminInfo, errAdmin := system.GetSysUserById(sysUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		resp.IsCanDownload = true
	}
	var condition string
	var condition2 string

	//同一用户上传多次参会记录时，到会与未到会分开查询
	list1, err := cygx.GetAttendanceDetailListGroup(activityId, condition+` AND s.is_meeting = 1 AND d.userid_entity != 3  GROUP BY s.user_id `)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	listGroup, err := cygx.GetAttendanceDetailListGroup(activityId, condition+` AND s.is_meeting = 0    GROUP BY  s.user_id   `)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var sellerCompanyIds []int
	if len(listGroup) > 0 {
		for _, v := range listGroup {
			list1 = append(list1, v)
		}
	}
	mobileStr := ""
	for _, v := range list1 {
		if v.OutboundMobile != "" {
			mobileStr += v.OutboundMobile + ","
		}
		if v.Mobile != "" {
			mobileStr += v.Mobile + ","
		}
		sellerCompanyIds = append(sellerCompanyIds, v.CompanyId)
	}
	mobileStr = strings.TrimRight(mobileStr, ",")
	if mobileStr == "" {
		mobileStr = "1"
	}
	condition2 += ` AND d.mobile NOT IN ( ` + mobileStr + ` )  `
	list2, err := cygx.GetAttendanceDetailList2(activityId, condition2+` AND d.company_id > 1 `)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	listNoAppointment, err := cygx.GetAttendanceDetailList2(activityId, ` AND d.mobile NOT IN ( `+mobileStr+` )  `+` AND d.company_id > 1  `) //未预约 所有
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for _, v := range listNoAppointment {
		if v.Mobile != "" {
			mobileStr += "," + v.Mobile
		}
	}
	//不在公司客户体系里面的也算潜在客户，通过手机号来排除 潜在客户不做权限判断
	mobileStr = strings.TrimLeft(mobileStr, ",")
	condition2 = ` 	AND d.real_name NOT LIKE '%专家%'   AND d.mobile NOT IN ( ` + mobileStr + ` )  `
	var isBloneSell bool //是否属于销售添加
	var isProhibit bool  // 是否禁止展示
	if activityInfo.AdminId > 0 {
		adminInfoActivity, errAdmin := system.GetSysUserById(activityInfo.AdminId)
		if errAdmin != nil && errAdmin.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
			return
		}
		if adminInfoActivity != nil {
			roleTypeCode := adminInfoActivity.RoleTypeCode
			if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
				isBloneSell = true
			}
			//如果这个活动属于销售创建，而且不是这个销售自己查看的，并且查看的角色不属于管理员或者权益管理员，那么就做限制处理
			if isBloneSell && sysUser.AdminId != adminInfoActivity.AdminId && (sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN) {
				isProhibit = true //限制又取消了。2023-06-14 ，2024.09.04又开启了
			}
		}
	}
	list3, err := cygx.GetAttendanceDetailList3(activityId, condition2)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for k, v := range list1 {
		if v.FirstMeetingTime == "0000-00-00 00:00:00" {
			list1[k].FirstMeetingTime = ""
			list1[k].LastMeetingTime = ""
		}
	}
	for k, v := range list2 {
		if v.FirstMeetingTime == "0000-00-00 00:00:00" {
			list2[k].FirstMeetingTime = ""
			list2[k].LastMeetingTime = ""
		}
		sellerCompanyIds = append(sellerCompanyIds, v.CompanyId)
	}

	//获取公司ID所对应的销售名称
	sellNameMap := services.GetSellNameMapByCompanyIds(sellerCompanyIds)
	for k, v := range list1 {
		list1[k].SellerName = sellNameMap[v.CompanyId]
	}
	for k, v := range list2 {
		list2[k].SellerName = sellNameMap[v.CompanyId]
	}
	mobileStr = ""
	for k, v := range list3 {
		if v.FirstMeetingTime == "0000-00-00 00:00:00" {
			list3[k].FirstMeetingTime = ""
			list3[k].LastMeetingTime = ""
		}
		if v.Mobile != "" {
			mobileStr += v.Mobile + ","
		}
	}
	mapRemark := make(map[string]string)
	if isProhibit {
		list3 = make([]*cygx.AttendanceDetail, 0)
	} else {
		mobileStr = strings.TrimRight(mobileStr, ",")
		if mobileStr != "" {
			listRemark, err := cygx.GetCygxActivityUserRemarksLlistByActivityId(mobileStr, activityId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取信息失败"
				br.ErrMsg = "获取备注信息失败,Err:" + err.Error()
				return
			}
			for _, v := range listRemark {
				if mapRemark[v.Mobile] == "" {
					mapRemark[v.Mobile] = v.Content
				}
			}
			for k, v := range list3 {
				if mapRemark[v.Mobile] != "" {
					list3[k].Content = mapRemark[v.Mobile]
				}
			}
		}
	}

	//添加浏览记录
	item := new(cygx.CygxActivityMeetingHistory)
	item.ActivityId = activityId
	item.AdminId = sysUser.AdminId
	item.RealName = sysUser.RealName
	item.RoleTypeCode = sysUser.RoleTypeCode
	item.CreateTime = time.Now()
	err = cygx.AddCygxActivityMeetingHistory(item)
	resplist := new(cygx.AttendanceDetailList)
	if resp.IsCanDownload == false {
		//var conditionMobile string
		//if adminInfo.RoleTypeCode == "rai_group" {
		//	//组长查看本组所有组员
		//	conditionMobile = ` SELECT mobile 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 {
		//	//组员查看自己
		//	conditionMobile = ` SELECT mobile FROM user_seller_relation WHERE seller_id  = ` + strconv.Itoa(sysUser.AdminId)
		//}
		//mobileList, err := cygx.GetSellerUserMobile(conditionMobile)
		//if err != nil {
		//	br.Msg = "获取失败"
		//	br.ErrMsg = "获取失败，GetSellerUserMobile Err:" + err.Error()
		//	return
		//}
		mapUserMobile, err := cygxService.GetAdminLookUserMobile(adminInfo)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,销售对应权限，Err:" + err.Error()
			return
		}
		//mapUserMobile := make(map[string]string)
		//for _, v := range mobileList {
		//	mapUserMobile[v.Mobile] = v.Mobile
		//}
		for _, v := range list1 {
			if _, ok := mapUserMobile[v.Mobile]; ok {
				resplist.List1 = append(resplist.List1, v)
			}
		}
		for _, v := range list2 {
			if _, ok := mapUserMobile[v.Mobile]; ok {
				resplist.List2 = append(resplist.List2, v)
			}
		}
	} else {
		resplist.List1 = list1
		resplist.List2 = list2
	}
	resplist.List3 = list3
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resplist
}

// @Title 线上活动进门财经关联匹配列表
// @Description 获取线上活动进门财经关联匹配列表接口
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success 200 {object} cygx.RoadshowDataTitleList
// @router /activityMeet/matchingList [get]
func (this *ActivityMeetCoAntroller) MatchingList() {
	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
	}
	keyWord := this.GetString("KeyWord")
	if keyWord == "" {
		br.Msg = "请输入搜索内容"
		return
	}
	list, err := cygx.GetRoadshowDataTitleList(keyWord)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	resplist := new(cygx.RoadshowDataTitleList)
	for k, v := range list {
		list[k].ActivityTime = utils.StrTimeToTime(v.ActivityTime).Format(utils.FormatDate)
		nameSlice := strings.Split(v.RoadshowTitle, "|")
		var activityName string
		if len(nameSlice) > 1 {
			activityName = nameSlice[len(nameSlice)-1]
			//activityName = strings.Replace(activityName, " ", "", -1)
		}
		if activityName != "" {
			list[k].RoadshowTitle = activityName
		}
	}
	resplist.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resplist
}

// @Title 手动匹配线上客户参会记录
// @Description 手动匹配线上客户参会记录接口
// @Param	request	body cygx.RoadshowDataTitleResp true "type json string"
// @Success 200 操作成功
// @router /activityMeet/matchingByHand [post]
func (this *ActivityMeetCoAntroller) MatchingByHand() {
	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
	}
	var req cygx.RoadshowDataTitleResp
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	var mobileStr string
	var userIdArr []int
	activityId := req.ActivityId
	keyWord := req.KeyWord
	slice := strings.Split(keyWord, "{|}")
	detail, err := cygx.GetAddActivityInfoById(activityId)
	if err != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
		return
	}
	//校验活动后台管理员、销售是否有修改权限
	havePower, popupMsg, err := cygxService.CheckActivityUpdatePower(AdminUser.AdminId, detail)
	if err != nil {
		br.Msg = "获取管理员身份信息失败"
		br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
		return
	}
	if !havePower {
		br.Msg = popupMsg
		return
	}
	var condition string
	dateTime := detail.ActivityTime
	dateTime = utils.TimeRemoveHms(dateTime)
	condition += ` AND roadshow_begin_time >= ` + "'" + dateTime + " 00:00:00'"
	condition += ` AND roadshow_begin_time  <= ` + "'" + dateTime + " 23:59:59'"
	if len(slice) > 0 {
		keyWord = slice[0]
	}
	if keyWord != "" {
		list, err := cygx.GetRoadshowDataList(keyWord, condition)
		if err != nil {
			br.Msg = "手动归类失败"
			br.ErrMsg = "获取进门财经数据失败，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
			return
		}
		var roadshowId string
		for _, v := range list {
			if v.RoadshowId != "" {
				roadshowId = v.RoadshowId
				break
			}
		}
		needAddAttendanc := make([]*cygx.CygxActivityAttendanceDetail, 0)
		if len(list) > 0 {
			err = cygx.UpdateActivityRoadshowTitle(activityId, keyWord, roadshowId)
			if err != nil {
				br.Msg = "手动归类失败"
				br.ErrMsg = "关联匹配类型失败，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
				return
			}
			for _, v := range list {
				if v.UserPhone != "" {
					item := new(cygx.CygxActivityAttendanceDetail)
					item.ActivityId = activityId
					item.RealName = v.UserName
					item.Mobile = v.UserPhone
					item.CompanyName = v.Company
					//item.SellerName = sellerName
					item.FirstMeetingTime = v.FirstWatchTime
					item.LastMeetingTime = v.LastWatchTime
					item.Duration = utils.GetAttendanceDetailSeconds(v.JoinTime)
					if v.JoinType == 1 {
						item.MeetingTypeStr = "网络"
					} else {
						item.MeetingTypeStr = "电话"
					}
					item.MeetingAuthentication = v.AuthInfo
					if v.DataType == 1 {
						item.MeetingStatusStr = "直播"
					} else {
						item.MeetingStatusStr = "回放"
					}
					item.Position = v.Occupation
					item.UseridEntity = v.UseridEntity
					item.CrmCompanyMapStatusId = v.CrmCompanyMapStatusId
					item.CreateTime = time.Now()
					mobileStr += "'" + v.UserPhone + "'" + ","

					needAddAttendanc = append(needAddAttendanc, item)
				}
			}
			mobileStr = strings.TrimRight(mobileStr, ",")
			if mobileStr == "" {
				mobileStr = "1"
			}
			listUser, err := cygx.GetWxUserOutboundMobile(mobileStr)
			if err != nil {
				br.Msg = "手动归类失败！"
				br.ErrMsg = "获取用户列表失败，Err:" + err.Error()
				return
			}
			for _, v := range listUser {
				userIdArr = append(userIdArr, v.UserId)
			}

			for k, v := range needAddAttendanc {
				for _, v2 := range listUser {
					if v2.OutboundMobile == v.Mobile {
						needAddAttendanc[k].CompanyId = v2.CompanyId
						needAddAttendanc[k].SellerName = v2.SellerName
						needAddAttendanc[k].CompanyName = v2.CompanyName
						needAddAttendanc[k].IsMeetingStr = 1
					}
				}
			}
			err = cygx.AddAttendancDetail(needAddAttendanc, activityId, mobileStr)
			if err != nil {
				br.Msg = "手动归类失败"
				br.ErrMsg = "手动归类失败，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
				return
			}
			go cygxService.AddCygxActivityRestrictSignupByAdmin(activityId)
			go cygx.AddCygxActivityMeetDetailLogOnline(needAddAttendanc, activityId)
			go cygxService.ActivityUserLabelLogAdd(activityId, userIdArr)                 //添加用户活动到会标签到Redis
			go cygxService.AddctivitySignupDetailListByHand(needAddAttendanc, activityId) //手动匹配进门财经信息
		} else {
			br.Msg = "手动归类失败"
			br.ErrMsg = "暂未找到匹配数据！"
			return
		}
	}
	//添加操作日志记录

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 下载客户参会记录
// @Description 下载客户参会记录接口
// @Param   CompanyId   query   int  true       "公司ID"
// @Param   MeetType   query   int  true       "参会方式 1线上，2线下 默认为线上"
// @Success Ret=200
// @router /activityMeet/companyHistory [get]
func (this *ActivityMeetCoAntroller) CompanyHisory() {
	br := new(models.BaseResponse).Init()
	var err error
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
		if err != nil {
			go alarm_msg.SendAlarmMsg("URI:"+this.Ctx.Input.URI()+"<br/> "+"下载客户参会记录失败"+err.Error(), 3)
		}
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	companyId, _ := this.GetInt("CompanyId")
	meetType, _ := this.GetInt("MeetType")
	if companyId < 1 {
		br.Msg = "请输入公司ID"
		return
	}

	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	var isCanDownload bool
	adminInfo, err := system.GetSysUserById(sysUser.AdminId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if adminInfo.Role == "admin" || strings.Index(adminInfo.RoleTypeCode, "rai") > -1 {
		isCanDownload = true
	}
	if !isCanDownload {
		br.Msg = "暂无下载权限"
		return
	}

	//获取企业客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取企业客户信息失败，Err:" + err.Error()
		return
	}
	var list []*cygx.CompanyMeetRep
	mobiles, err := models.GetCompanyUserMobilesByCompanyId(companyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
		return
	}
	var meetTypeName string
	if mobiles != "" {
		mobiles = strings.Replace(mobiles, ",", "','", -1)
		mobiles = "'" + mobiles + "'"
		if meetType != 2 {
			list, err = cygx.GetCygxActivityAttendanceDetailByCompanyId(mobiles)
			meetTypeName = "线上"
		} else {
			list, err = cygx.GetCygxActivityOfflineMeetingDetailByCompanyId(mobiles)
			meetTypeName = "线下"
		}
	}
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户信息失败,Err:" + err.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(meetTypeName + "参会记录统计")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "手机号/邮箱"
	cellC := rowTitle.AddCell()
	cellC.Value = "活动名称"
	cellD := rowTitle.AddCell()
	cellD.Value = "所属行业"
	cellE := rowTitle.AddCell()
	cellE.Value = "活动类型"
	cellF := rowTitle.AddCell()
	cellF.Value = "活动主题"
	cellG := rowTitle.AddCell()
	cellG.Value = "活动时间"
	if meetType != 2 {
		cellH := rowTitle.AddCell()
		cellH.Value = "首次入会时间"
		cellI := rowTitle.AddCell()
		cellI.Value = "最后退出时间"
		cellJ := rowTitle.AddCell()
		cellJ.Value = "参与总时长"
		cellK := rowTitle.AddCell()
		cellK.Value = "参会方式"
		cellL := rowTitle.AddCell()
		cellL.Value = "参会鉴权"
		cellM := rowTitle.AddCell()
		cellM.Value = "参会状态"
	}

	for _, item := range list {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.Mobile
		if item.Mobile == "" {
			cellB.Value = item.Email
		}
		cellC := row.AddCell()
		cellC.Value = item.ActivityName
		cellD := row.AddCell()
		cellD.Value = item.ChartPermissionName
		cellE := row.AddCell()
		cellE.Value = item.ActivityTypeName
		cellF := row.AddCell()
		cellF.Value = item.Label
		cellG := row.AddCell()
		cellG.Value = item.ActivityTime
		cellH := row.AddCell()

		if meetType != 2 {
			cellH.Value = item.FirstMeetingTime
			cellI := row.AddCell()
			cellI.Value = item.LastMeetingTime
			cellJ := row.AddCell()
			cellJ.Value = item.Duration
			cellK := row.AddCell()
			cellK.Value = item.MeetingTypeStr
			cellL := row.AddCell()
			cellL.Value = item.MeetingAuthentication
			cellM := row.AddCell()
			cellM.Value = item.MeetingStatusStr
		}
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := companyInfo.CompanyName + meetTypeName + "参会记录" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	//添加操作日志记录

	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
	br.IsAddLog = true
}

// @Title 下载客户参会月度统计记录
// @Description 下载客户参会月度统计记录接口
// @Param   CompanyId   query   int  true       "公司ID"
// @Param   MeetType   query   int  true       "参会方式 1线上，2线下 默认为线上"
// @Success Ret=200
// @router /activityMeet/companyCoount [get]
func (this *ActivityMeetCoAntroller) CompanyCoount() {
	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
	}
	companyId, _ := this.GetInt("CompanyId")
	meetType, _ := this.GetInt("MeetType")
	if companyId < 1 {
		br.Msg = "请输入公司ID"
		return
	}

	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	var isCanDownload bool
	adminInfo, err := system.GetSysUserById(sysUser.AdminId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if adminInfo.Role == "admin" || strings.Index(adminInfo.RoleTypeCode, "rai") > -1 {
		isCanDownload = true
	}
	if !isCanDownload {
		br.Msg = "暂无下载权限"
		return
	}

	//获取企业客户信息
	companyInfo, err := company.GetCompanyById(companyId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取企业客户信息失败，Err:" + err.Error()
		return
	}
	var list []*cygx.CompanyMeetRep

	listDate, err := cygx.GetCompanyAciviytyGroupDate()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	dateMap := make(map[string]int)
	permissionNameMap := make(map[string]int)

	var meetTypeName string
	if meetType != 2 {
		list, err = cygx.GetCompanyActivityCount(companyId)
		meetTypeName = "线上"
	} else {
		list, err = cygx.GetCygxActivityOfflineMeetingCoount(companyId)
		meetTypeName = "线下"
	}
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	for _, v := range list {
		if dateMap[v.ActivityTime] == 0 {
			dateMap[v.ActivityTime] = 1
		} else {
			dateMap[v.ActivityTime] += 1
		}
		if permissionNameMap[v.ActivityTime+v.ChartPermissionName] == 0 {
			permissionNameMap[v.ActivityTime+v.ChartPermissionName] = 1
		} else {
			permissionNameMap[v.ActivityTime+v.ChartPermissionName] += 1
		}
	}

	//创建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
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "月份"
	cellB := rowTitle.AddCell()
	cellB.Value = "总参与量"
	cellC := rowTitle.AddCell()
	cellC.Value = "医药"
	cellD := rowTitle.AddCell()
	cellD.Value = "消费"
	cellE := rowTitle.AddCell()
	cellE.Value = "科技"
	cellF := rowTitle.AddCell()
	cellF.Value = "智造"
	cellG := rowTitle.AddCell()
	cellG.Value = "策略"
	cellH := rowTitle.AddCell()
	cellH.Value = "研选"

	for _, item := range listDate {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.CreateTimes
		cellB := row.AddCell()
		cellB.Value = strconv.Itoa(dateMap[item.CreateTimes])
		cellC := row.AddCell()
		cellC.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"医药"])
		cellD := row.AddCell()
		cellD.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"消费"])
		cellE := row.AddCell()
		cellE.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"科技"])
		cellF := row.AddCell()
		cellF.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"智造"])
		cellG := row.AddCell()
		cellG.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"策略"])
		cellH := row.AddCell()
		cellH.Value = strconv.Itoa(permissionNameMap[item.CreateTimes+"研选"])
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := companyInfo.CompanyName + "活动参与量月度统计(" + meetTypeName + ")" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
	br.IsAddLog = true
}

// @Title 新增备注接口
// @Description 新增备注
// @Param	request	body cygx.ActivityUserRemarksAddReq true "type json string"
// @Success 200 新增成功
// @router /activityMeet/addRemarks [post]
func (this *ActivityMeetCoAntroller) Add() {
	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"
		br.Ret = 408
		return
	}
	var req cygx.ActivityUserRemarksAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Content == "" {
		br.Msg = "请填写内容"
		return
	}
	if req.ActivityId < 1 {
		br.Msg = "请选择活动ID"
		return
	}
	if req.Mobile == "" {
		br.Msg = "手机号不能为空"
		return
	}

	item := new(cygx.CygxActivityUserRemarks)
	item.ActivityId = req.ActivityId
	item.Mobile = req.Mobile
	item.AdminId = sysUser.AdminId
	item.RealName = sysUser.RealName
	item.Content = req.Content
	item.CreateTime = time.Now()
	err = cygx.AddCygxActivityUserRemarks(item)
	if err != nil {
		br.Msg = "新增失败."
		br.ErrMsg = "新增失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// @Title 备注列表
// @Description 备注列表接口
// @Param  Mobile   query   string  true       "手机号"
// @Success 200 {object} cygx.CygxActivityUserRemarksListResp
// @router /activityMeet/remark/list [get]
func (this *ActivityMeetCoAntroller) RemarkList() {
	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"
		br.Ret = 408
		return
	}
	mobile := this.GetString("Mobile")
	if mobile == "" {
		br.Msg = "请输入手机号"
		return
	}
	list, err := cygx.GetCygxActivityUserRemarksLlist(mobile)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取备注信息失败,Err:" + err.Error()
		return
	}
	if len(list) == 0 {
		list = make([]*cygx.CygxActivityUserRemarksResp, 0)
	}
	resp := new(cygx.CygxActivityUserRemarksListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 上传停留时间
// @Description 上传停留时间
// @Param	request	body cygx.CygxActivityMeetingHistoryAddReq true "type json string"
// @Success 200 新增成功
// @router /activityMeet/addStopTime [post]
func (this *ActivityMeetCoAntroller) AddStopTime() {
	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"
		br.Ret = 408
		return
	}
	var req cygx.CygxActivityMeetingHistoryAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	stopTime := req.StopTime
	activityId := req.ActivityId
	if stopTime > 0 {
		detail, err := cygx.GetCygxActivityMeetingHistoryNew(activityId, sysUser.AdminId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取最新消息失败,Err:" + err.Error()
			return
		}
		if detail != nil {
			err = cygx.UpdateActivityMeetingHistoryTime(stopTime, detail.Id)
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// @Title 阅读记录列表
// @Description 阅读记录列表接口
// @Param   ActivityId   query   int  true     "活动ID"
// @Success 200 {object} cygx.CygxActivityMeetingHistoryListResp
// @router /activityMeet/history/list [get]
func (this *ActivityMeetCoAntroller) HistoryList() {
	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"
		br.Ret = 408
		return
	}
	activityId, _ := this.GetInt("ActivityId")
	if activityId < 1 {
		br.Msg = "活动不存在"
		return
	}
	list, err := cygx.GetCygxActivityMeetingHistoryLlist(activityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取备注信息失败,Err:" + err.Error()
		return
	}
	if len(list) == 0 {
		list = make([]*cygx.CygxActivityMeetingHistoryResp, 0)
	}
	resp := new(cygx.CygxActivityMeetingHistoryListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 上传参会表格(易董举办的活动)
// @Description 上传参会表格数据(易董举办的活动)
// @Param   File   query   file  true       "文件"
// @Param   ActivityId   query   int  true     "活动ID"
// @Success 200 Ret=200 导入成功
// @router /activityMeet/importYidong [post]
func (this *ActivityMeetCoAntroller) ImportYidongConduct() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请重新登录"
		return
	}
	file, h, err := this.GetFile("File")
	if err != nil {
		br.Msg = "获取文件失败"
		br.ErrMsg = "获取文件失败，Err:" + err.Error()
		return
	}
	activityId, _ := this.GetInt("ActivityId")
	if activityId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "活动id为0"
		return
	}
	activityInfo, err := cygx.GetAddActivityInfoById(activityId)
	if err != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
		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 != 3 && activityInfo.ActiveState != 2 {
		br.Msg = "任务未开始，请稍后上传"
		return
	}
	if activityInfo.IsYidongConduct == 0 {
		br.Msg = "不属于易董的活动无法上传参会信息！"
		return
	}
	uploadDir := "static/xls"
	err = os.MkdirAll(uploadDir, 766)
	if err != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
		return
	}
	path := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
	defer file.Close()
	err = this.SaveToFile("File", path)
	if err != nil {
		br.Msg = "文件保存失败"
		br.ErrMsg = "文件保存失败，Err:" + err.Error()
		return
	}
	xlFile, err := xlsx.OpenFile(path)
	if err != nil {
		br.Msg = "文件导入失败"
		br.ErrMsg = "文件导入失败，Err:" + err.Error()
		return
	}
	defer func() {
		os.Remove(path)
	}()
	//允许添加的联系人
	needAddAttendanc := make([]*cygx.CygxActivityAttendanceDetail, 0)
	var mobileStr string
	// 遍历sheet页读取
	realNameKey, mobileKey, companyNameKey, positionKey, firstMeetingTimeKey, lastMeetingTimeKey, durationKey, meetingTypeStrKey, meetingAuthenticationKey, meetingStatusStrKey, meetNumKey := -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
	for _, sheet := range xlFile.Sheets {
		//遍历行读取
		maxRow := sheet.MaxRow
		for i := 0; i < maxRow; i++ {
			if i == 0 {
				row := sheet.Row(i)
				cells := row.Cells
				for k, cell := range cells {
					text := cell.String()
					if text == "姓名" {
						realNameKey = k
					}
					if text == "公司" {
						companyNameKey = k
					}
					if text == "职位" {
						positionKey = k
					}
					if text == "手机" {
						mobileKey = k
					}
					if text == "参会方式" {
						meetingTypeStrKey = k
					}
					if text == "参会时长" {
						durationKey = k
					}

					if text == "入会时间" {
						firstMeetingTimeKey = k
					}
					if text == "离会时间" {
						lastMeetingTimeKey = k
					}
					if text == "来源" {
						meetingAuthenticationKey = k
					}
					if text == "参会状态" {
						meetingStatusStrKey = k
					}
					if text == "入会次数" {
						meetNumKey = k
					}
				}
			}
			if i == 0 {
				if mobileKey == -1 {
					br.Msg = "模板格式错误，缺少：电话"
					br.ErrMsg = "模板格式错误"
					return
				}
				if firstMeetingTimeKey == -1 {
					br.Msg = "模板格式错误，缺少：首次入会时间"
					br.ErrMsg = "模板格式错误！"
					return
				}
				if lastMeetingTimeKey == -1 {
					br.Msg = "模板格式错误，缺少：最后退出时间"
					br.ErrMsg = "模板格式错误！"
					return
				}
				if durationKey == -1 {
					br.Msg = "模板格式错误，缺少：参与总时长"
					br.ErrMsg = "模板格式错误！"
					return
				}
			}
			if i >= 1 {
				row := sheet.Row(i)
				cells := row.Cells
				var realName, mobile, companyName, position, sellerName, firstMeetingTime, lastMeetingTime, duration, meetingTypeStr, meetingAuthentication, meetingStatusStr, meetNum string
				for k, cell := range cells {
					if k == realNameKey {
						realName = cell.String()
					}
					if k == mobileKey {
						mobile = cell.String()
					}
					if k == companyNameKey {
						companyName = cell.String()
					}
					if k == positionKey {
						position = cell.String()
					}
					if k == firstMeetingTimeKey {
						firstMeetingTime = cell.String()
					}
					if k == lastMeetingTimeKey {
						lastMeetingTime = cell.String()
					}
					if k == durationKey {
						duration = cell.String()
					}
					if k == meetingTypeStrKey {
						meetingTypeStr = cell.String()
					}
					if k == meetingAuthenticationKey {
						meetingAuthentication = cell.String()
					}
					if k == meetingStatusStrKey {
						meetingStatusStr = cell.String()
					}
					if k == meetNumKey {
						meetNum = cell.String()
					}

				}
				//这些字段都没有的话，系统认为excel到底了
				if duration == "" && mobile == "" && firstMeetingTime == "" {
					break
				}
				item := new(cygx.CygxActivityAttendanceDetail)
				item.ActivityId = activityId
				item.RealName = realName
				item.Mobile = mobile
				item.CompanyName = companyName
				item.SellerName = sellerName
				if meetNum == "1" {
					item.FirstMeetingTime = firstMeetingTime
					item.LastMeetingTime = lastMeetingTime
				}
				item.Duration = duration
				item.MeetingTypeStr = meetingTypeStr
				item.MeetingAuthentication = meetingAuthentication
				item.MeetingStatusStr = meetingStatusStr
				item.Position = position
				item.CreateTime = time.Now()
				if mobile != "" {
					mobileStr += "'" + mobile + "'" + ","
					needAddAttendanc = append(needAddAttendanc, item)
				}
			}
		}
	}

	mobileStr = strings.TrimRight(mobileStr, ",")
	if mobileStr == "" {
		mobileStr = "1"
	}
	//外呼号
	listUser, err := cygx.GetWxUserOutboundMobile(mobileStr)
	if err != nil {
		br.Msg = "手动归类失败！"
		br.ErrMsg = "获取用户列表失败，Err:" + err.Error()
		return
	}
	//手机号
	listUserMobile, err := cygx.GetWxUserMobile(mobileStr)
	if err != nil {
		br.Msg = "手动归类失败！"
		br.ErrMsg = "获取用户列表失败，Err:" + err.Error()
		return
	}

	mapneedAddAttendanc := make(map[string]*cygx.WxUserOutboundMobile)
	for _, v := range listUser {
		mapneedAddAttendanc[v.OutboundMobile] = v
	}

	for _, v := range listUserMobile {
		if mapneedAddAttendanc[v.Mobile] == nil {
			mapneedAddAttendanc[v.Mobile] = v
		}
	}

	for k, v := range needAddAttendanc {
		if mapneedAddAttendanc[v.Mobile] != nil {
			needAddAttendanc[k].CompanyId = mapneedAddAttendanc[v.Mobile].CompanyId
			needAddAttendanc[k].SellerName = mapneedAddAttendanc[v.Mobile].SellerName
			needAddAttendanc[k].CompanyName = mapneedAddAttendanc[v.Mobile].CompanyName
			needAddAttendanc[k].IsMeetingStr = 1
		}
	}

	err = cygx.AddAttendancDetail(needAddAttendanc, activityId, mobileStr)
	if err != nil {
		br.Msg = "手动归类失败"
		br.ErrMsg = "手动归类失败，Err:" + err.Error() + "activityId：" + strconv.Itoa(activityId)
		return
	}
	go cygxService.AddCygxActivityRestrictSignupByAdmin(activityId)
	go cygx.AddCygxActivityMeetDetailLogOnline(needAddAttendanc, activityId)
	br.Msg = "导入成功"
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
}
