package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/models/company"
	"hongze/hongze_cygx/utils"
	"strconv"
	"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
}

// 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
			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.GetCygxActivityPointsCompanyCountByCompanyId(companyId)
	if e != nil {
		err = errors.New("GetCygxActivityPointsCompanyCountByCompanyId, Err: " + e.Error())
		return
	}
	var companyPointsNum float64
	if total == 0 {
		companyPointsNum = 0
		itemPointsCompany := new(models.CygxActivityPointsCompany)

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

		e = models.AddCygxActivityPointsCompany(itemPointsCompany)
		if e != nil {
			err = errors.New("AddCygxActivityPointsCompany, Err: " + e.Error())
			return
		}
	} else {
		// 获取用户所在公司剩余的点
		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 = -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 + "--报名"
	item.Points = companyPointsNum - activityPointsSetDetail.UserPointsNum
	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
}

// 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.GetCompanyPoints(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 bill_detailed < 0   ORDER BY id DESC LIMIT 1  `
	pars = append(pars, activityId, userId)
	activityPointsBillDetail, e := models.GetCygxActivityPointsBillDetailByCondition(condition, pars)
	if e != nil {
		err = errors.New("activityPointsBillDetail" + 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 = -activityPointsBillDetail.BillDetailed
	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 - activityPointsBillDetail.BillDetailed
	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
}

// 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.GetCompanyPoints(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 bill_detailed < 0   ORDER BY id DESC LIMIT 1  `
	pars = append(pars, activityId, comapnyId)
	activityPointsBillDetail, e := models.GetCygxActivityPointsBillDetailByCondition(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyPoints, Err: " + e.Error())
		return
	}
	var items []*models.CygxActivityPointsBill
	item := new(models.CygxActivityPointsBill)
	var itemCompanys []*models.CygxActivityPointsCompany
	itemCompany := new(models.CygxActivityPointsCompany)

	if activityPointsBillDetail == nil { //如果是空的就添加
		//获取需要添加的流水信息
		//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
		items = append(items, item)

		//更新对应机构的剩余点数
		itemCompany.CompanyId = comapny.CompanyId
		itemCompany.Points = item.Points
		itemCompany.ModifyTime = time.Now()
		itemCompanys = append(itemCompanys, itemCompany)
		e = models.AddCygxActivityPointsBillMulti(items, itemCompanys)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("AddCygxActivityPointsBillMulti, Err: " + e.Error())
			return
		}
	} else {
		//如果存在就进行对比修改
		if activityPointsSetDetail.CompanyPointsNum != -activityPointsBillDetail.BillDetailed {
			item.Id = activityPointsBillDetail.Id
			item.BillDetailed = -activityPointsSetDetail.CompanyPointsNum
			item.Points = companyPointsNum - activityPointsBillDetail.BillDetailed - activityPointsSetDetail.CompanyPointsNum
			items = append(items, item)

			//更新对应机构的剩余点数
			itemCompany.CompanyId = comapny.CompanyId
			itemCompany.Points = item.Points
			itemCompany.ModifyTime = time.Now()
			itemCompanys = append(itemCompanys, itemCompany)
			e = models.UpdateCygxActivityPointsBillMulti(items, itemCompanys)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("UpdateCygxActivityPointsBillMulti, 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.CygxActivityPointsBill

	var itemCompanys []*models.CygxActivityPointsCompany
	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.GetCompanyPoints(comapny.CompanyId)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCompanyPoints, Err: " + e.Error())
				return
			}
			item := new(models.CygxActivityPointsBill)
			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
			items = append(items, item)

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

		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.GetCygxActivityPointsCompanyList(condition, pars)
				if e != nil && e.Error() != utils.ErrNoRow() {
					err = errors.New("GetCygxActivityPointsCompanyList, 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.CygxActivityPointsBill)
					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]
					items = append(items, item)

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

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

		if comapnyId > 0 {
			comapny, e := models.GetCompanyById(comapnyId)
			if e != nil {
				err = errors.New("GetCompanyById" + e.Error())
				return
			}
			// 获取用户所在公司剩余的点
			companyPointsNum, e := models.GetCompanyPoints(comapny.CompanyId)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCompanyPoints, Err: " + e.Error())
				return
			}
			item := new(models.CygxActivityPointsBill)
			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
			items = append(items, item)
			//更新对应机构的剩余点数
			itemCompany := new(models.CygxActivityPointsCompany)
			itemCompany.CompanyId = comapny.CompanyId
			itemCompany.Points = item.Points
			itemCompany.ModifyTime = time.Now()
			itemCompanys = append(itemCompanys, itemCompany)
			mapCompanyPoints[comapnyId] = item.Points
		}

		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.GetCygxActivityPointsCompanyList(condition, pars)
				if e != nil && e.Error() != utils.ErrNoRow() {
					err = errors.New("GetCygxActivityPointsCompanyList, 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 = ?   `
				pars = append(pars, activityId)
				//获取扣点的流水记录
				activityPointsBillList, e := models.GetCygxActivityPointsBillList(condition, pars)
				if e != nil && e.Error() != utils.ErrNoRow() {
					err = errors.New("GetCygxActivityPointsBillList" + 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.CygxActivityPointsBill)
					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]
					items = append(items, item)

					//更新对应机构的剩余点数
					itemCompany := new(models.CygxActivityPointsCompany)
					itemCompany.CompanyId = user.CompanyId
					itemCompany.Points = item.Points
					itemCompany.ModifyTime = time.Now()
					itemCompanys = append(itemCompanys, itemCompany)
					mapCompanyPoints[user.CompanyId] = item.Points
				}
			}
		}
	}
	e = models.AddCygxActivityPointsBillMulti(items, itemCompanys)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("AddCygxActivityPointsBillMulti, 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)
		}
	}()

	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 = ? AND  is_meeting = 1 `
	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)
	}

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

	pars = make([]interface{}, 0)
	condition = ` AND activity_id = ? AND  mobile  != ''  `
	pars = append(pars, activityId)
	//获取扣点的流水记录
	activityPointsBillList, e := models.GetCygxActivityPointsBillList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityPointsBillList" + e.Error())
		return
	}
	mapActivityPointsBill := make(map[string]*models.CygxActivityPointsBill)
	for _, v := range activityPointsBillList {
		mapActivityPointsBill[v.Mobile] = v
	}
	//return
	for _, v := range conpanyList {
		if v.CompanyId != 0 {
			mapCompanyPoints[v.CompanyId] = v.Points
		}
	}

	//return
	var items []*models.CygxActivityPointsBill
	var itemCompanys []*models.CygxActivityPointsCompany
	for _, user := range signUpDetailList {
		item := new(models.CygxActivityPointsBill)
		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 mapActivityPointsBill[user.Mobile] == nil {
			item.BillDetailed = -activityPointsSetDetail.UserPointsNum
			item.DoType = 1
			item.Content = activityInfo.ActivityName + "--活动到会"
			item.Points = mapCompanyPoints[user.CompanyId] - activityPointsSetDetail.UserPointsNum
			items = append(items, item)
			//更新对应机构的剩余点数
			itemCompany := new(models.CygxActivityPointsCompany)
			itemCompany.CompanyId = user.CompanyId
			itemCompany.Points = item.Points
			itemCompany.ModifyTime = time.Now()
			itemCompanys = append(itemCompanys, itemCompany)
			mapCompanyPoints[user.CompanyId] = item.Points
		} else {
			//第二次提交改成未到会的，对其进行返点处理
			if mapActivityPointsBill[user.Mobile].BillDetailed < 0 {
				item.BillDetailed = activityPointsSetDetail.UserPointsNum
				item.DoType = 2
				item.Content = activityInfo.ActivityName + "--活动取消到会"
				item.Points = mapCompanyPoints[user.CompanyId] + activityPointsSetDetail.UserPointsNum
				items = append(items, item)

				//更新对应机构的剩余点数
				itemCompany := new(models.CygxActivityPointsCompany)
				itemCompany.CompanyId = user.CompanyId
				itemCompany.Points = item.Points
				itemCompany.ModifyTime = time.Now()
				itemCompanys = append(itemCompanys, itemCompany)
				mapCompanyPoints[user.CompanyId] = item.Points
			}
		}
	}
	e = models.AddCygxActivityPointsBillMulti(items, itemCompanys)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("AddCygxActivityPointsBillMulti, 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.GetCompanyPoints(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.GetCompanyPoints(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
}
