package yb

import (
	"errors"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/request"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/services/quanshi"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// AddActivity 添加活动
func AddActivity(req request.AddActivityReq, userId int) (activityInfo *yb.Activity, err error) {
	startTime, err := time.ParseInLocation(utils.FormatDateTime, req.StartTime, time.Local)
	if err != nil {
		err = errors.New(fmt.Sprint("活动开始日期转换失败：", err))
		return
	}
	endTime, err := time.ParseInLocation(utils.FormatDateTime, req.EndTime, time.Local)
	if err != nil {
		err = errors.New(fmt.Sprint("活动结束日期转换失败：", err))
		return
	}

	//是否限制人数
	var isLimitPeople int8
	if req.LimitPeopleNum > 0 {
		isLimitPeople = 1
	}

	//  查询分类详情
	activityType, err := yb.GetActivityTypeListById(req.ActivityTypeId)
	if err != nil {
		return
	}
	firstActivityType, err := yb.GetActivityTypeListById(activityType.Pid)
	if err != nil {
		return
	}

	//活动
	activityInfo = &yb.Activity{
		FirstActivityTypeId:   firstActivityType.ActivityTypeId,
		FirstActivityTypeName: firstActivityType.ActivityTypeName,
		ActivityTypeId:        req.ActivityTypeId,
		ActivityTypeName:      req.ActivityTypeName,
		//ChartPermissionId   int       `description:"对应的权限id，表chart_permission中id"`
		//ChartPermissionName string    `description:"对应的权限名称，表chart_permission中name"`
		ActivityName:         utils.TrimStr(req.ActivityName),
		StartTime:            startTime,
		EndTime:              endTime,
		Speaker:              req.Speaker,
		SpeakerHeadPic:       req.SpeakerHeadPic,
		SpeakerBackgroundPic: getBackgroundPic(firstActivityType.ActivityTypeId),
		MainlandTel:          req.MainlandTel,
		HongKongTel:          req.HongKongTel,
		TaiwanTel:            req.TaiwanTel,
		AmericaTel:           req.AmericaTel,
		SingaporeTel:         req.SingaporeTel,
		ParticipationCode:    req.ParticipationCode,
		LinkParticipants:     req.LinkParticipants,
		IsLimitPeople:        isLimitPeople,
		LimitPeopleNum:       req.LimitPeopleNum,
		ReportId:             req.ReportId,
		ReportLink:           req.ReportLink,
		ReportName:           utils.TrimStr(req.ReportName),
		City:                 req.City,
		Address:              req.Address,
		//VoiceUrl            :req.Vi
		//Remarks             :req.Remarks,
		UserId:        userId,
		PublishStatus: req.PublishStatus,
		//ActiveStatus        int8      `description:"活动进行状态 未开始：1、进行中2、已结束3"`
		IsSendWxMsg:      0,
		IsSendSalonWxMsg: 0,
		//ArticleId           int       `description:"报告链接所关联的文章ID"`
		ModifyTime:  time.Now(),
		CreateTime:  time.Now(),
		IsNewReport: req.IsNewReport,
	}

	//活动海报
	activityPosterList := make([]*yb.ActivityPoster, 0)
	for _, v := range req.PosterList {
		tmpPoster := &yb.ActivityPoster{
			//ActivityId: activityInfo.ActivityId,
			Url:        v.Url,
			Name:       v.Name,
			CreateTime: time.Now(),
		}
		activityPosterList = append(activityPosterList, tmpPoster)
	}

	// 权限列表
	activityPermissionList := make([]*yb.ActivityPermission, 0)
	permissionIdList := make([]int, 0)
	if activityInfo.FirstActivityTypeId == 1 { //电话会这种，直接从数据库里面读取权限配置
		activityType, tmpErr := yb.GetActivityTypeListById(activityInfo.ActivityTypeId)
		if tmpErr != nil {
			err = fmt.Errorf("查询分类权限失败,Err：", tmpErr)
			return
		}
		if activityType.ChartPermissionId != "" {
			permissionIds := strings.Split(activityType.ChartPermissionId, ",")
			for _, val := range permissionIds {
				permissionId, _ := strconv.Atoi(val)
				permissionIdList = append(permissionIdList, permissionId)
			}
		}
	} else {
		permissionIdList = req.PermissionIdList
	}
	if len(permissionIdList) > 0 {
		permissionList, tmpErr := company.GetChartPermissionListByIds(permissionIdList)
		if tmpErr != nil {
			err = fmt.Errorf("查询权限失败,Err：", tmpErr)
			return
		}
		for _, v := range permissionList {
			tmpPermission := &yb.ActivityPermission{
				PermissionId:   v.ChartPermissionId,
				PermissionName: v.PermissionName,
				CreateTime:     time.Now(),
			}
			activityPermissionList = append(activityPermissionList, tmpPermission)
		}
	}

	//新增活动
	err = yb.AddNewActivity(activityInfo, activityPosterList, activityPermissionList)

	//推送报告给同花顺
	//if activityInfo.ReportLink != `` && activityInfo.PublishStatus == 1 {
	//	go services.SendActivityToThs(activityInfo)
	//}
	return
}

// EditActivity 编辑活动
func EditActivity(req request.EditActivityReq) (activityInfo *yb.Activity, err error, errMsg string) {
	startTime, err := time.ParseInLocation(utils.FormatDateTime, req.StartTime, time.Local)
	if err != nil {
		err = errors.New(fmt.Sprint("活动开始日期转换失败：", err))
		return
	}
	endTime, err := time.ParseInLocation(utils.FormatDateTime, req.EndTime, time.Local)
	if err != nil {
		err = errors.New(fmt.Sprint("活动结束日期转换失败：", err))
		return
	}

	activityInfo, err = yb.GetById(req.ActivityId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "找不到该活动"
		}
		return
	}

	oldActivityInfo := *activityInfo //修改前的数据

	// 活动已结束去除所有时间限制
	now := time.Now()
	if oldActivityInfo.EndTime.After(now) {
		/*if now.After(startTime) {
			err = errors.New(fmt.Sprint("活动时间不允许小于当前时间!", err))
			errMsg = "活动时间不允许小于当前时间!"
			return
		}*/
		if startTime.After(endTime) {
			err = errors.New(fmt.Sprint("活动结束时间不允许小于开始时间!", err))
			errMsg = "活动结束时间不允许小于开始时间!"
			return
		}
		allowEndTime := startTime.Add(30 * time.Minute)
		if allowEndTime.After(endTime) {
			err = errors.New(fmt.Sprint("活动结束时间至少要在开始时间半个小时之后!", err))
			errMsg = "活动结束时间至少要在开始时间半个小时之后!"
			return
		}
	}

	//是否限制人数
	var isLimitPeople int8
	if req.LimitPeopleNum > 0 {
		isLimitPeople = 1
	}
	req.ReportLink = utils.TrimStr(req.ReportLink)

	updateCols := make([]string, 0)

	activityInfo.ActivityName = utils.TrimStr(req.ActivityName)
	activityInfo.StartTime = startTime
	activityInfo.EndTime = endTime
	activityInfo.Speaker = req.Speaker
	activityInfo.SpeakerHeadPic = req.SpeakerHeadPic
	activityInfo.SpeakerBackgroundPic = getBackgroundPic(activityInfo.FirstActivityTypeId)
	activityInfo.MainlandTel = req.MainlandTel
	activityInfo.HongKongTel = req.HongKongTel
	activityInfo.TaiwanTel = req.TaiwanTel
	activityInfo.AmericaTel = req.AmericaTel
	activityInfo.SingaporeTel = req.SingaporeTel
	activityInfo.ParticipationCode = req.ParticipationCode
	activityInfo.LinkParticipants = req.LinkParticipants
	activityInfo.IsLimitPeople = isLimitPeople
	activityInfo.ReportId = req.ReportId
	activityInfo.LimitPeopleNum = req.LimitPeopleNum
	activityInfo.ReportLink = req.ReportLink
	activityInfo.ReportName = utils.TrimStr(req.ReportName)
	activityInfo.City = req.City
	activityInfo.Address = req.Address
	////VoiceUrl            :req.Vi
	activityInfo.Remarks = req.Remarks
	activityInfo.IsNewReport = req.IsNewReport
	//发布
	if req.PublishStatus >= 1 {
		activityInfo.PublishStatus = req.PublishStatus
		updateCols = append(updateCols, "PublishStatus")
	}
	activityInfo.ModifyTime = time.Now()
	////ActiveStatus        int8      `description:"活动进行状态 未开始：1、进行中2、已结束3"`
	////ArticleId           int       `description:"报告链接所关联的文章ID"`

	//更新
	updateCols = append(updateCols, "ActivityName", "StartTime", "EndTime", "Speaker", "SpeakerHeadPic", "SpeakerBackgroundPic", "MainlandTel", "HongKongTel", "TaiwanTel", "AmericaTel", "SingaporeTel", "ParticipationCode", "LinkParticipants", "IsLimitPeople", "LimitPeopleNum", "ReportLink", "ReportName", "ReportId", "City", "Address", "Remarks", "ModifyTime", "IsNewReport")

	//插入新的海报文件
	activityPosterList := make([]*yb.ActivityPoster, 0)
	for _, v := range req.PosterList {
		tmpPoster := &yb.ActivityPoster{
			ActivityId: activityInfo.ActivityId,
			Url:        v.Url,
			Name:       v.Name,
			CreateTime: time.Now(),
		}
		activityPosterList = append(activityPosterList, tmpPoster)
	}

	//插入新的音频文件
	activityVoiceList := make([]*yb.ActivityVoice, 0)
	for _, v := range req.VoiceList {
		tmpVoice := &yb.ActivityVoice{
			ActivityId:       activityInfo.ActivityId,
			VoiceUrl:         v.Url,
			VoiceName:        v.Name,
			VoicePlaySeconds: v.PlaySeconds,
			CreateTime:       time.Now(),
		}
		activityVoiceList = append(activityVoiceList, tmpVoice)
	}

	// 权限列表
	activityPermissionList := make([]*yb.ActivityPermission, 0)
	permissionIdList := make([]int, 0)
	if activityInfo.FirstActivityTypeId == 1 { //电话会这种，直接从数据库里面读取权限配置
		activityType, tmpErr := yb.GetActivityTypeListById(activityInfo.ActivityTypeId)
		if tmpErr != nil {
			err = fmt.Errorf("查询分类权限失败,Err：", tmpErr)
			return
		}
		if activityType.ChartPermissionId != "" {
			permissionIds := strings.Split(activityType.ChartPermissionId, ",")
			for _, val := range permissionIds {
				permissionId, _ := strconv.Atoi(val)
				permissionIdList = append(permissionIdList, permissionId)
			}
		}
	} else {
		permissionIdList = req.PermissionIdList
	}
	if len(permissionIdList) > 0 {
		permissionList, tmpErr := company.GetChartPermissionListByIds(permissionIdList)
		if tmpErr != nil {
			err = fmt.Errorf("查询权限失败,Err：", tmpErr)
			return
		}
		for _, v := range permissionList {
			tmpPermission := &yb.ActivityPermission{
				ActivityId:     activityInfo.ActivityId,
				PermissionId:   v.ChartPermissionId,
				PermissionName: v.PermissionName,
				CreateTime:     time.Now(),
			}
			activityPermissionList = append(activityPermissionList, tmpPermission)
		}
	}

	err = activityInfo.UpdateActivity(updateCols, activityPosterList, activityVoiceList, activityPermissionList)
	if err != nil {
		return
	}

	//变更提醒（活动已经发布了）
	if oldActivityInfo.PublishStatus >= 1 {
		go sendWxMsg(oldActivityInfo, activityInfo)
	}

	//推送报告给同花顺
	//if activityInfo.ReportLink != `` && activityInfo.PublishStatus == 1 {
	//	go services.SendActivityToThs(activityInfo)
	//}

	// 如果开始时间/活动标题有过变更，那么需要去修改全时会议
	if !oldActivityInfo.StartTime.Equal(activityInfo.StartTime) || oldActivityInfo.ActivityName != activityInfo.ActivityName {
		go updateQsEvent(activityInfo)
	}
	return
}

// PublishActivity 发布活动
func PublishActivity(activityId int) (activityInfo *yb.Activity, err error, errMsg string) {
	activityInfo, err = yb.GetById(activityId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "找不到该活动"
		}
		return
	}

	if activityInfo.PublishStatus == 1 {
		err = errors.New("该活动已发布")
		errMsg = "该活动已发布"
		return
	}

	updateCols := make([]string, 0)
	//发布
	activityInfo.PublishStatus = 1
	activityInfo.ModifyTime = time.Now()
	//更新
	updateCols = append(updateCols, "PublishStatus", "ModifyTime")
	err = activityInfo.Update(updateCols)

	//推送同花顺报告
	//if activityInfo.ReportLink != `` && activityInfo.PublishStatus == 1 {
	//	go services.SendActivityToThs(activityInfo)
	//}
	return
}

// UnPublishActivity 取消发布活动
func UnPublishActivity(activityId int) (activityInfo *yb.Activity, err error, errMsg string) {
	activityInfo, err = yb.GetById(activityId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "找不到该活动"
		}
		return
	}

	if activityInfo.PublishStatus == 0 {
		err = errors.New("该活动未发布")
		errMsg = "该活动未发布"
		return
	}

	oldActivityInfo := *activityInfo

	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 1.取消发布活动
	activityInfo.PublishStatus = 0
	activityInfo.ModifyTime = time.Now()
	updateCols := make([]string, 0)
	updateCols = append(updateCols, "PublishStatus", "ModifyTime")
	err = activityInfo.Update(updateCols)
	if err != nil {
		err = errors.New("取消发布失败")
		errMsg = "取消发布失败"
		return
	}

	// 2.更新该活动所有报名为取消报名
	err = yb.CancelActivityRegisters(activityId)
	if err != nil {
		err = errors.New("取消报名信息失败")
		errMsg = "取消报名信息失败"
		return
	}

	// 3.清除所有活动提醒
	err = yb.DelActivityReminds(activityId)
	if err != nil {
		err = errors.New("清除活动提醒失败")
		errMsg = "清除活动提醒失败"
		return
	}

	// 4.变更提醒
	go sendWxMsg(oldActivityInfo, activityInfo)

	// 取消全时会议
	go cancelQsEvent(activityInfo)

	return
}

// DelActivity 删除活动
func DelActivity(activityId int) (activityInfo *yb.Activity, err error, errMsg string) {
	activityInfo, err = yb.GetById(activityId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "找不到该活动"
		}
		return
	}

	if activityInfo.IsDelete == 1 {
		err = errors.New("该活动不存在")
		errMsg = "该活动不存在"
		return
	}

	updateCols := make([]string, 0)
	//发布
	activityInfo.IsDelete = 1
	activityInfo.ModifyTime = time.Now()
	//更新
	updateCols = append(updateCols, "IsDelete", "ModifyTime")
	err = activityInfo.Update(updateCols)

	return
}

// sendWxMsg 发送微信消息
func sendWxMsg(oldActivityInfo yb.Activity, activityInfo *yb.Activity) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "发送电话会提醒失败 ErrMsg:"+err.Error())
			//go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "发送电话会提醒失败 ErrMsg:"+err.Error(), utils.EmailSendToUsers)
		}
	}()

	// 如果活动结束时间小于现在，那么也不提醒
	if activityInfo.EndTime.Before(time.Now()) {
		return
	}

	//不是我们主持的会议或者沙龙，那么就不通知
	if activityInfo.FirstActivityTypeId != 1 && activityInfo.FirstActivityTypeId != 3 {
		return
	}

	var isUpdateTime, isUpdateAddress, isCancel bool //是否更改时间，是否更改地址
	if activityInfo.StartTime != oldActivityInfo.StartTime || activityInfo.EndTime != oldActivityInfo.EndTime {
		isUpdateTime = true
	}
	if activityInfo.Address != oldActivityInfo.Address {
		isUpdateAddress = true
	}
	//活动取消
	if activityInfo.PublishStatus != oldActivityInfo.PublishStatus && activityInfo.PublishStatus == 0 {
		isCancel = true
	}
	//您有一场【橡胶双周报】发生了时间变更
	firstUpdateStr := ""
	detailUpdateStr := ``
	if isUpdateTime && isUpdateAddress {
		firstUpdateStr = `发生了时间变更、活动地址变更`
		detailUpdateStr = `原定时间【` + formatActivityTimeStr(oldActivityInfo.StartTime, oldActivityInfo.EndTime) + `】变更为【` + formatActivityTimeStr(activityInfo.StartTime, activityInfo.EndTime) + `】，原定活动地址【` + oldActivityInfo.Address + `】变更为【` + activityInfo.Address + `】`
	} else if isUpdateTime {
		firstUpdateStr = `发生了时间变更`
		detailUpdateStr = `原定时间【` + formatActivityTimeStr(oldActivityInfo.StartTime, oldActivityInfo.EndTime) + `】变更为【` + formatActivityTimeStr(activityInfo.StartTime, activityInfo.EndTime) + `】`
	} else if isUpdateAddress {
		firstUpdateStr = `发生了活动地址变更`
		detailUpdateStr = `原定活动地址【` + oldActivityInfo.Address + `】变更为【` + activityInfo.Address + `】`
	} else if isCancel {
		firstUpdateStr = `已取消`
		detailUpdateStr = `已取消`
	} else {
		return
	}

	//您有一场【橡胶双周报】将在15分钟后开始
	userIdList := make([]string, 0) //提醒用户列表

	//电话会
	if activityInfo.FirstActivityTypeId == 1 {
		list, tmpErr := yb.GetAllActivityRemindListByActivityId(activityInfo.ActivityId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range list {
			userIdList = append(userIdList, fmt.Sprint(v.UserId))
		}
	} else { //沙龙
		//提醒
		list, tmpErr := yb.GetAllActivityRemindListByActivityId(activityInfo.ActivityId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range list {
			userIdList = append(userIdList, fmt.Sprint(v.UserId))
		}

		//线下报名
		list2, tmpErr := yb.GetAllActivityRegisterListByActivityId(activityInfo.ActivityId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range list2 {
			userIdList = append(userIdList, fmt.Sprint(v.UserId))
		}
	}

	if len(userIdList) <= 0 {
		return
	}

	first := `您有一场【` + activityInfo.ActivityTypeName + `】` + firstUpdateStr
	keyword1 := activityInfo.ActivityName
	keyword2 := detailUpdateStr
	remark := ``
	//小程序跳转地址
	wxAppPath := ``

	//如果不是已取消，那么需要让他跳转到详情
	if !isCancel {
		wxAppPath = `pages-activity/detail?id=` + fmt.Sprint(activityInfo.ActivityId)
		remark = `点击查看活动详情`
	}

	//由于测试环境小程序没有发布，模板消息设置了小程序跳转地址，会导致模板消息发送失败
	if utils.RunMode == `debug` {
		wxAppPath = ``
	}

	//获取所有用户的openid列表
	openidList, err := models.GetUserOpenidListByUserIds(userIdList)
	if err != nil {
		return
	}
	err = services.SendWxMsgWithActivityAppointmentRemind(first, keyword1, keyword2, remark, wxAppPath, openidList)
	return
}

// formatActivityTimeStr 格式化活动的开始结束时间
func formatActivityTimeStr(startTime, endTime time.Time) string {
	startStr := startTime.Format("2006-01-02 15:04")
	endStr := endTime.Format("15:04")
	weekStr := ``
	weekInt := startTime.Weekday()
	switch weekInt {
	case 0:
		weekStr = `星期日`
	case 1:
		weekStr = `星期一`
	case 2:
		weekStr = `星期二`
	case 3:
		weekStr = `星期三`
	case 4:
		weekStr = `星期四`
	case 5:
		weekStr = `星期五`
	case 6:
		weekStr = `星期六`
	}

	return startStr + `-` + endStr + ` ` + weekStr
}

// getBackgroundPic 获取活动背景图
func getBackgroundPic(typeId int) (pic string) {
	if typeId <= 2 {
		//电话会议
		pic = `https://hongze.oss-accelerate.aliyuncs.com/static/images/202112/20211214/nNSTxmH6lxlT0PAp7xcfJJTGX9Gu.png`
	} else {
		//线下沙龙
		pic = `https://hongze.oss-accelerate.aliyuncs.com/static/images/202112/20211214/k77gDxvFvuAnYUhF6PU1FOVDHI8O.png`
	}
	return
}

// CreateQsEvent 创建全时会议
func CreateQsEvent(req request.CreateQsReq) (err error, errMsg string) {
	activityInfo, err := yb.GetById(req.ActivityId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "活动信息不存在"
		} else {
			errMsg = "活动详情获取失败"
		}
		return
	}

	//获取最近一条全时会议信息
	qsEventInfo, err := yb.GetLastQsEventByActivityId(req.ActivityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		errMsg = "获取全时信息异常！"
		return
	}
	if qsEventInfo != nil {
		if qsEventInfo.Status == 1 {
			errMsg = "全时会议已创建，请勿重复创建！"
			return
		} else if qsEventInfo.Status == 2 {
			qsEventInfo = nil
		}
	}

	//创建全时会议
	startTime := activityInfo.StartTime
	if startTime.Before(time.Now()) { //如果开始时间早于现在，那么就以现在的时间往后推迟10s作为会议开始时间
		startTime = time.Now().Add(10 * time.Second)
	}

	paramStr := fmt.Sprintf(`activity_id=%d&time=%d`, activityInfo.ActivityId, time.Now().Unix())
	signStr := quanshi.GetSign(paramStr)
	paramStr += `&sign=` + signStr

	callbackUrl := `http://8.136.199.33:8608/api/quanshi/callback?` + paramStr
	if utils.RunMode == "release" {
		callbackUrl = `https://openapi.hzinsights.com/api/quanshi/callback?` + paramStr
	}

	qsResp, err := quanshi.QsEventCreate(activityInfo.ActivityName, req.Time, 1, startTime, callbackUrl)
	if err != nil {
		errMsg = "请求全时接口异常"
		return
	}

	if qsEventInfo != nil {
		qsEventInfo.QsEventId = int(qsResp.EventID)
		qsEventInfo.StartTime = startTime
		qsEventInfo.EndTime = startTime.Add(time.Duration(req.Time*60) * time.Second)
		qsEventInfo.ModifyTime = time.Now()
		qsEventInfo.Status = 1
		err = qsEventInfo.Update([]string{"QsEventId", "StartTime", "EndTime", "ModifyTime", "Status"})

	} else {
		qsEventInfo = &yb.QsEvent{
			YbActivityId: req.ActivityId,
			QsEventId:    int(qsResp.EventID),
			StartTime:    startTime,
			EndTime:      startTime.Add(time.Duration(req.Time*60) * time.Second),
			Time:         req.Time,
			Status:       1,
			ModifyTime:   time.Now(),
			CreateTime:   time.Now(),
		}
		err = yb.AddQsEvent(qsEventInfo)
	}
	if err != nil {
		go alarm_msg.SendAlarmMsg("全时会议创建成功，变更全时记录表信息失败；ERR："+err.Error(), 3)
		errMsg = "保存活动失败！"
		return
	}

	//变更参会信息
	activityInfo.HostCode = qsResp.Pcode1
	activityInfo.ParticipationCode = qsResp.Pcode2
	activityInfo.LinkParticipants = qsResp.AttendeeJoinURL
	activityInfo.QsId = qsEventInfo.QsId
	err = activityInfo.Update([]string{"HostCode", "ParticipationCode", "LinkParticipants", "QsId"})
	if err != nil {
		go alarm_msg.SendAlarmMsg("全时会议创建成功，变更参会信息失败；ERR："+err.Error(), 3)
	}
	return
}

// CancelQsEvent 取消全时会议
func CancelQsEvent(activityId int) (err error, errMsg string) {
	activityInfo, err := yb.GetById(activityId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			errMsg = "找不到该活动！"
		} else {
			errMsg = "获取活动信息异常！"
		}
		return
	}
	err, errMsg = cancelQsEvent(activityInfo)
	return
}

// cancelQsEvent 取消全时会议
func cancelQsEvent(activityInfo *yb.Activity) (err error, errMsg string) {
	qsEventInfo, err := yb.GetQsEventByActivityId(activityInfo.ActivityId)
	if err != nil {
		errMsg = "获取全时信息异常！"
		return
	}

	//取消全时会议
	err = quanshi.QsEventCancel(qsEventInfo.QsEventId)
	if err != nil {
		errMsg = "取消全时会议失败！"
		return
	}

	//变更全时会议同步状态
	qsEventInfo.Status = 2
	err = qsEventInfo.Update([]string{"Status"})
	if err != nil {
		errMsg = "取消会议失败！"
		return
	}

	//变更活动关联关系id
	activityInfo.QsId = 0
	activityInfo.HostCode = ""
	activityInfo.ParticipationCode = ""
	activityInfo.LinkParticipants = ""
	err = activityInfo.Update([]string{"QsId", "HostCode", "ParticipationCode", "LinkParticipants"})
	if err != nil {
		errMsg = "取消会议失败！"
		return
	}
	return
}

// updateQsEvent 修改全时会议
func updateQsEvent(activityInfo *yb.Activity) (err error, errMsg string) {
	//获取最近一条全时会议信息
	qsEventInfo, err := yb.GetLastQsEventByActivityId(activityInfo.ActivityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		errMsg = "获取全时信息异常！"
		return
	}
	if qsEventInfo == nil {
		errMsg = "没有创建全时会议！"
		err = errors.New("没有创建全时会议")
		return
	}
	//变更全时会议信息
	startTime := activityInfo.StartTime
	if startTime.Before(time.Now()) { //如果开始时间早于现在，那么就以现在的时间往后推迟10s作为会议开始时间
		startTime = time.Now().Add(10)
	}
	_, err = quanshi.QsEventUpdate(qsEventInfo.QsEventId, qsEventInfo.Time, activityInfo.ActivityName, startTime)
	if err != nil {
		errMsg = "请求全时接口异常"
		return
	}
	return
}

func SyncUser(qsEventId int) {
	//qsEventId := 6631607
	qsEventInfo, err := yb.GetQsEventByQsEventId(qsEventId)
	if err != nil {
		return
	}

	if qsEventInfo.IsSync == 1 {
		return
	}
	//获取全时的参会人员信息
	qsData, err := quanshi.QsEventReportSummary(qsEventId)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(qsData)

	//获取全时录制的流媒体信息
	qsVideoData, err := quanshi.QsEventReportQueryVideo(int64(qsEventId))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(qsData)

	if qsData.Summary != nil && len(qsData.Summary) > 0 {
		for _, v := range qsData.Summary {
			fmt.Println(v)
			mobile := v.Mobile
			trimMobile := mobile
			countryCode := "86"
			var companyProductInfo *company.CompanyProduct
			var wxUserInfo *models.WxUser
			if mobile != "" {
				trimMobileSlice := strings.Split(v.Mobile, "-")
				lenTrimMobileSlice := len(trimMobileSlice)
				if lenTrimMobileSlice > 1 {
					trimMobile = trimMobileSlice[1]
					countryCode = strings.Replace(trimMobileSlice[0], "+", "", -1)
				}
				fmt.Println(trimMobile)
				fmt.Println(countryCode)
				wxUserInfo, _ = models.GetWxUserByMobileCountryCode(trimMobile, countryCode)
				if wxUserInfo != nil {
					companyProductInfo, _ = company.GetCompanyProductByCompanyIdAndProductId(wxUserInfo.CompanyId, 1)
				}
			}

			qsEventUserInfo := &yb.QsEventUser{
				QsId:   qsEventInfo.QsId,
				UserId: 0,
				Mobile: v.Mobile,
				Email:  v.Email,
				Name:   v.Name,
				//RegisterTime:     time.Time{},
				ViewTotal: 0,
				//LastViewTime:     time.Time{},
				CompanyId:        0,
				ProductId:        0,
				CompanyName:      "",
				Status:           "",
				SellerId:         0,
				SellerName:       "",
				CompanyViewTotal: 0,
				CompanyRoadTotal: 0,
				CreateTime:       time.Now(),
			}
			//这个时候是系统用户了，美滋滋
			if companyProductInfo != nil {
				qsEventUserInfo.RegisterTime = wxUserInfo.RegisterTime

				userViewStatisticsInfo, _ := models.GetUserViewStatisticsByMobile(trimMobile) //用户阅读信息
				if userViewStatisticsInfo != nil {
					qsEventUserInfo.ViewTotal = userViewStatisticsInfo.Total
					qsEventUserInfo.LastViewTime = userViewStatisticsInfo.LastViewTime
				}

				qsEventUserInfo.CompanyId = companyProductInfo.CompanyId
				qsEventUserInfo.ProductId = companyProductInfo.ProductId
				qsEventUserInfo.CompanyName = companyProductInfo.ProductName
				qsEventUserInfo.Status = companyProductInfo.Status
				qsEventUserInfo.SellerId = companyProductInfo.SellerId
				qsEventUserInfo.SellerName = companyProductInfo.SellerName
				qsEventUserInfo.CompanyViewTotal = companyProductInfo.ViewTotal
				qsEventUserInfo.CompanyRoadTotal = companyProductInfo.RoadShowTotal
			}
			_ = yb.AddQsEventUser(qsEventUserInfo)
		}
	}

	videoUrl := ``
	for k, v := range qsVideoData.Records {
		if k == strconv.Itoa(qsEventId) {
			videoUrl = v.VideoURL
		}
	}
	qsEventInfo.VideoUrl = videoUrl
	qsEventInfo.IsSync = 1
	qsEventInfo.QsStatus = 2
	err = qsEventInfo.Update([]string{"VideoUrl", "IsSync"})
}
