package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/models/company"
	"hongze/hongze_cygx/models/roadshow"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
	"time"
)

//func init() {
//	GetActivityPointsAll()
//}

// GetActivityPointsByUserAllMap 获取所有针对用户扣点的活动
func GetActivityPointsByUserAllMap() (mapResp map[int]bool) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("GetActivityPointsByUserAllMap，Err："+err.Error(), 2)
		}
	}()
	var condition string
	var pars []interface{}
	//获取所有研选类型的活动
	condition = `  AND chart_permission_id =   ` + strconv.Itoa(utils.CHART_PERMISSION_ID_YANXUAN)
	listActivity, e := models.GetActivityListByCondition(condition, pars)
	if e != nil {
		err = errors.New("GetActivityListByCondition, Err: " + e.Error())
		return
	}
	var activityIds []int
	condition = ""
	pars = make([]interface{}, 0)
	for _, v := range listActivity {
		activityIds = append(activityIds, v.ActivityId)
	}
	condition += ` AND  points_object  IN  (1,3) `
	condition += ` AND activity_id IN (` + utils.GetOrmInReplace(len(activityIds)) + `)   `
	pars = append(pars, activityIds)
	list, e := models.GetCygxActivityPointsSetList(condition, pars, 0, 0)
	if e != nil {
		err = errors.New("GetCygxActivityPointsSetList, Err: " + e.Error())
		return
	}
	mapResp = make(map[int]bool, 0)
	for _, v := range list {
		mapResp[v.ActivityId] = true
	}
	return
}

// GetActivityPointsAll 获取所有带有扣点的活动
func GetActivityPointsAll() (mapResp map[int]bool, err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("获取所有带有扣点的活动失败"+err.Error(), 2)
		}
	}()
	var condition string
	var pars []interface{}
	mapResp = make(map[int]bool, 0)
	list, e := models.GetCygxActivityPointsSetList(condition, pars, 0, 0)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityPointsSetList，Err: " + e.Error())
		return
	}
	for _, v := range list {
		mapResp[v.ActivityId] = true
	}
	return
}

// 用户报名添加到处理研选扣点
func YanXuanActivityPointsBillSignupAdd(activityId, uid int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId, "userId:", uid)
			go utils.SendAlarmMsg("用户报名添加到处理研选扣点，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
	log := &models.YanXuanActivityPointsRedis{UserId: uid, ActivityId: activityId, SourceType: 1, RegisterPlatform: utils.REGISTER_PLATFORM, Source: 1, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 用户取消报名添加到处理研选扣点
func YanXuanActivityPointsBillSignupCancel(activityId, uid int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId, "userId:", uid)
			go utils.SendAlarmMsg("用户取消报名添加到处理研选扣点，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
	log := &models.YanXuanActivityPointsRedis{UserId: uid, ActivityId: activityId, SourceType: 2, RegisterPlatform: utils.REGISTER_PLATFORM, Source: 1, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 5 活动到会研选扣点处理
func YanXuanActivityPointsBillSubmitMeeting(activityId, adminId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId)
			go utils.SendAlarmMsg("活动到会研选扣点处理，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。6:研选审批通过的时候研选扣点更新、 7:正式专试用定时任务更新研选扣点"`
	log := &models.YanXuanActivityPointsRedis{ActivityId: activityId, SourceType: 5, AdminId: adminId, Source: 2, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 用户报名专项调研活动扣点处理
func SpecialActivityPointsBillSignupAddSpecial(activityId, uid int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId, "userId:", uid)
			go utils.SendAlarmMsg("用户报名专项调研活动扣点处理，写入Redis队列消息失败 SpecialActivityPointsBillSignupAddSpecial ："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
	log := &models.YanXuanActivityPointsRedis{UserId: uid, ActivityId: activityId, SourceType: 9, RegisterPlatform: utils.REGISTER_PLATFORM, Source: 1, CreateTime: time.Now()}
	if utils.Re == nil {
		err = utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 用户取消报名专项调研活动扣点处理
func ActivityPointsBillSignupCancelSpecial(activityId, uid int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId, "userId:", uid)
			go utils.SendAlarmMsg("用户取消报名专项调研活动扣点处理，写入Redis队列消息失败 ActivityPointsBillSignupCancelSpecial ："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
	log := &models.YanXuanActivityPointsRedis{UserId: uid, ActivityId: activityId, SourceType: 10, RegisterPlatform: utils.REGISTER_PLATFORM, Source: 1, CreateTime: time.Now()}
	if utils.Re == nil {
		err = utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// YanXuanActivityPointsBillReduce 处理研选活动扣点
func YanXuanActivityPointsBillReduce() (err error) {
	for {
		//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
		utils.Rc.Brpop(utils.CYGX_YANXUAN_POINTS_KEY, func(b []byte) {
			var log models.YanXuanActivityPointsRedis
			if err := json.Unmarshal(b, &log); err != nil {
				fmt.Println("json unmarshal wrong!")
				go utils.SendAlarmMsg("处理研选活动扣点处理Redis队列消息失败："+err.Error()+string(b), 2)
			}
			switch log.SourceType {
			case 1:
				go YanXuanActivityPointsBillSignupAddReduce(log)
				fmt.Println("1：报名")
				break
			case 2:
				go YanXuanActivityPointsBillSignupCancelReduce(log)
				fmt.Println(" 2：取消报名")
				break
			case 3:
				go YanXuanActivityPointsBillActivityEditReduce(log)
				fmt.Println("3：活动编辑")
				break
			case 4:
				go YanXuanActivityPointsBillActivityPublishAndCancelReduce(log)
				fmt.Println("4：活动发布、取消发布")
				break
			case 5:
				go YanXuanActivityPointsBillSubmitMeetingReduce(log)
				fmt.Println("5：活动到会研选扣点处理。")
			case 6:
				//go YanXuanCompanyApprovalReduce(log)
				fmt.Println("6：研选审批通过的时候研选扣点更新。")
				break
			case 7:
				//go YanXuanCompanyCompanyTryOutReduce(log)
				fmt.Println("7：正式专试用定时任务更新研选扣点。")
				break
			case 8:
				//go YanXuanActivityVivoPointsBillSignupReduce(log)
				fmt.Println("8：播放研选扣点音视频。")
				break
			case 9:
				go YanXuanActivityPointsBillSignupAddReduceSpecial(log)
				fmt.Println("9：报名专项调研活动。")
				break
			case 10:
				go SpecialActivityPointsBillSignupCancelReduce(log)
				fmt.Println(" 10：取消报名专项调研活动")
				break
			case 11:
				go ActivitySpecialCompanyApprovalReduce(log)
				fmt.Println("11：合同审批通过的时候，专项调研点数更新。")
				break
			case 12:
				go ActivitySpecialPointsBillSubmitMeetingReduce(log)
				fmt.Println("12，专项调研活动提交到会点数更新。")
				break
			case 13:
				go SpecialActivityPointsBillRoadShowReduce(log)
				fmt.Println("13，给公司添加路演，对应专项调研扣点处理。")
				break

			default:
				fmt.Println(string(b))
				go utils.SendAlarmMsg("处理研选活动扣点处理Redis队列消息失败："+string(b), 2)
			}
		})
	}
}

// 1:用户报名
func YanXuanActivityPointsBillSignupAddReduce(log models.YanXuanActivityPointsRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户报名活动扣点，处理Redis队列消息失败："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "userId", log.UserId), 2)
		}
	}()
	//加2000毫秒的延迟
	time.Sleep(2 * time.Second)
	activityId := log.ActivityId
	userId := log.UserId

	activtyPayTotal := GetCygxOrderVirtualAssetdCountTotal(userId, activityId) // 单场付费活动不处理扣点明细
	if activtyPayTotal > 0 {
		return
	}

	//获取活动是否扣点以及扣点规则明细
	activityPointsSetDetail, e := models.GetCygxActivityPointsSetDetail(activityId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityPointsSetDetail" + e.Error())
		return
	}
	if activityPointsSetDetail == nil {
		return
	}
	if activityPointsSetDetail.UserPointsNum == 0 || activityPointsSetDetail.PointsType != 1 {
		return // 如果不是报名即扣点的这种形式，那么就不做任何处理
	}

	activityInfo, e := models.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoById" + e.Error())
		return
	}
	user, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}
	companyId := user.CompanyId
	//判断公司是不是满足扣点情况，如果是后台超管手动给试用客户报名，就写入一条点数初始化数据
	total, e := models.GetCygxActivitySpecialPermissionPointsCountByCompanyId(companyId)
	if e != nil {
		err = errors.New("GetCygxActivityPointsCompanyCountByCompanyId, Err: " + e.Error())
		return
	}
	var companyPointsNum float64
	if total == 0 {
		companyPointsNum = 0
		itemPointsCompany := new(models.CygxActivitySpecialPermissionPoints)

		itemPointsCompany.CompanyId = companyId
		itemPointsCompany.CompanyName = user.CompanyName
		itemPointsCompany.CreateTime = time.Now()
		itemPointsCompany.ModifyTime = time.Now()

		e = models.AddCygxActivitySpecialPermissionPoints(itemPointsCompany)
		if e != nil {
			err = errors.New("AddCygxActivitySpecialPermissionPoints, Err: " + e.Error())
			return
		}
	} else {
		// 获取用户所在公司剩余的点
		companyPointsNum, e = models.GetCygxActivitySpecialPermissionPoints(user.CompanyId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxActivitySpecialPermissionPoints, Err: " + e.Error())
			return
		}
	}

	//获取需要添加的流水信息
	var items []*models.CygxActivitySpecialTripBill
	item := new(models.CygxActivitySpecialTripBill)
	item.UserId = user.UserId
	item.ActivityId = activityId
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.RealName = user.RealName
	item.BillDetailed = -activityPointsSetDetail.UserPointsNum
	item.RegisterPlatform = log.RegisterPlatform
	item.AdminId = log.AdminId
	item.Source = log.Source
	item.ChartPermissionId = activityInfo.ChartPermissionId
	item.ChartPermissionName = activityInfo.ChartPermissionName
	item.DoType = 1
	item.Content = activityInfo.ActivityName + "--报名"
	item.Total = fmt.Sprint(companyPointsNum-activityPointsSetDetail.UserPointsNum, "次")
	item.TableSource = utils.CYGX_OBJ_ACTIVITY
	items = append(items, item)

	//更新对应机构的剩余点数
	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	itemCompany := new(models.CygxActivitySpecialPermissionPoints)
	itemCompany.CompanyId = user.CompanyId
	itemCompany.Points = companyPointsNum - activityPointsSetDetail.UserPointsNum
	itemCompany.ModifyTime = time.Now()
	itemCompanys = append(itemCompanys, itemCompany)

	err = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	return
}

// 2:用户取消报名
func YanXuanActivityPointsBillSignupCancelReduce(log models.YanXuanActivityPointsRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户取消报名扣点，处理Redis队列消息失败："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "userId", log.UserId), 2)
		}
	}()

	activityId := log.ActivityId
	userId := log.UserId

	activtyPayTotal := GetCygxOrderVirtualAssetdCountTotal(userId, activityId) // 单场付费活动不处理扣点明细
	if activtyPayTotal > 0 {
		return
	}
	//获取活动是否扣点以及扣点规则明细
	activityPointsSetDetail, e := models.GetCygxActivityPointsSetDetail(activityId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityPointsSetDetail" + e.Error())
		return
	}
	if activityPointsSetDetail == nil {
		return
	}
	if activityPointsSetDetail.UserPointsNum == 0 || activityPointsSetDetail.PointsType != 1 {
		return // 如果不是报名即扣点的这种形式，那么就不做任何处理
	}

	activityInfo, e := models.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoById" + e.Error())
		return
	}
	user, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}

	// 获取用户所在公司剩余的点
	companyPointsNum, e := models.GetCygxActivitySpecialPermissionPoints(user.CompanyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyPoints, Err: " + e.Error())
		return
	}

	//查询最新的一条针对这个用户的扣点记录
	var condition string
	var pars []interface{}
	condition += ` AND activity_id = ? AND user_id = ? AND table_source = 'activity'  AND bill_detailed < 0   ORDER BY id DESC LIMIT 1  `
	pars = append(pars, activityId, userId)
	activityPointsBillDetail, e := models.GetCygxActivitySpecialTripBillByCondition(condition, pars)
	if e != nil {
		err = errors.New("GetCygxActivitySpecialTripBillByCondition" + e.Error())
		return
	}

	//获取需要添加的流水信息
	var items []*models.CygxActivitySpecialTripBill
	item := new(models.CygxActivitySpecialTripBill)
	item.UserId = user.UserId
	item.ActivityId = activityId
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.RealName = user.RealName
	item.BillDetailed = -activityPointsBillDetail.BillDetailed
	item.RegisterPlatform = log.RegisterPlatform
	item.AdminId = log.AdminId
	item.Source = log.Source
	item.ChartPermissionId = activityInfo.ChartPermissionId
	item.ChartPermissionName = activityInfo.ChartPermissionName
	item.DoType = 2
	item.Content = activityInfo.ActivityName + "--取消报名"
	item.Total = fmt.Sprint(companyPointsNum-activityPointsBillDetail.BillDetailed, "次")
	item.TableSource = utils.CYGX_OBJ_ACTIVITY
	items = append(items, item)

	//更新对应机构的剩余点数
	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	itemCompany := new(models.CygxActivitySpecialPermissionPoints)
	itemCompany.CompanyId = user.CompanyId
	itemCompany.Points = companyPointsNum - activityPointsBillDetail.BillDetailed
	itemCompany.ModifyTime = time.Now()
	itemCompanys = append(itemCompanys, itemCompany)

	err = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	return
}

// 3:活动编辑
func YanXuanActivityPointsBillActivityEditReduce(log models.YanXuanActivityPointsRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户报名活动扣点，处理Redis队列消息失败："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "userId", log.UserId), 2)
		}
	}()

	activityId := log.ActivityId

	//获取活动是否扣点以及扣点规则明细
	activityPointsSetDetail, e := models.GetCygxActivityPointsSetDetail(activityId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityPointsSetDetail" + e.Error())
		return
	}
	if activityPointsSetDetail == nil {
		return
	}
	if activityPointsSetDetail.CompanyPointsNum == 0 {
		return // 如果不是办会人，即扣点的这种形式，那么就不做任何处理
	}
	comapnyId := activityPointsSetDetail.CompanyId
	activityInfo, e := models.GetAddActivityInfoByActivityId(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoByActivityId" + e.Error())
		return
	}
	if activityInfo.PublishStatus == 0 {
		return // 未发布的活动不做处理
	}
	comapny, e := models.GetCompanyById(comapnyId)
	if e != nil {
		err = errors.New("GetCompanyById" + e.Error())
		return
	}

	// 获取用户所在公司剩余的点
	companyPointsNum, e := models.GetCygxActivitySpecialPermissionPoints(comapny.CompanyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyPoints, Err: " + e.Error())
		return
	}

	//查询最新的一条针对这个公司的扣点记录
	var condition string
	var pars []interface{}
	condition += ` AND activity_id = ? AND company_id = ? AND mobile = ''  AND table_source = 'activity'  AND bill_detailed < 0   ORDER BY id DESC LIMIT 1  `
	pars = append(pars, activityId, comapnyId)
	activityPointsBillDetail, e := models.GetCygxActivitySpecialTripBillByCondition(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyPoints, Err: " + e.Error())
		return
	}
	var items []*models.CygxActivitySpecialTripBill
	item := new(models.CygxActivitySpecialTripBill)
	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	itemCompany := new(models.CygxActivitySpecialPermissionPoints)
	//item.UserId = user.UserId
	item.ActivityId = activityId
	item.CreateTime = time.Now()
	//item.Mobile = user.Mobile
	//item.Email = user.Email
	item.CompanyId = comapny.CompanyId
	item.CompanyName = comapny.CompanyName
	//item.RealName = user.RealName
	item.BillDetailed = -activityPointsSetDetail.CompanyPointsNum
	item.RegisterPlatform = log.RegisterPlatform
	item.AdminId = log.AdminId
	item.Source = log.Source
	item.ChartPermissionId = activityInfo.ChartPermissionId
	item.DoType = 1
	item.Content = activityInfo.ActivityName + "--办会"
	//item.Points = companyPointsNum - activityPointsSetDetail.CompanyPointsNum
	item.Total = fmt.Sprint(companyPointsNum-activityPointsSetDetail.CompanyPointsNum, "次")
	item.TableSource = utils.CYGX_OBJ_ACTIVITY
	if activityPointsBillDetail == nil { //如果是空的就添加
		//获取需要添加的流水信息
		items = append(items, item)
		//更新对应机构的剩余点数
		itemCompany.CompanyId = comapny.CompanyId
		itemCompany.Points = companyPointsNum - activityPointsSetDetail.CompanyPointsNum
		itemCompany.ModifyTime = time.Now()
		itemCompanys = append(itemCompanys, itemCompany)
		e = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("AddCygxActivitySpecialTripBillMulti, Err: " + e.Error())
			return
		}
	} else {
		//如果存在就进行对比修改
		if activityPointsSetDetail.CompanyPointsNum != -activityPointsBillDetail.BillDetailed {
			//item.Id = activityPointsBillDetail.Id
			item.BillDetailed = -activityPointsSetDetail.CompanyPointsNum
			item.Total = fmt.Sprint(companyPointsNum-activityPointsBillDetail.BillDetailed-activityPointsSetDetail.CompanyPointsNum, "次")
			items = append(items, item)

			//更新对应机构的剩余点数
			itemCompany.CompanyId = comapny.CompanyId
			itemCompany.Points = companyPointsNum - activityPointsBillDetail.BillDetailed - activityPointsSetDetail.CompanyPointsNum
			itemCompany.ModifyTime = time.Now()
			itemCompanys = append(itemCompanys, itemCompany)

			e = models.DelCygxActivitySpecialTripBillById(activityPointsBillDetail.Id)
			if e != nil {
				err = errors.New("DelCygxActivitySpecialTripBillById, Err: " + e.Error())
				return
			}
			e = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("AddCygxActivitySpecialTripBillMulti, Err: " + e.Error())
				return
			}
		}
	}
	return
}

// 4:活动发布取消发布
func YanXuanActivityPointsBillActivityPublishAndCancelReduce(log models.YanXuanActivityPointsRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("活动发布扣点，处理Redis队列消息失败："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "userId", log.UserId), 2)
		}
	}()

	activityId := log.ActivityId
	publishStatus := log.PublishStatus
	//comapnyId := log.ComapnyId

	//获取活动是否扣点以及扣点规则明细
	activityPointsSetDetail, e := models.GetCygxActivityPointsSetDetail(activityId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityPointsSetDetail" + e.Error())
		return
	}
	if activityPointsSetDetail == nil {
		return
	}
	if activityPointsSetDetail.CompanyPointsNum == 0 && activityPointsSetDetail.PointsType == 2 {
		//if activityPointsSetDetail.CompanyPointsNum == 0 {
		return // 如果不是办会人扣点,且对用户是到会扣点的这种形式，那么就不做任何处理
	}

	activityInfo, e := models.GetAddActivityInfoByActivityId(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoByActivityId" + e.Error())
		return
	}

	comapnyId := activityPointsSetDetail.CompanyId
	var items []*models.CygxActivitySpecialTripBill

	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	mapCompanyPoints := make(map[int]float64) //一组公司的剩余点数
	if publishStatus == 1 {
		fmt.Println("//活动发布")
		if comapnyId > 0 {
			comapny, e := models.GetCompanyById(comapnyId)
			if e != nil {
				err = errors.New("GetCompanyById" + e.Error())
				return
			}
			// 获取用户所在公司剩余的点
			companyPointsNum, e := models.GetCygxActivitySpecialPermissionPoints(comapny.CompanyId)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCompanyPoints, Err: " + e.Error())
				return
			}
			item := new(models.CygxActivitySpecialTripBill)
			item.ActivityId = activityId
			item.CreateTime = time.Now()
			//item.Mobile = user.Mobile
			//item.Email = user.Email
			item.CompanyId = comapny.CompanyId
			item.CompanyName = comapny.CompanyName
			//item.RealName = user.RealName
			item.BillDetailed = -activityPointsSetDetail.CompanyPointsNum
			item.RegisterPlatform = log.RegisterPlatform
			item.AdminId = log.AdminId
			item.Source = log.Source
			item.ChartPermissionId = activityInfo.ChartPermissionId
			item.ChartPermissionName = activityInfo.ChartPermissionName
			item.DoType = 1
			item.Content = activityInfo.ActivityName + "--办会"
			//item.Points = companyPointsNum - activityPointsSetDetail.CompanyPointsNum
			item.Total = fmt.Sprint(companyPointsNum-activityPointsSetDetail.CompanyPointsNum, "次")
			item.TableSource = utils.CYGX_OBJ_ACTIVITY
			items = append(items, item)

			//更新对应机构的剩余点数
			itemCompany := new(models.CygxActivitySpecialPermissionPoints)
			itemCompany.CompanyId = comapny.CompanyId
			itemCompany.Points = companyPointsNum - activityPointsSetDetail.CompanyPointsNum
			itemCompany.ModifyTime = time.Now()
			itemCompanys = append(itemCompanys, itemCompany)
			mapCompanyPoints[comapnyId] = companyPointsNum - activityPointsSetDetail.CompanyPointsNum
		}

		if activityPointsSetDetail.UserPointsNum > 0 && activityPointsSetDetail.PointsType == 1 {
			//如果扣点形式选的是报名即扣点，那么就对已经报名的用户所在机构进行扣点
			var condition string
			var pars []interface{}
			condition = ` AND do_fail_type = 0 AND activity_id  = ?`
			pars = append(pars, activityId)

			listSignup, e := models.GetActivitySignupList(condition, pars)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetActivitySignupList, Err: " + e.Error())
				return
			}
			var companyIds []int
			if len(listSignup) > 0 {
				for _, v := range listSignup {
					companyIds = append(companyIds, v.CompanyId)
				}
				pars = make([]interface{}, 0)
				condition = ` AND company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
				pars = append(pars, companyIds)

				//获取这些公司剩余的点数
				conpanyList, e := models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
				if e != nil && e.Error() != utils.ErrNoRow() {
					err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err: " + e.Error())
					return
				}

				for _, v := range conpanyList {
					if mapCompanyPoints[v.CompanyId] == 0 {
						mapCompanyPoints[v.CompanyId] = v.Points
					}
				}

				for _, user := range listSignup {
					item := new(models.CygxActivitySpecialTripBill)
					item.ActivityId = activityId
					item.CreateTime = time.Now()
					item.Mobile = user.Mobile
					item.UserId = user.UserId
					item.Email = user.Email
					item.CompanyId = user.CompanyId
					item.CompanyName = user.CompanyName
					item.RealName = user.RealName
					item.BillDetailed = -activityPointsSetDetail.UserPointsNum
					item.RegisterPlatform = log.RegisterPlatform
					item.AdminId = log.AdminId
					item.Source = log.Source
					item.ChartPermissionId = activityInfo.ChartPermissionId
					item.DoType = 1
					item.Content = activityInfo.ActivityName + "--发布活动"
					mapCompanyPoints[user.CompanyId] -= activityPointsSetDetail.UserPointsNum //通过map处理机构剩余点数
					//item.Points = mapCompanyPoints[user.CompanyId]
					item.Total = fmt.Sprint(mapCompanyPoints[user.CompanyId], "次")
					item.TableSource = utils.CYGX_OBJ_ACTIVITY
					items = append(items, item)

					//更新对应机构的剩余点数
					itemCompany := new(models.CygxActivitySpecialPermissionPoints)
					itemCompany.CompanyId = user.CompanyId
					itemCompany.Points = mapCompanyPoints[user.CompanyId]
					itemCompany.ModifyTime = time.Now()
					itemCompanys = append(itemCompanys, itemCompany)
					mapCompanyPoints[user.CompanyId] = mapCompanyPoints[user.CompanyId]
				}
			}
		}

	} else {
		fmt.Println("//活动取消发布")
		//活动取消发布

		if comapnyId > 0 {
			comapny, e := models.GetCompanyById(comapnyId)
			if e != nil {
				err = errors.New("GetCompanyById" + e.Error())
				return
			}
			// 获取用户所在公司剩余的点
			companyPointsNum, e := models.GetCygxActivitySpecialPermissionPoints(comapny.CompanyId)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCompanyPoints, Err: " + e.Error())
				return
			}
			item := new(models.CygxActivitySpecialTripBill)
			item.ActivityId = activityId
			item.CreateTime = time.Now()
			//item.Mobile = user.Mobile
			//item.Email = user.Email
			item.CompanyId = comapny.CompanyId
			item.CompanyName = comapny.CompanyName
			//item.RealName = user.RealName
			item.BillDetailed = activityPointsSetDetail.CompanyPointsNum
			item.RegisterPlatform = log.RegisterPlatform
			item.AdminId = log.AdminId
			item.Source = log.Source
			item.ChartPermissionId = activityInfo.ChartPermissionId
			item.DoType = 2
			item.Content = activityInfo.ActivityName + "--取消办会"
			//item.Points = companyPointsNum + activityPointsSetDetail.CompanyPointsNum
			item.Total = fmt.Sprint(companyPointsNum+activityPointsSetDetail.CompanyPointsNum, "次")
			item.TableSource = utils.CYGX_OBJ_ACTIVITY
			items = append(items, item)
			//更新对应机构的剩余点数
			itemCompany := new(models.CygxActivitySpecialPermissionPoints)
			itemCompany.CompanyId = comapny.CompanyId
			itemCompany.Points = companyPointsNum + activityPointsSetDetail.CompanyPointsNum
			itemCompany.ModifyTime = time.Now()
			itemCompanys = append(itemCompanys, itemCompany)
			mapCompanyPoints[comapnyId] = companyPointsNum + activityPointsSetDetail.CompanyPointsNum
		}

		if activityPointsSetDetail.UserPointsNum > 0 && activityPointsSetDetail.PointsType == 1 {
			//如果扣点形式选的是报名即扣点，那么就对已经报名的用户所在机构进行返点
			var condition string
			var pars []interface{}
			condition = ` AND do_fail_type = 0 AND activity_id  = ?`
			pars = append(pars, activityId)

			listSignup, e := models.GetActivitySignupList(condition, pars)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetActivitySignupList, Err: " + e.Error())
				return
			}
			var companyIds []int
			if len(listSignup) > 0 {
				for _, v := range listSignup {
					companyIds = append(companyIds, v.CompanyId)
				}
				pars = make([]interface{}, 0)
				condition = ` AND company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
				pars = append(pars, companyIds)

				//获取这些公司剩余的点数
				conpanyList, e := models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
				if e != nil && e.Error() != utils.ErrNoRow() {
					err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err: " + e.Error())
					return
				}

				for _, v := range conpanyList {
					if mapCompanyPoints[v.CompanyId] == 0 {
						mapCompanyPoints[v.CompanyId] = v.Points
					}
				}

				pars = make([]interface{}, 0)
				condition = ` AND activity_id = ? AND table_source = 'activity'   `
				pars = append(pars, activityId)
				//获取扣点的流水记录
				activityPointsBillList, e := models.GetCygxActivitySpecialTripBill(condition, pars)
				if e != nil && e.Error() != utils.ErrNoRow() {
					err = errors.New("GetCygxActivitySpecialTripBill" + e.Error())
					return
				}
				mapUserBill := make(map[int]bool)
				for _, v := range activityPointsBillList {
					mapUserBill[v.UserId] = true
				}
				for _, user := range listSignup {
					if !mapUserBill[user.UserId] {
						continue // 如果用户的扣点记录不存在，那么就不进行返点处理
					}
					item := new(models.CygxActivitySpecialTripBill)
					item.ActivityId = activityId
					item.CreateTime = time.Now()
					item.Mobile = user.Mobile
					item.UserId = user.UserId
					item.Email = user.Email
					item.CompanyId = user.CompanyId
					item.CompanyName = user.CompanyName
					item.RealName = user.RealName
					item.BillDetailed = activityPointsSetDetail.UserPointsNum
					item.RegisterPlatform = log.RegisterPlatform
					item.AdminId = log.AdminId
					item.Source = log.Source
					item.ChartPermissionId = activityInfo.ChartPermissionId
					item.DoType = 2
					item.Content = activityInfo.ActivityName + "--取消活动"
					mapCompanyPoints[user.CompanyId] += activityPointsSetDetail.UserPointsNum //通过map处理机构剩余点数
					//item.Points = mapCompanyPoints[user.CompanyId]

					item.Total = fmt.Sprint(mapCompanyPoints[user.CompanyId], "次")
					item.TableSource = utils.CYGX_OBJ_ACTIVITY

					items = append(items, item)

					//更新对应机构的剩余点数
					itemCompany := new(models.CygxActivitySpecialPermissionPoints)
					itemCompany.CompanyId = user.CompanyId
					itemCompany.Points = mapCompanyPoints[user.CompanyId]
					itemCompany.ModifyTime = time.Now()
					itemCompanys = append(itemCompanys, itemCompany)
					//mapCompanyPoints[user.CompanyId] = item.Points
				}
			}
		}
	}
	e = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("AddCygxActivitySpecialTripBillMulti, Err: " + e.Error())
		return
	}
	return
}

//func init() {
//	log := models.YanXuanActivityPointsRedis{ActivityId: 2385, SourceType: 5, RegisterPlatform: utils.REGISTER_PLATFORM, Source: 4, CreateTime: time.Now()}
//	YanXuanActivityPointsBillSubmitMeetingReduce(log)
//}

// 5:活动到会研选扣点处理
func YanXuanActivityPointsBillSubmitMeetingReduce(log models.YanXuanActivityPointsRedis) (err error) {
	//func YanXuanActivityPointsBillSubmitMeetingReduce(activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("活动到会研选扣点，处理Redis队列消息失败："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "adminId", log.AdminId), 2)
		}
	}()

	time.Sleep(5 * time.Second) //添加五秒的延迟

	activityId := log.ActivityId
	//获取活动是否扣点以及扣点规则明细
	activityPointsSetDetail, e := models.GetCygxActivityPointsSetDetail(activityId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityPointsSetDetail" + e.Error())
		return
	}
	if activityPointsSetDetail == nil {
		return
	}
	if activityPointsSetDetail.PointsType != 2 {
		return // 如果不是到会即扣点,的这种形式，那么就不做任何处理
	}

	activityInfo, e := models.GetAddActivityInfoByActivityId(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoByActivityId" + e.Error())
		return
	}
	var companyIds []int
	mapCompanyPoints := make(map[int]float64) //一组公司的剩余点数
	var condition string
	var pars []interface{}
	condition += ` AND activity_id = ?  `
	pars = append(pars, activityId)

	//获取提交到会的人员信息
	signUpDetailList, e := models.GetSignupDetailList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSignupDetailList" + e.Error())
		return
	}
	if len(signUpDetailList) == 0 {
		return
	}
	for _, v := range signUpDetailList {
		companyIds = append(companyIds, v.CompanyId)

		companyId := v.CompanyId
		//判断公司是不是满足扣点情况，如果是后台超管手动给试用客户报名，就写入一条点数初始化数据
		total, e := models.GetCygxActivitySpecialPermissionPointsCountByCompanyId(companyId)
		if e != nil {
			err = errors.New("GetCygxActivitySpecialPermissionPointsCountByCompanyId, Err: " + e.Error())
			return
		}

		if total == 0 {
			itemPointsCompany := new(models.CygxActivitySpecialPermissionPoints)
			itemPointsCompany.CompanyId = companyId
			itemPointsCompany.CompanyName = v.CompanyName
			itemPointsCompany.CreateTime = time.Now()
			itemPointsCompany.ModifyTime = time.Now()

			e = models.AddCygxActivitySpecialPermissionPoints(itemPointsCompany)
			if e != nil {
				err = errors.New("AddCygxActivitySpecialPermissionPoints, Err: " + e.Error())
				return
			}
		}
	}

	//return
	pars = make([]interface{}, 0)
	condition = ` AND company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
	pars = append(pars, companyIds)
	//获取这些公司剩余的点数
	conpanyList, e := models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err: " + e.Error())
		return
	}

	pars = make([]interface{}, 0)
	condition = ` AND activity_id = ? AND table_source = 'activity'  AND  mobile  != ''  ORDER BY  id DESC   `
	pars = append(pars, activityId)
	//获取扣点的流水记录
	activityPointsBillList, e := models.GetCygxActivitySpecialTripBill(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialTripBill" + e.Error())
		return
	}
	mapActivityPointsBill := make(map[string]*models.CygxActivitySpecialTripBill)
	for _, v := range activityPointsBillList { //获取这场活动，某个手机号最后一次的扣点记录
		if mapActivityPointsBill[v.Mobile] == nil {
			mapActivityPointsBill[v.Mobile] = v
		}
	}
	//return
	for _, v := range conpanyList {
		if v.CompanyId != 0 {
			mapCompanyPoints[v.CompanyId] = v.Points
		}
	}

	//return
	var items []*models.CygxActivitySpecialTripBill
	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	for _, user := range signUpDetailList {
		item := new(models.CygxActivitySpecialTripBill)
		item.ActivityId = activityId
		item.CreateTime = time.Now()
		item.UserId = user.UserId
		item.Mobile = user.Mobile
		item.Email = user.Email
		item.CompanyId = user.CompanyId
		item.CompanyName = user.CompanyName
		item.RealName = user.RealName
		item.RegisterPlatform = log.RegisterPlatform
		item.AdminId = log.AdminId
		item.Source = log.Source
		item.ChartPermissionId = activityInfo.ChartPermissionId
		if user.IsMeeting == 1 {
			//如果没有扣点记录就对他们进行扣点处理
			if mapActivityPointsBill[user.Mobile] == nil || mapActivityPointsBill[user.Mobile].BillDetailed > 0 {
				points := mapCompanyPoints[user.CompanyId] - activityPointsSetDetail.UserPointsNum
				item.BillDetailed = -activityPointsSetDetail.UserPointsNum
				item.DoType = 1
				item.Content = activityInfo.ActivityName + "--活动到会"
				item.Total = fmt.Sprint(points, "次")
				item.TableSource = utils.CYGX_OBJ_ACTIVITY
				//item.Points = mapCompanyPoints[user.CompanyId] - activityPointsSetDetail.UserPointsNum
				items = append(items, item)
				//更新对应机构的剩余点数
				itemCompany := new(models.CygxActivitySpecialPermissionPoints)
				itemCompany.CompanyId = user.CompanyId
				itemCompany.Points = points
				itemCompany.ModifyTime = time.Now()
				itemCompanys = append(itemCompanys, itemCompany)
				mapCompanyPoints[user.CompanyId] = points
			}
		} else {
			////第二次提交改成未到会的，对其进行返点处理
			if mapActivityPointsBill[user.Mobile] != nil && mapActivityPointsBill[user.Mobile].BillDetailed < 0 {
				fmt.Println("取消到会了")
				points := mapCompanyPoints[user.CompanyId] + activityPointsSetDetail.UserPointsNum
				item.BillDetailed = activityPointsSetDetail.UserPointsNum
				item.DoType = 2
				item.Content = activityInfo.ActivityName + "--活动取消到会"
				//item.Points =points
				item.Total = fmt.Sprint(points, "次")
				item.TableSource = utils.CYGX_OBJ_ACTIVITY
				items = append(items, item)

				//更新对应机构的剩余点数
				itemCompany := new(models.CygxActivitySpecialPermissionPoints)
				itemCompany.CompanyId = user.CompanyId
				itemCompany.Points = points
				itemCompany.ModifyTime = time.Now()
				itemCompanys = append(itemCompanys, itemCompany)
				mapCompanyPoints[user.CompanyId] = points
			}
		}
	}
	e = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("AddCygxActivitySpecialTripBillMulti, Err: " + e.Error())
		return
	}
	return
}

// 6:研选审批通过的时候研选扣点更新
func YanXuanCompanyApprovalReduce(log models.YanXuanActivityPointsRedis) (err error) {
	time.Sleep(5 * time.Second) // 延迟5秒处理
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("研选审批通过的时候研选扣点更新，处理Redis队列消息失败："+err.Error()+fmt.Sprint(log), 2)
		}
	}()
	comapnyId := log.ComapnyId
	companyContractId := log.CompanyContractId

	comapnyDetail, e := models.GetCompanyById(comapnyId)
	if e != nil {
		err = errors.New("GetCompanyById" + e.Error())
		return
	}
	total, e := models.GetCygxActivityPointsCompanyCountByCompanyId(comapnyId)
	if e != nil {
		err = errors.New("GetCygxActivityPointsCompanyCountByCompanyId, Err: " + e.Error())
		return
	}

	//查询研选的权限状态
	var condition string
	var pars []interface{}
	condition += " AND company_id = ? AND company_contract_id =?  AND chart_permission_id = ?   ORDER BY id DESC LIMIT 1  "
	pars = append(pars, comapnyId, companyContractId, utils.YAN_XUAN_KOU_DIAN_BAO_ID)
	companyPointDetail, e := company.GetCompanyContractPermissionDetail(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractPermissionDetail, Err: " + e.Error())
		return
	}
	if companyPointDetail == nil {
		return // 如果不存在就不做研选扣点处理
	}

	//获取最近的一条审批合同信息
	//newCompanyApprovalDetail, e := company.GetCompanyApprovalById(comapnyId)
	//if e != nil && e.Error() != utils.ErrNoRow() {
	//	err = errors.New("GetCompanyApprovalById, Err: " + e.Error())
	//	return
	//}
	//if newCompanyApprovalDetail == nil {
	//	return
	//}
	//companyContractId := newCompanyApprovalDetail.CompanyContractId

	//totalYxPerminssion, e := company.GetCompanyContractPermissionCheck(companyContractId, utils.CHART_PERMISSION_ID_YANXUAN)
	//if e != nil {
	//	err = errors.New("GetCompanyContractPermissionCheck, Err: " + e.Error())
	//	return
	//}
	//// 如果最新的审批合同里没有研选的权限，那么就不做处理
	//if totalYxPerminssion == 0 {
	//	return
	//}

	var billDetailed float64
	var content string
	//ExpensiveYx               int       `description:"权益研选: 0->3w; 1->5w；2->10W"` 3W3次、5W 15次，20w:40次 ,
	//if companyReportPermissionDetail.ExpensiveYx == 1 {
	//	billDetailed = 15
	//	content = "买方研选(5W)转正"
	//} else if companyReportPermissionDetail.ExpensiveYx == 2 {
	//	billDetailed = 40
	//	content = "买方研选(10w)转正"
	//} else {
	//	billDetailed = 3
	//	content = "买方研选(3W)转正"
	//}
	// 获取用户所在公司剩余的点
	companyPointsNum, e := models.GetCygxActivitySpecialPermissionPoints(comapnyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyPoints, Err: " + e.Error())
		return
	}
	billDetailed = companyPointDetail.Points + companyPointsNum

	content = "签约研选扣点包"

	//获取需要添加的流水信息
	var items []*models.CygxActivityPointsBill
	item := new(models.CygxActivityPointsBill)
	//item.UserId = user.UserId
	//item.ActivityId = activityId
	item.CreateTime = time.Now()
	//item.Mobile = user.Mobile
	//item.Email = user.Email
	item.CompanyId = comapnyDetail.CompanyId
	item.CompanyName = comapnyDetail.CompanyName
	//item.RealName = user.RealName
	item.BillDetailed = billDetailed
	item.RegisterPlatform = log.RegisterPlatform
	item.AdminId = log.AdminId
	item.Source = log.Source
	//item.ChartPermissionId = activityInfo.ChartPermissionId
	item.DoType = 2
	item.Content = content
	item.Points = billDetailed
	items = append(items, item)

	//更新对应机构的剩余点数
	var itemCompanys []*models.CygxActivityPointsCompany
	itemCompany := new(models.CygxActivityPointsCompany)
	itemCompany.CompanyId = comapnyDetail.CompanyId
	itemCompany.CompanyName = comapnyDetail.CompanyName
	itemCompany.Points = item.Points
	itemCompany.CreateTime = time.Now()
	itemCompany.ModifyTime = time.Now()
	itemCompanys = append(itemCompanys, itemCompany)
	//判断是否存在记录，如果有就一个新增一个修改，如果没有就同时新增
	if total == 0 {
		err = models.AddCygxActivityPointsBillAndCompanyMulti(items, itemCompanys)
	} else {
		err = models.AddCygxActivityPointsBillMulti(items, itemCompanys)
	}

	return
}

// 7:正式专试用定时任务更新研选扣点
func YanXuanCompanyCompanyTryOutReduce(log models.YanXuanActivityPointsRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("正式专试用定时任务更新研选扣点更新，处理Redis队列消息失败："+err.Error()+fmt.Sprint(log), 2)
		}
	}()
	comapnyId := log.ComapnyId

	comapny, e := models.GetCompanyById(comapnyId)
	if e != nil {
		err = errors.New("GetCompanyById" + e.Error())
		return
	}
	// 获取用户所在公司剩余的点
	companyPointsNum, e := models.GetCygxActivitySpecialPermissionPoints(comapnyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyPoints, Err: " + e.Error())
		return
	}
	if companyPointsNum <= 0 {
		return
	}
	//获取需要添加的流水信息
	var items []*models.CygxActivityPointsBill
	item := new(models.CygxActivityPointsBill)
	//item.UserId = user.UserId
	//item.ActivityId = activityId
	item.CreateTime = time.Now()
	//item.Mobile = user.Mobile
	//item.Email = user.Email
	item.CompanyId = comapny.CompanyId
	item.CompanyName = comapny.CompanyName
	//item.RealName = user.RealName
	item.BillDetailed = -companyPointsNum
	item.RegisterPlatform = log.RegisterPlatform
	item.AdminId = log.AdminId
	item.Source = log.Source
	//item.ChartPermissionId = activityInfo.ChartPermissionId
	item.DoType = 2
	item.Content = "研选扣点包到期清零"
	item.Points = 0
	items = append(items, item)

	//更新对应机构的剩余点数
	var itemCompanys []*models.CygxActivityPointsCompany
	itemCompany := new(models.CygxActivityPointsCompany)
	itemCompany.CompanyId = comapny.CompanyId
	itemCompany.Points = 0
	itemCompany.CreateTime = time.Now()
	itemCompany.ModifyTime = time.Now()
	itemCompanys = append(itemCompanys, itemCompany)

	err = models.AddCygxActivityPointsBillMulti(items, itemCompanys)

	return
}

// 8:用户观看音视频研选扣点处理
func YanXuanActivityVivoPointsBillSignupReduce(log models.YanXuanActivityPointsRedis) (err error) {
	//func YanXuanActivityPointsBillSubmitMeetingReduce(activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户观看音视频研选扣点处理，处理Redis队列消息失败："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "UserId", log.UserId), 2)
		}
	}()

	activityId := log.ActivityId
	userId := log.UserId
	//获取活动是否扣点以及扣点规则明细
	vivoPointsSetDetail, e := models.GetCygxActivityVivoPointsSetByActivityId(activityId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityVivoPointsSetByActivityId" + e.Error())
		return
	}
	if vivoPointsSetDetail == nil {
		return
	}

	var vivoName string

	activityInfo, e := models.GetAddActivityInfoByActivityId(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoByActivityId" + e.Error())
		return
	}
	totalVi, e := models.GetCygxActivityVideoCount(activityId)
	if e != nil {
		err = errors.New("GetCygxActivityVideoCount" + e.Error())
		return
	}
	if totalVi > 0 {
		activityVideoInfo, e := models.GetCygxActivityVideoByActivityId(activityId)
		if e != nil {
			err = errors.New("GetCygxActivityVideoByActivityId, Err: " + e.Error())
			return
		}
		vivoName = activityVideoInfo.VideoName // 视频名称
	} else {
		totalVo, e := models.GetCygxActivityVoiceCount(activityId)
		if e != nil {
			err = errors.New("GetCygxActivityVoiceCount" + e.Error())
			return
		}
		if totalVo > 0 {
			activityVoiceInfo, e := models.GetCygxActivityVoiceByActivityId(activityId)
			if e != nil {
				err = errors.New("GetCygxActivityVoiceByActivityId, Err: " + e.Error())
				return
			}
			vivoName = activityVoiceInfo.VoiceName // 音频名称
		}
	}

	user, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}

	// 获取用户所在公司剩余的点
	companyPointsNum, e := models.GetCompanyPoints(user.CompanyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyPoints, Err: " + e.Error())
		return
	}

	//获取需要添加的流水信息
	var items []*models.CygxActivityPointsBill
	item := new(models.CygxActivityPointsBill)
	item.UserId = user.UserId
	item.ActivityId = activityId
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.RealName = user.RealName
	item.BillDetailed = -vivoPointsSetDetail.PointsNum
	item.RegisterPlatform = log.RegisterPlatform
	item.AdminId = log.AdminId
	item.Source = log.Source
	item.ChartPermissionId = activityInfo.ChartPermissionId
	item.DoType = 1
	item.Content = "查看活动回放-" + vivoName
	item.Points = companyPointsNum - vivoPointsSetDetail.PointsNum
	items = append(items, item)

	//更新对应机构的剩余点数
	var itemCompanys []*models.CygxActivityPointsCompany
	itemCompany := new(models.CygxActivityPointsCompany)
	itemCompany.CompanyId = user.CompanyId
	itemCompany.Points = item.Points
	itemCompany.ModifyTime = time.Now()
	itemCompanys = append(itemCompanys, itemCompany)
	err = models.AddCygxActivityPointsBillMulti(items, itemCompanys)
	return
}

// 9:用户报名（专项调研活动）
func YanXuanActivityPointsBillSignupAddReduceSpecial(log models.YanXuanActivityPointsRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户报名活动扣点，处理Redis队列消息失败："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "userId", log.UserId), 2)
		}
	}()
	//加2000毫秒的延迟
	time.Sleep(2 * time.Second)
	activityId := log.ActivityId
	userId := log.UserId
	activityInfo, e := models.GetCygxActivitySpecialDetail(activityId)
	if e != nil {
		err = errors.New("GetCygxActivitySpecialDetail" + e.Error())
		return
	}
	user, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}
	companyId := user.CompanyId
	//判断公司是不是满足扣点情况，如果是后台超管手动给试用客户报名，就写入一条点数初始化数据
	total, e := models.GetCygxActivitySpecialPermissionPointsCountByCompanyId(companyId)
	if e != nil {
		err = errors.New("GetCygxActivityPointsCompanyCountByCompanyId, Err: " + e.Error())
		return
	}
	var companyPointsNum float64
	if total == 0 {
		companyPointsNum = 0
		itemPointsCompany := new(models.CygxActivitySpecialPermissionPoints)
		itemPointsCompany.CompanyId = companyId
		itemPointsCompany.CompanyName = user.CompanyName
		itemPointsCompany.CreateTime = time.Now()
		itemPointsCompany.ModifyTime = time.Now()
		e = models.AddCygxActivitySpecialPermissionPoints(itemPointsCompany)
		if e != nil {
			err = errors.New("AddCygxActivitySpecialPermissionPoints, Err: " + e.Error())
			return
		}
	} else {
		// 获取用户所在公司剩余的点
		companyPointsNum, e = models.GetCygxActivitySpecialPermissionPoints(user.CompanyId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxActivitySpecialPermissionPoints, Err: " + e.Error())
			return
		}
	}

	//获取需要添加的流水信息
	var items []*models.CygxActivitySpecialTripBill
	itemBill := new(models.CygxActivitySpecialTripBill)
	itemBill.UserId = user.UserId
	itemBill.ActivityId = activityInfo.ActivityId
	itemBill.CreateTime = time.Now()
	itemBill.Mobile = user.Mobile
	itemBill.Email = user.Email
	itemBill.CompanyId = user.CompanyId
	itemBill.CompanyName = user.CompanyName
	itemBill.RealName = user.RealName
	itemBill.Source = 1
	itemBill.DoType = 1
	itemBill.BillDetailed = -1 // 流水减一
	itemBill.RegisterPlatform = utils.REGISTER_PLATFORM
	itemBill.ChartPermissionId = activityInfo.ChartPermissionId
	itemBill.ChartPermissionName = activityInfo.ChartPermissionName
	itemBill.Content = activityInfo.ResearchTheme + "--报名"
	resultTime := utils.StrTimeToTime(activityInfo.ActivityTime)
	//48小时之内的取消也扣除一次参会记录
	if time.Now().Add(+time.Hour * 48).After(resultTime) {
		itemBill.BillDetailed = 0 //48小时之内，取消报名之后二次报名，不扣除流水记录
	}
	itemBill.Total = fmt.Sprint(companyPointsNum+itemBill.BillDetailed, "次")
	itemBill.TableSource = utils.CYGX_OBJ_ACTIVITYSPECIAL
	items = append(items, itemBill)
	//更新对应机构的剩余点数
	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	itemCompany := new(models.CygxActivitySpecialPermissionPoints)
	itemCompany.CompanyId = user.CompanyId
	itemCompany.Points = companyPointsNum + itemBill.BillDetailed
	itemCompany.ModifyTime = time.Now()
	itemCompanys = append(itemCompanys, itemCompany)

	err = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	return
}

// 10:用户取消报名（专项调研活动）
func SpecialActivityPointsBillSignupCancelReduce(log models.YanXuanActivityPointsRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户取消报名扣点，处理Redis队列消息失败 SpecialActivityPointsBillSignupCancelReduce："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "userId", log.UserId), 2)
		}
	}()

	activityId := log.ActivityId
	userId := log.UserId

	activityInfo, e := models.GetCygxActivitySpecialDetail(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoById" + e.Error())
		return
	}
	user, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}

	// 获取用户所在公司剩余的点
	companyPointsNum, e := models.GetCygxActivitySpecialPermissionPoints(user.CompanyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyPoints, Err: " + e.Error())
		return
	}

	//获取需要添加的流水信息
	var items []*models.CygxActivitySpecialTripBill
	//流水记录表
	itemBill := new(models.CygxActivitySpecialTripBill)
	itemBill.UserId = user.UserId
	itemBill.ActivityId = activityInfo.ActivityId
	itemBill.CreateTime = time.Now()
	itemBill.Mobile = user.Mobile
	itemBill.Email = user.Email
	itemBill.CompanyId = user.CompanyId
	itemBill.CompanyName = user.CompanyName
	itemBill.RealName = user.RealName
	itemBill.Source = 1
	itemBill.DoType = 2
	itemBill.BillDetailed = 1 // 流水加一
	itemBill.RegisterPlatform = log.RegisterPlatform
	itemBill.ChartPermissionId = activityInfo.ChartPermissionId
	itemBill.ChartPermissionName = activityInfo.ChartPermissionName
	resultTime := utils.StrTimeToTime(activityInfo.ActivityTime)
	//48小时之内的取消也扣除一次参会记录
	if time.Now().Add(+time.Hour * 48).After(resultTime) {
		itemBill.BillDetailed = 0 //48小时之内取消的活动扣点不返回
	}
	itemBill.Total = fmt.Sprint(companyPointsNum+itemBill.BillDetailed, "次")
	itemBill.Content = activityInfo.ResearchTheme + "--取消报名"
	itemBill.TableSource = utils.CYGX_OBJ_ACTIVITYSPECIAL
	items = append(items, itemBill)

	//更新对应机构的剩余点数
	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	itemCompany := new(models.CygxActivitySpecialPermissionPoints)
	itemCompany.CompanyId = user.CompanyId
	itemCompany.Points = companyPointsNum + itemBill.BillDetailed
	itemCompany.ModifyTime = time.Now()
	itemCompanys = append(itemCompanys, itemCompany)

	err = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	return
}

// 11:合同审批通过的时候，专项调研点数更新
func ActivitySpecialCompanyApprovalReduce(log models.YanXuanActivityPointsRedis) (err error) {
	time.Sleep(5 * time.Second) // 延迟5秒处理
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("研选审批通过的时候研选扣点更新，处理Redis队列消息失败："+err.Error()+fmt.Sprint(log), 2)
		}
	}()
	companyId := log.ComapnyId
	companyContractId := log.CompanyContractId
	comapnyDetail, e := models.GetCompanyById(companyId)
	if e != nil {
		err = errors.New("GetCompanyById" + e.Error())
		return
	}

	//判断公司是不是满足扣点情况，如果是后台超管手动给试用客户报名，就写入一条点数初始化数据
	total, e := models.GetCygxActivitySpecialPermissionPointsCountByCompanyId(companyId)
	if e != nil {
		err = errors.New("GetCygxActivitySpecialPermissionPointsCountByCompanyId, Err: " + e.Error())
		return
	}
	var companyPointsNum float64
	if total == 0 {
		companyPointsNum = 0
		itemPointsCompany := new(models.CygxActivitySpecialPermissionPoints)
		itemPointsCompany.CompanyId = companyId
		itemPointsCompany.CompanyName = comapnyDetail.CompanyName
		itemPointsCompany.CreateTime = time.Now()
		itemPointsCompany.ModifyTime = time.Now()
		e = models.AddCygxActivitySpecialPermissionPoints(itemPointsCompany)
		if e != nil {
			err = errors.New("AddCygxActivitySpecialPermissionPoints, Err: " + e.Error())
			return
		}
	} else {
		// 获取用户所在公司剩余的点
		companyPointsNum, e = models.GetCygxActivitySpecialPermissionPoints(companyId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxActivitySpecialPermissionPoints, Err: " + e.Error())
			return
		}
	}

	companyPoints, e := company.GetCompanyContractPermissionPointsCount(companyContractId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractPermissionPointsCount, Err: " + e.Error())
		return
	}
	//获取需要添加的流水信息
	var items []*models.CygxActivitySpecialTripBill
	if companyPoints > 0 {
		companyPointsNum += companyPoints
		itemBill := new(models.CygxActivitySpecialTripBill)
		itemBill.CreateTime = time.Now()
		itemBill.CompanyId = comapnyDetail.CompanyId
		itemBill.CompanyName = comapnyDetail.CompanyName
		itemBill.Source = 2
		itemBill.DoType = 2
		itemBill.Way = 3
		itemBill.RegisterPlatform = log.RegisterPlatform
		itemBill.TableSource = utils.CYGX_OBJ_ACTIVITYSPECIAL
		itemBill.BillDetailed = companyPoints
		itemBill.Total = fmt.Sprint(companyPointsNum, "次")
		itemBill.Content = "路演/专项点数转正"
		items = append(items, itemBill)
	}

	// 获取合同信息-套餐信息
	companyContract, e := company.GetCompanyContractById(companyContractId)
	if e != nil {
		err = errors.New("GetCompanyContractById, Err: " + e.Error())
		return
	}

	itemBill := new(models.CygxActivitySpecialTripBill)
	itemBill.CreateTime = time.Now()
	itemBill.CompanyId = comapnyDetail.CompanyId
	itemBill.CompanyName = comapnyDetail.CompanyName
	itemBill.Source = 2
	itemBill.DoType = 2
	itemBill.Way = 3
	itemBill.RegisterPlatform = log.RegisterPlatform
	itemBill.TableSource = utils.CYGX_OBJ_ACTIVITYSPECIAL

	packageType := companyContract.RaiPackageType
	if packageType > 0 {
		packageTypeMap := map[int]float64{1: 16, 2: 12}
		totalTrip := packageTypeMap[packageType]
		itemBill.BillDetailed = totalTrip
		companyPointsNum += totalTrip
		itemBill.Total = fmt.Sprint(itemBill.BillDetailed) + "次"
		if packageType == 2 {
			itemBill.Content = "45w大套餐转正"
		} else {
			itemBill.Content = "70w大套餐转正"
		}
		itemBill.Total = fmt.Sprint(companyPointsNum, "次")
		items = append(items, itemBill)
	} else {
		var condition string
		var pars []interface{}
		pars = make([]interface{}, 0)
		condition = " AND  company_contract_id = ?  AND  is_upgrade = 1  "
		pars = append(pars, companyContractId)
		list, e := company.GetCompanyContractPermissionList(condition, pars) // 获取带有升级的权限
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCompanyContractPermissionList, Err: " + e.Error())
			return
		}
		if len(list) > 0 {
			//获取权益主观权限
			listRaiSubjectivity, e := models.GetChartPermissionListRaiSubjectivity()
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetChartPermissionListRaiSubjectivity, Err: " + e.Error())
			}
			mapRaiSubjectivity := make(map[int]bool)
			mapPermissionName := make(map[int]string)
			for _, v := range listRaiSubjectivity {
				mapRaiSubjectivity[v.ChartPermissionId] = true
				mapPermissionName[v.ChartPermissionId] = v.ChartPermissionName
			}
			for _, v := range list {
				//如果是升级则加点
				if v.IsUpgrade == 1 && mapRaiSubjectivity[v.ChartPermissionId] {
					itemBill.BillDetailed += 4
					companyPointsNum += 4
				}
			}
			itemBill.Total = fmt.Sprint(companyPointsNum, "次")
			itemBill.Content = "行业升级套餐转正"
			items = append(items, itemBill)
		}
	}

	//更新对应机构的剩余点数
	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	itemCompany := new(models.CygxActivitySpecialPermissionPoints)
	itemCompany.CompanyId = comapnyDetail.CompanyId
	itemCompany.Points = companyPointsNum
	itemCompany.ModifyTime = time.Now()
	itemCompanys = append(itemCompanys, itemCompany)
	err = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	return
}

//func init() {
//	SpecialActivityPointsBillRoadShowReduce(1882)
//}

// 12: 专项调活动提交到会扣点处理
func ActivitySpecialPointsBillSubmitMeetingReduce(log models.YanXuanActivityPointsRedis) (err error) {
	//func ActivitySpecialPointsBillSubmitMeetingReduce(activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("专项调活动提交到会扣点处理，处理Redis队列消息失败："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "adminId", log.AdminId), 2)
		}
	}()

	time.Sleep(5 * time.Second) //添加五秒的延迟

	activityId := log.ActivityId
	activityInfo, e := models.GetCygxActivitySpecialDetail(activityId)
	if e != nil {
		err = errors.New("GetCygxActivitySpecialDetail" + e.Error())
		return
	}
	var companyIds []int
	mapCompanyPoints := make(map[int]float64) //一组公司的剩余点数
	var condition string
	var pars []interface{}
	condition += ` AND activity_id = ?   `
	pars = append(pars, activityId)

	//获取提交到会的人员信息
	signUpDetailList, e := models.GetCygxActivitySpecialmeetingDetailList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSignupDetailList" + e.Error())
		return
	}
	if len(signUpDetailList) == 0 {
		return
	}
	for _, v := range signUpDetailList {
		companyIds = append(companyIds, v.CompanyId)

		companyId := v.CompanyId
		//判断公司是不是满足扣点情况，如果是后台超管手动给试用客户报名，就写入一条点数初始化数据
		total, e := models.GetCygxActivitySpecialPermissionPointsCountByCompanyId(companyId)
		if e != nil {
			err = errors.New("GetCygxActivitySpecialPermissionPointsCountByCompanyId, Err: " + e.Error())
			return
		}

		if total == 0 {
			itemPointsCompany := new(models.CygxActivitySpecialPermissionPoints)
			itemPointsCompany.CompanyId = companyId
			itemPointsCompany.CompanyName = v.CompanyName
			itemPointsCompany.CreateTime = time.Now()
			itemPointsCompany.ModifyTime = time.Now()

			e = models.AddCygxActivitySpecialPermissionPoints(itemPointsCompany)
			if e != nil {
				err = errors.New("AddCygxActivitySpecialPermissionPoints, Err: " + e.Error())
				return
			}
		}
	}

	pars = make([]interface{}, 0)
	condition = ` AND activity_id = ? AND table_source = 'activityspecial'  AND  mobile  != ''  ORDER BY  id DESC   `
	pars = append(pars, activityId)
	//获取扣点的流水记录
	activityPointsBillList, e := models.GetCygxActivitySpecialTripBill(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialTripBill" + e.Error())
		return
	}
	mapActivityPointsBill := make(map[string]*models.CygxActivitySpecialTripBill)
	var itemsOld []*models.CygxActivitySpecialTripBill // 之前扣过点的流水记录
	for _, v := range activityPointsBillList {         //获取这场活动，某个手机号最后一次的扣点记录
		if mapActivityPointsBill[v.Mobile] == nil {
			mapActivityPointsBill[v.Mobile] = v
			if v.BillDetailed < 0 {
				itemsOld = append(itemsOld, v)
			}
		}
		companyIds = append(companyIds, v.CompanyId)
	}

	//return
	pars = make([]interface{}, 0)
	condition = ` AND company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
	pars = append(pars, companyIds)
	//获取这些公司剩余的点数
	conpanyList, e := models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err: " + e.Error())
		return
	}

	//return
	for _, v := range conpanyList {
		if v.CompanyId != 0 {
			mapCompanyPoints[v.CompanyId] = v.Points
		}
	}

	//return
	var items []*models.CygxActivitySpecialTripBill
	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	mapMeetUserId := make(map[int]bool)
	for _, user := range signUpDetailList {
		mapMeetUserId[user.UserId] = true
		item := new(models.CygxActivitySpecialTripBill)
		item.ActivityId = activityId
		item.CreateTime = time.Now()
		item.UserId = user.UserId
		item.Mobile = user.Mobile
		item.Email = user.Email
		item.CompanyId = user.CompanyId
		item.CompanyName = user.CompanyName
		item.RealName = user.RealName
		item.RegisterPlatform = log.RegisterPlatform
		item.AdminId = log.AdminId
		item.Source = log.Source
		item.ChartPermissionId = activityInfo.ChartPermissionId
		item.ChartPermissionName = activityInfo.ChartPermissionName
		if user.IsMeeting == 1 {
			//如果没有扣点记录就对他们进行扣点处理
			if mapActivityPointsBill[user.Mobile] == nil || mapActivityPointsBill[user.Mobile].BillDetailed > 0 {
				points := mapCompanyPoints[user.CompanyId] - 1
				item.BillDetailed = -1
				item.DoType = 1
				item.Content = activityInfo.ResearchTheme + "--活动到会"
				item.Total = fmt.Sprint(points, "次")
				item.TableSource = utils.CYGX_OBJ_ACTIVITYSPECIAL
				//item.Points = mapCompanyPoints[user.CompanyId] - activityPointsSetDetail.UserPointsNum
				items = append(items, item)
				//更新对应机构的剩余点数
				itemCompany := new(models.CygxActivitySpecialPermissionPoints)
				itemCompany.CompanyId = user.CompanyId
				itemCompany.Points = points
				itemCompany.ModifyTime = time.Now()
				itemCompanys = append(itemCompanys, itemCompany)
				mapCompanyPoints[user.CompanyId] = points
			}
		}
		//else {
		//	////第二次提交改成未到会的，对其进行返点处理
		//	if mapActivityPointsBill[user.Mobile] != nil && mapActivityPointsBill[user.Mobile].BillDetailed < 0 {
		//		fmt.Println("取消到会了")
		//		points := mapCompanyPoints[user.CompanyId] + 1
		//		item.BillDetailed = 1
		//		item.DoType = 2
		//		item.Content = activityInfo.ResearchTheme + "--活动取消到会"
		//		//item.Points =points
		//		item.Total = fmt.Sprint(points, "次")
		//		item.TableSource = utils.CYGX_OBJ_ACTIVITYSPECIAL
		//		items = append(items, item)
		//
		//		//更新对应机构的剩余点数
		//		itemCompany := new(models.CygxActivitySpecialPermissionPoints)
		//		itemCompany.CompanyId = user.CompanyId
		//		itemCompany.Points = points
		//		itemCompany.ModifyTime = time.Now()
		//		itemCompanys = append(itemCompanys, itemCompany)
		//		mapCompanyPoints[user.CompanyId] = points
		//	}
		//}
	}

	if len(itemsOld) > 0 {
		for _, user := range itemsOld {
			if mapMeetUserId[user.UserId] {
				continue
			}
			item := new(models.CygxActivitySpecialTripBill)
			item.ActivityId = activityId
			item.CreateTime = time.Now()
			item.UserId = user.UserId
			item.Mobile = user.Mobile
			item.Email = user.Email
			item.CompanyId = user.CompanyId
			item.CompanyName = user.CompanyName
			item.RealName = user.RealName
			item.RegisterPlatform = log.RegisterPlatform
			item.AdminId = log.AdminId
			item.Source = log.Source
			item.ChartPermissionId = activityInfo.ChartPermissionId
			item.ChartPermissionName = activityInfo.ChartPermissionName

			points := mapCompanyPoints[user.CompanyId] + 1
			item.BillDetailed = 1
			item.DoType = 2
			item.Content = activityInfo.ResearchTheme + "--活动取消到会"
			//item.Points =points
			item.Total = fmt.Sprint(points, "次")
			item.TableSource = utils.CYGX_OBJ_ACTIVITYSPECIAL
			items = append(items, item)

			//更新对应机构的剩余点数
			itemCompany := new(models.CygxActivitySpecialPermissionPoints)
			itemCompany.CompanyId = user.CompanyId
			itemCompany.Points = points
			itemCompany.ModifyTime = time.Now()
			itemCompanys = append(itemCompanys, itemCompany)
			mapCompanyPoints[user.CompanyId] = points
		}
	}

	e = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("AddCygxActivitySpecialTripBillMulti, Err: " + e.Error())
		return
	}
	return
}

//func init() {
//	SpecialActivityPointsBillRoadShowReduce(1895)
//}

// 13: 给公司添加路演，对应专项调研扣点处理
func SpecialActivityPointsBillRoadShowReduce(log models.YanXuanActivityPointsRedis) (err error) {
	//func SpecialActivityPointsBillRoadShowReduce(activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			//go utils.SendAlarmMsg("专项调活动提交到会扣点处理，处理Redis队列消息失败："+err.Error()+fmt.Sprint("ActivityId", log.ActivityId, "adminId", log.AdminId), 2)
		}
	}()

	time.Sleep(5 * time.Second) //添加五秒的延迟

	activityId := log.ActivityId
	rsCalendar, e := roadshow.GetRsCalendarById(activityId)
	if e != nil {
		err = errors.New("GetRsCalendarById" + e.Error())
		return
	}
	var companyIds []int
	mapCompanyPoints := make(map[int]float64) //一组公司的剩余点数
	var condition string
	var pars []interface{}

	companyId := rsCalendar.CompanyId
	companyIds = append(companyIds, companyId)
	//判断公司是不是满足扣点情况，如果是后台超管手动给试用客户报名，就写入一条点数初始化数据
	total, e := models.GetCygxActivitySpecialPermissionPointsCountByCompanyId(companyId)
	if e != nil {
		err = errors.New("GetCygxActivitySpecialPermissionPointsCountByCompanyId, Err: " + e.Error())
		return
	}

	if total == 0 {
		itemPointsCompany := new(models.CygxActivitySpecialPermissionPoints)
		itemPointsCompany.CompanyId = companyId
		itemPointsCompany.CompanyName = rsCalendar.CompanyName
		itemPointsCompany.CreateTime = time.Now()
		itemPointsCompany.ModifyTime = time.Now()
		e = models.AddCygxActivitySpecialPermissionPoints(itemPointsCompany)
		if e != nil {
			err = errors.New("AddCygxActivitySpecialPermissionPoints, Err: " + e.Error())
			return
		}
	}

	pars = make([]interface{}, 0)
	condition = ` AND activity_id = ?   AND table_source = 'roadshow'  AND researcher_id > 0  ORDER BY  id DESC   `
	pars = append(pars, activityId)
	//获取扣点的流水记录
	activityPointsBillList, e := models.GetCygxActivitySpecialTripBill(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialTripBill" + e.Error())
		return
	}
	mapActivityPointsBill := make(map[string]*models.CygxActivitySpecialTripBill)
	var itemsOld []*models.CygxActivitySpecialTripBill // 之前扣过点的流水记录
	for _, v := range activityPointsBillList {         //获取这场路演，某个研究员最后一次的扣点记录
		keyBill := fmt.Sprint(v.ResearcherId, "_CID", v.CompanyId)
		if mapActivityPointsBill[keyBill] == nil {
			mapActivityPointsBill[keyBill] = v
			if v.BillDetailed <= 0 && v.DoType == 1 {
				itemsOld = append(itemsOld, v)
			}
		}
		companyIds = append(companyIds, v.CompanyId)
	}

	//return
	pars = make([]interface{}, 0)
	condition = ` AND company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
	pars = append(pars, companyIds)
	//获取这些公司剩余的点数
	conpanyList, e := models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err: " + e.Error())
		return
	}

	//return
	for _, v := range conpanyList {
		if v.CompanyId != 0 {
			mapCompanyPoints[v.CompanyId] = v.Points
		}
	}

	var billDetailed float64
	var companyStatus string
	productDetail, e := company.GetCompanyProductDetailByCompanyId(companyId, 2)
	if e != nil {
		err = errors.New("GetCompanyProductDetailByCompanyId, Err: " + e.Error())
		return
	}
	if productDetail.Status == "正式" || mapCompanyPoints[companyId] > 0 {
		billDetailed = -1
	}
	if productDetail.Status != "正式" {
		companyStatus = "（" + productDetail.Status + "）"
	}

	//获取研究员信息
	researcherList, e := roadshow.GetRsCalendarResearcherListByIds([]int{activityId})
	if e != nil {
		err = errors.New("GetRsCalendarResearcherListByIds, Err: " + e.Error())
		return
	}
	//return
	var items []*models.CygxActivitySpecialTripBill
	var itemCompanys []*models.CygxActivitySpecialPermissionPoints
	mapOldResearcherId := make(map[string]bool)
	for _, user := range researcherList {
		if user.ResearcherName == "王芳" {
			continue
		}
		keyBill := fmt.Sprint(user.ResearcherId, "_CID", companyId)
		item := new(models.CygxActivitySpecialTripBill)
		item.ActivityId = activityId
		item.CreateTime = time.Now()

		item.CompanyId = rsCalendar.CompanyId
		item.CompanyName = rsCalendar.CompanyName
		item.ResearcherId = user.ResearcherId
		item.ResearcherName = user.ResearcherName
		item.RegisterPlatform = log.RegisterPlatform
		item.AdminId = log.AdminId
		item.Source = log.Source
		item.TableSource = utils.CYGX_OBJ_ROADSHOW

		if user.Status == 2 {
			mapOldResearcherId[keyBill] = true
			//如果没有扣点记录就对他们进行扣点处理
			if mapActivityPointsBill[keyBill] == nil || mapActivityPointsBill[keyBill].DoType == 2 {
				points := mapCompanyPoints[companyId] + billDetailed
				item.BillDetailed = billDetailed
				item.DoType = 1
				item.Content = fmt.Sprint(user.StartDate, " ", user.StartTime, "-", user.EndDate, " ", user.EndTime, " ", user.ResearcherName, "路演", companyStatus)
				item.Total = fmt.Sprint(points, "次")
				item.TableSource = utils.CYGX_OBJ_ROADSHOW
				//item.Points = mapCompanyPoints[user.CompanyId] - activityPointsSetDetail.UserPointsNum
				items = append(items, item)
				//更新对应机构的剩余点数
				itemCompany := new(models.CygxActivitySpecialPermissionPoints)
				itemCompany.CompanyId = companyId
				itemCompany.Points = points
				itemCompany.ModifyTime = time.Now()
				itemCompanys = append(itemCompanys, itemCompany)
				mapCompanyPoints[companyId] = points
			}
		} else {
			if mapActivityPointsBill[keyBill] != nil && mapActivityPointsBill[keyBill].DoType == 1 {
				mapOldResearcherId[keyBill] = true
				userItem := mapActivityPointsBill[keyBill]
				points := mapCompanyPoints[companyId] - userItem.BillDetailed
				item.BillDetailed = -userItem.BillDetailed
				item.DoType = 2
				item.Content = strings.Replace(userItem.Content, "路演", "路演--取消", -1)
				//item.Points =points
				item.Total = fmt.Sprint(points, "次")
				item.TableSource = utils.CYGX_OBJ_ROADSHOW

				item.CompanyId = rsCalendar.CompanyId
				item.CompanyName = rsCalendar.CompanyName
				item.ResearcherId = user.ResearcherId
				item.ResearcherName = user.ResearcherName
				items = append(items, item)

				//更新对应机构的剩余点数
				itemCompany := new(models.CygxActivitySpecialPermissionPoints)
				itemCompany.CompanyId = userItem.CompanyId
				itemCompany.Points = points
				itemCompany.ModifyTime = time.Now()
				itemCompanys = append(itemCompanys, itemCompany)
				mapCompanyPoints[userItem.CompanyId] = points
			}
		}

	}

	if len(itemsOld) > 0 {
		for _, user := range itemsOld {
			keyBill := fmt.Sprint(user.ResearcherId, "_CID", user.CompanyId)
			if mapOldResearcherId[keyBill] {
				continue
			}
			item := new(models.CygxActivitySpecialTripBill)
			item.ActivityId = activityId
			item.CreateTime = time.Now()
			item.CompanyId = user.CompanyId
			item.CompanyName = user.CompanyName
			item.RegisterPlatform = log.RegisterPlatform
			item.AdminId = log.AdminId
			item.Source = log.Source

			points := mapCompanyPoints[user.CompanyId] - user.BillDetailed
			item.BillDetailed = -user.BillDetailed
			item.DoType = 2
			item.Content = strings.Replace(user.Content, "路演", "路演--取消", -1)
			//item.Points =points
			item.Total = fmt.Sprint(points, "次")
			item.TableSource = utils.CYGX_OBJ_ROADSHOW

			item.CompanyId = user.CompanyId
			item.CompanyName = user.CompanyName
			item.ResearcherId = user.ResearcherId
			item.ResearcherName = user.ResearcherName
			items = append(items, item)

			//更新对应机构的剩余点数
			itemCompany := new(models.CygxActivitySpecialPermissionPoints)
			itemCompany.CompanyId = user.CompanyId
			itemCompany.Points = points
			itemCompany.ModifyTime = time.Now()
			itemCompanys = append(itemCompanys, itemCompany)
			mapCompanyPoints[user.CompanyId] = points
		}
	}

	e = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("AddCygxActivitySpecialTripBillMulti, Err: " + e.Error())
		return
	}
	return
}

//func init() {
//	initCygx14_5_01()
//}

func initCygx14_5_01() {
	// 获取流水信息
	var condition string
	var pars []interface{}
	condition += ` AND  points != 0  `
	list, err := models.GetCygxActivityPointsCompanyList(condition, pars)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, v := range list {
		fmt.Println("v.CompanyId", v.CompanyId)
		companyId := v.CompanyId
		total, e := models.GetCygxActivitySpecialPermissionPointsCountByCompanyId(companyId)
		if e != nil {
			err = errors.New("GetCygxActivityPointsCompanyCountByCompanyId, Err: " + e.Error())
			return
		}
		var companyPointsNum float64
		if total == 0 {
			companyPointsNum = 0
			itemPointsCompany := new(models.CygxActivitySpecialPermissionPoints)
			itemPointsCompany.CompanyId = companyId
			itemPointsCompany.CompanyName = v.CompanyName
			itemPointsCompany.CreateTime = time.Now()
			itemPointsCompany.ModifyTime = time.Now()
			e = models.AddCygxActivitySpecialPermissionPoints(itemPointsCompany)
			if e != nil {
				err = errors.New("AddCygxActivitySpecialPermissionPoints, Err: " + e.Error())
				return
			}
		} else {
			// 获取用户所在公司剩余的点
			companyPointsNum, e = models.GetCygxActivitySpecialPermissionPoints(v.CompanyId)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCygxActivitySpecialPermissionPoints, Err: " + e.Error())
				return
			}
		}

		//获取需要添加的流水信息
		var items []*models.CygxActivitySpecialTripBill
		itemBill := new(models.CygxActivitySpecialTripBill)

		itemBill.CreateTime = time.Now()

		itemBill.CompanyId = v.CompanyId
		itemBill.CompanyName = v.CompanyName
		itemBill.Source = 3
		itemBill.DoType = 0
		itemBill.BillDetailed = v.Points / 2 // 流水减一
		//itemBill.RegisterPlatform = utils.REGISTER_PLATFORM

		itemBill.Content = "研选点数清零，1/2比例折算进专项/路演点数"
		itemBill.Total = fmt.Sprint(companyPointsNum+itemBill.BillDetailed, "次")
		itemBill.TableSource = utils.CYGX_OBJ_ACTIVITYSPECIAL
		items = append(items, itemBill)
		//更新对应机构的剩余点数
		var itemCompanys []*models.CygxActivitySpecialPermissionPoints
		itemCompany := new(models.CygxActivitySpecialPermissionPoints)
		itemCompany.CompanyId = v.CompanyId
		itemCompany.Points = companyPointsNum + itemBill.BillDetailed
		itemCompany.ModifyTime = time.Now()
		itemCompanys = append(itemCompanys, itemCompany)

		err = models.AddCygxActivitySpecialTripBillMulti(items, itemCompanys)
	}
	fmt.Println("enddd145")
}
