package services

import (
	"context"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/models/company"
	"hongze/hongze_cygx/models/rai_serve"
	"hongze/hongze_cygx/models/roadshow"
	"hongze/hongze_cygx/utils"
	"strings"
	"time"
)

// var startWeekDate = time.Now().AddDate(0, 0, -75).Format(utils.FormatDate) + " 23:59:59" // 查询12周以内的数据
//var startWeekDate = time.Now().AddDate(0, 0, -75).Format(utils.FormatDateTime) // 查询12周以内的数据

//权益服务统计

//上线跑的脚本
//func initJob() {
//	UpdateRaiServeCompany()              //1
//	UpdateCygxRaiServeBillByCompanyIds() //2
//	UpdateCygxRaiServeBillWeek()         // 3
//	UpdateWeekAvg()                      // 4
//}

//func init() {
//	UpdateWeekAvg() //1
//}

//func init() {
//	UpdateRaiServeCompany()              //1
//	UpdateCygxRaiServeBillByCompanyIds() //2
//	UpdateCygxRaiServeBillWeekTask()     // 3
//	UpdateWeekAvg()                      // 4
//}

// 定时任务处理权益服务公司
func UpdateRaiServeCompanyDate(cont context.Context) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("定时任务处理权益服务公司 失败 UpdateRaiServeCompanyDate  ，err：", err.Error()), 2)
		}
	}()
	err = UpdateRaiServeCompany()
	return
}

// 定时任务处理权益服务记录明细
func UpdateRaiServeBillDate(cont context.Context) (err error) {
	//func UpdateRaiServeBillDate() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("定时任务处理权益服务公司 失败 UpdateRaiServeBillDate  ，err：", err.Error()), 2)
		}
	}()

	err = UpdateRaiServeCompany() // 处理共享机构信息
	if err != nil {
		return
	}

	err = UpdateCygxRaiServeBillByCompanyIds() // 处理个人流水记录
	if err != nil {
		return
	}

	err = UpdateCygxRaiServeBillWeekTask() // 更新周度服务明细
	if err != nil {
		return
	}

	err = UpdateWeekAvg() //更新最近四周平均覆盖率，是否标红，权限，时间，金额
	if err != nil {
		return
	}
	return
}

// 更新现有的权益服务客户数据
func UpdateRaiServeCompany() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("更新现有的权益服务客户数据失败 UpdateRaiServeCompany："+err.Error(), 2)
		}
	}()

	var condition string
	var pars []interface{}
	condition = `    AND p.product_id = 2 AND  (p.group_id IN (` + utils.RAI_SERVE_GROUP_ID + `)  OR  p.share_group_id IN (` + utils.RAI_SERVE_GROUP_ID + `) ) `
	//pars = append(pars, utils.RAI_SERVE_GROUP_ID, utils.RAI_SERVE_GROUP_ID)
	listCompanyProduct, e := company.GetCompanyProductAndCompanyListByCondition(condition, pars)
	if e != nil {
		err = errors.New("GetCompanyProductListByCondition, Err: " + e.Error())
		return
	}
	//fmt.Println(len(listCompanyProduct))
	//return

	raiServeCompanyList, e := rai_serve.GetCygxRaiServeCompanyAllList()
	if e != nil {
		err = errors.New("GetCygxRaiServeCompanyAllList, Err: " + e.Error())
		return
	}

	mapOLdCompany := make(map[int]bool)
	mapOLdCompanyDate := make(map[int]string)
	for _, v := range raiServeCompanyList {
		mapOLdCompany[v.CompanyId] = true
		mapOLdCompanyDate[v.CompanyId] = fmt.Sprint(v.CompanyId, v.CompanyName, v.SellerId, v.StartDate, v.EndDate, v.ShareSeller, v.ShareSellerId, v.Status, v.GroupId, v.ShareGroupId)
	}

	mapNewCompany := make(map[int]bool)
	var delCompanyIds []int // 需要删除的公司ID
	for _, v := range listCompanyProduct {
		mapNewCompany[v.CompanyId] = true
	}
	for _, v := range raiServeCompanyList {
		if !mapNewCompany[v.CompanyId] {
			delCompanyIds = append(delCompanyIds, v.CompanyId)
		}
	}

	var items []*rai_serve.CygxRaiServeCompany
	var itemsUpdate []*rai_serve.CygxRaiServeCompany
	for _, v := range listCompanyProduct {
		item := new(rai_serve.CygxRaiServeCompany)
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		item.CreateTime = time.Now()
		item.SellerId = v.SellerId
		item.SellerName = v.SellerName
		item.StartDate = v.StartDate
		item.EndDate = v.EndDate
		item.ShareSeller = v.ShareSeller
		item.ShareSellerId = v.ShareSellerId
		item.Status = v.Status
		item.GroupId = v.GroupId
		item.ShareGroupId = v.ShareGroupId
		if !mapOLdCompany[v.CompanyId] {
			items = append(items, item) // 如果原有数据不存在就新增
		} else {
			if mapOLdCompanyDate[v.CompanyId] != fmt.Sprint(v.CompanyId, v.CompanyName, v.SellerId, v.StartDate, v.EndDate, v.ShareSeller, v.ShareSellerId, v.Status, v.GroupId, v.ShareGroupId) {
				itemsUpdate = append(itemsUpdate, item) // 新老数据不一致就进行修改
			}
		}
	}

	//fmt.Println("items", len(items))
	//fmt.Println("itemsUpadte222", len(itemsUpdate))
	//fmt.Println("delCompanyIds", len(delCompanyIds))
	//fmt.Println("delCompanyIds", (delCompanyIds))
	//return
	//先删除老的再添加新的
	e = rai_serve.AddCygxRaiServeCompanyMulti(items, itemsUpdate, delCompanyIds)
	if e != nil {
		err = errors.New("AddCygxRaiServeCompanyMulti, Err: " + e.Error())
		return
	}

	return
}

// GetCompanyContractPermissionNameMapById 获取合并之后的合同所对应的权限种类名称
func GetCompanyContractPermissionNameMapById(companyContractIds []int) (mapContractResp map[int]string, err error) {
	//return
	lenArr := len(companyContractIds)
	if lenArr == 0 {
		return
	}
	var condition string
	var pars []interface{}

	condition += " AND  company_contract_id IN (" + utils.GetOrmInReplace(lenArr) + ")"
	pars = append(pars, companyContractIds)

	//companyContractList, e := company.GetCompanyContractList(condition, pars)
	//if e != nil && e.Error() != utils.ErrNoRow() {
	//	err = errors.New("GetCompanyContractList, Err: " + e.Error())
	//	return
	//}

	permissionList, e := models.GetChartPermissionList()
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetChartPermissionList, Err: " + e.Error())
		return
	}
	mappermissionName := make(map[int]string)
	for _, v := range permissionList {
		if v.ProductId == 2 {
			mappermissionName[v.ChartPermissionId] = v.Remark
		}
	}

	mapContractIdPerssion := make(map[int]string) //单个合同ID所对应的套餐或者权限名称
	//for _, v := range companyContractList {
	//	if v.RaiPackageType == 1 {
	//		mapContractIdPerssion[v.CompanyContractId] = "70w套餐,"
	//	}
	//	if v.RaiPackageType == 2 {
	//		mapContractIdPerssion[v.CompanyContractId] = "45w套餐,"
	//	}
	//}

	companyContractPermissionList, e := company.GetCompanyContractPermissionList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractPermissionList, Err: " + e.Error())
		return
	}

	mapIsUpgrade := make(map[string]bool) //合同ID对应的行业是否有升级
	for _, v := range companyContractPermissionList {
		//如果开通的不是整个套餐，那么就做单独的子权限处理
		if strings.Count(mapContractIdPerssion[(v.CompanyContractId)], "w套餐") == 0 {
			if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
				if v.ExpensiveYx == 1 {
					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(5w),"
				} else if v.ExpensiveYx == 2 {
					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(10w),"
				} else {
					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + ","
				}
			} else {
				mapContractIdPerssion[(v.CompanyContractId)] += mappermissionName[v.ChartPermissionId] + ","
				if v.IsUpgrade == 1 {
					//合同ID，权限名称形成唯一的主键索引
					perssionName := mappermissionName[v.ChartPermissionId]
					perssionName = strings.Replace(perssionName, "(客观)", "", -1)
					perssionName = strings.Replace(perssionName, "(主观)", "", -1)
					mapIsUpgrade[fmt.Sprint(v.CompanyContractId, "perssionName", perssionName)] = true
				}
			}
		} else {
			if v.ChartPermissionId == utils.ZHUAN_JIA_ID {
				mapContractIdPerssion[(v.CompanyContractId)] += utils.ZHUAN_JIA_NAME + ","
			}
			if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
				if v.ExpensiveYx == 1 {
					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(5w),"
				} else if v.ExpensiveYx == 2 {
					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(10w),"
				} else {
					mapContractIdPerssion[(v.CompanyContractId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + ","
				}
			}

			if v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
				mapContractIdPerssion[(v.CompanyContractId)] += utils.YAN_XUAN_KOU_DIAN_BAO_NAME + ","
			}
		}
	}
	//合并客观权限
	for k, v := range mapContractIdPerssion {
		perssionName := v
		if strings.Count(v, utils.YI_YAO_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "医药(主观)", "医药", -1)
			perssionName = strings.Replace(perssionName, "医药(客观)", "", -1)
		}
		if strings.Count(v, utils.XIAO_FEI_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "消费(主观)", "消费", -1)
			perssionName = strings.Replace(perssionName, "消费(客观)", "", -1)
		}
		if strings.Count(v, utils.KE_JI_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "科技(主观)", "科技", -1)
			perssionName = strings.Replace(perssionName, "科技(客观)", "", -1)
		}
		if strings.Count(v, utils.ZHI_ZAO_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "智造(主观)", "智造", -1)
			perssionName = strings.Replace(perssionName, "智造(客观)", "", -1)
		}

		perssionName = strings.TrimRight(perssionName, ",")
		mapContractIdPerssion[k] = perssionName
	}
	mapContractResp = make(map[int]string, 0)

	//过滤多余的","
	for k, v := range mapContractIdPerssion {
		sliceName := strings.Split(v, ",")
		var nameArr []string
		for _, vName := range sliceName {
			if vName == "" {
				continue
			}
			if mapIsUpgrade[fmt.Sprint(k, "perssionName", vName)] {
				vName += "(升级)"
			}
			nameArr = append(nameArr, vName)
		}
		mapContractResp[k] = strings.Join(nameArr, ",")
	}
	return
}

// 根据公司ID获取目前行业所对应的正式权限
func GetCompanyReportPermissionNameMapByCompanyId(companyIds []int) (mapContractResp map[int]string, err error) {
	lenArr := len(companyIds)
	if lenArr == 0 {
		return
	}
	var condition string
	var pars []interface{}

	condition += " AND  company_id IN (" + utils.GetOrmInReplace(lenArr) + ") AND product_id = 2 AND status  IN ( '正式','永续') "
	pars = append(pars, companyIds)

	permissionList, e := models.GetChartPermissionList()
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetChartPermissionList, Err: " + e.Error())
		return
	}
	mappermissionName := make(map[int]string)
	for _, v := range permissionList {
		if v.ProductId == 2 {
			mappermissionName[v.ChartPermissionId] = v.Remark
		}
	}

	mapContractIdPerssion := make(map[int]string) //单个合同ID所对应的套餐或者权限名称

	companyReportPermissionList, e := models.GetCompanyReportPermissionList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyReportPermissionList, Err: " + e.Error())
		return
	}

	mapIsUpgrade := make(map[string]bool) //合同ID对应的行业是否有升级
	for _, v := range companyReportPermissionList {
		//如果开通的不是整个套餐，那么就做单独的子权限处理
		if strings.Count(mapContractIdPerssion[(v.CompanyId)], "w套餐") == 0 {
			if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
				if v.ExpensiveYx == 1 {
					mapContractIdPerssion[(v.CompanyId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(5w),"
				} else if v.ExpensiveYx == 2 {
					mapContractIdPerssion[(v.CompanyId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(10w),"
				} else {
					mapContractIdPerssion[(v.CompanyId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + ","
				}
			} else {
				mapContractIdPerssion[(v.CompanyId)] += mappermissionName[v.ChartPermissionId] + ","
				if v.IsUpgrade == 1 {
					//合同ID，权限名称形成唯一的主键索引
					perssionName := mappermissionName[v.ChartPermissionId]
					perssionName = strings.Replace(perssionName, "(客观)", "", -1)
					perssionName = strings.Replace(perssionName, "(主观)", "", -1)
					mapIsUpgrade[fmt.Sprint(v.CompanyId, "perssionName", perssionName)] = true
				}
			}
		} else {
			if v.ChartPermissionId == utils.ZHUAN_JIA_ID {
				mapContractIdPerssion[(v.CompanyId)] += utils.ZHUAN_JIA_NAME + ","
			}
			if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
				if v.ExpensiveYx == 1 {
					mapContractIdPerssion[(v.CompanyId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(5w),"
				} else if v.ExpensiveYx == 2 {
					mapContractIdPerssion[(v.CompanyId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + "(10w),"
				} else {
					mapContractIdPerssion[(v.CompanyId)] += utils.CHART_PERMISSION_NAME_MF_YANXUAN + ","
				}
			}

			if v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
				mapContractIdPerssion[(v.CompanyId)] += utils.YAN_XUAN_KOU_DIAN_BAO_NAME + ","
			}
		}
	}
	//合并客观权限
	for k, v := range mapContractIdPerssion {
		perssionName := v
		if strings.Count(v, utils.YI_YAO_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "医药(主观)", "医药", -1)
			perssionName = strings.Replace(perssionName, "医药(客观)", "", -1)
		}
		if strings.Count(v, utils.XIAO_FEI_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "消费(主观)", "消费", -1)
			perssionName = strings.Replace(perssionName, "消费(客观)", "", -1)
		}
		if strings.Count(v, utils.KE_JI_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "科技(主观)", "科技", -1)
			perssionName = strings.Replace(perssionName, "科技(客观)", "", -1)
		}
		if strings.Count(v, utils.ZHI_ZAO_NAME) == 2 {
			perssionName = strings.Replace(perssionName, "智造(主观)", "智造", -1)
			perssionName = strings.Replace(perssionName, "智造(客观)", "", -1)
		}

		perssionName = strings.TrimRight(perssionName, ",")
		mapContractIdPerssion[k] = perssionName
	}
	mapContractResp = make(map[int]string, 0)

	//过滤多余的","
	for k, v := range mapContractIdPerssion {
		sliceName := strings.Split(v, ",")
		var nameArr []string
		for _, vName := range sliceName {
			if vName == "" {
				continue
			}
			if mapIsUpgrade[fmt.Sprint(k, "perssionName", vName)] {
				vName += "(升级)"
			}
			nameArr = append(nameArr, vName)
		}
		mapContractResp[k] = strings.Join(nameArr, ",")
	}
	return
}

// Redis对列消息中的结构体
type RaiServeBillRedis struct {
	Content          string    `comment:"服务内容说明"`
	UserId           int       `comment:"用户ID"`
	ComapnyId        int       `comment:"公司ID"`
	SourceId         int       `comment:"来源ID"`
	Source           string    `comment:"来源"`
	RegisterPlatform int       `comment:"来源 1小程序，2：网页"`
	ViewTime         time.Time `comment:"浏览时间"`
}

//func init() {
//	UpdateCygxRaiServeBillByCompanyIds()
//}

// 批量更新企业服务明细记录
func UpdateCygxRaiServeBillByCompanyIds() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("批量更新企业服务明细记录失败： UpdateCygxRaiServeBillByCompanyIds Err"+err.Error(), 2)
		}
	}()
	var delBillIds []int
	var startWeekDate = time.Now().AddDate(0, 0, -75).Format(utils.FormatDate) + " 23:59:59"
	fmt.Println("UpdateCygxRaiServeBillByCompanyIds start")
	companyList, e := rai_serve.GetCygxRaiServeCompanyAllList()
	if e != nil {
		err = errors.New("GetCygxRaiServeCompanyAllList, Err: " + e.Error())
		return
	}
	var companyIds []int
	var items []*rai_serve.CygxRaiServeBill
	for _, v := range companyList {
		companyIds = append(companyIds, v.CompanyId)
	}

	lencompanyId := len(companyIds)
	listisMakeruser, e := models.GetWxUserisMakerByCompanyIds(companyIds)
	if e != nil {
		err = errors.New("GetWxUserisMakerByCompanyIds, Err: " + e.Error())
		return
	}
	mapUserMaker := make(map[int]bool)
	mapUserMobileUserId := make(map[string]int)
	for _, v := range listisMakeruser {
		mapUserMaker[v.UserId] = true
		mapUserMobileUserId[v.Mobile] = v.UserId
	}

	var condition string
	var pars []interface{}

	condition = " AND  art.company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND art.create_time > ?  "
	pars = append(pars, companyIds, startWeekDate)

	fmt.Println("startWeekDate", startWeekDate)
	//研选专栏阅读记录内容
	{
		listYanxuanSpecialRecord, e := models.GetCygxYanxuanSpecialRecordRespListAll(condition+"  GROUP BY art.user_id, art.yanxuan_special_id  ORDER BY art.create_time ASC ", pars)
		if e != nil {
			err = errors.New("GetCygxYanxuanSpecialRecordRespListAll, Err: " + e.Error())
			return
		}

		var yanxuanspecialIds []int
		for _, v := range listYanxuanSpecialRecord {
			yanxuanspecialIds = append(yanxuanspecialIds, v.YanxuanSpecialId)
		}

		var conditionYanxuanSpecial string
		var parsYanxuanSpecial []interface{}
		conditionYanxuanSpecial += `  AND  id  IN (` + utils.GetOrmInReplace(len(yanxuanspecialIds)) + `) `
		parsYanxuanSpecial = append(parsYanxuanSpecial, yanxuanspecialIds)
		listYanxuanSpecial, e := models.GetYanxuanSpecialListBycondition(conditionYanxuanSpecial, parsYanxuanSpecial, 0, len(yanxuanspecialIds))
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetYanxuanSpecialListBycondition, Err: " + e.Error())
			return
		}
		mapYanxuanSpecialTitle := make(map[int]string)

		for _, v := range listYanxuanSpecial {
			mapYanxuanSpecialTitle[v.Id] = v.Title
		}

		//研选阅读明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'yanxuanspecial' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillByYanxuanspecial, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapYanxuanspecialBill := make(map[string]bool)
		for _, v := range listBillByYanxuanspecial {
			mapYanxuanspecialBill[fmt.Sprint("UID_", v.UserId, "SID_", v.SourceId)] = true
		}

		for _, v := range listYanxuanSpecialRecord {
			if mapYanxuanspecialBill[fmt.Sprint("UID_", v.UserId, "SID_", v.YanxuanSpecialId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = mapYanxuanSpecialTitle[v.YanxuanSpecialId]
			item.ServeTypeId = 5
			item.ServeTypeName = "阅读uv"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			item.RegisterPlatform = v.RegisterPlatform
			item.ServeCount = 0.5

			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.YanxuanSpecialId
			item.Source = utils.CYGX_OBJ_YANXUANSPECIAL
			item.CreateTime = time.Now()
			item.ViewTime = v.CreateTime
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			items = append(items, item)
		}
	}
	//研选专栏阅读记录内容end

	//文章阅读记录内容
	{
		listArticleRecord, e := models.GetCygxArticleHistoryRecordAllListNoLimit(condition+"  GROUP BY art.user_id, art.article_id  ORDER BY art.create_time ASC ", pars)
		if e != nil {
			err = errors.New("GetCygxArticleHistoryRecordAllListNoLimit, Err: " + e.Error())
			return
		}
		//文章阅读明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'article' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillByArticle, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapArticleBill := make(map[string]bool)
		for _, v := range listBillByArticle {
			mapArticleBill[fmt.Sprint("UID_", v.UserId, "SID_", v.SourceId)] = true
		}

		//部分数据来源没有存用户姓名，重新查一下
		var userIds []int
		for _, v := range listArticleRecord {
			userIds = append(userIds, v.UserId)
		}
		ListUser, e := models.GetWxUserListByUserIdsArr(userIds)
		if e != nil {
			err = errors.New("GetWxUserListByUserIdsArr, Err: " + e.Error())
			return
		}
		mapUserName := make(map[int]string)
		for _, v := range ListUser {
			mapUserName[v.UserId] = v.RealName
		}

		for _, v := range listArticleRecord {
			if mapArticleBill[fmt.Sprint("UID_", v.UserId, "SID_", v.ArticleId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = v.Title
			item.ServeTypeId = 5
			item.ServeTypeName = "阅读uv"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = mapUserName[v.UserId]
			item.RegisterPlatform = v.RegisterPlatform
			item.ServeCount = 0.5

			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.ArticleId
			item.Source = utils.CYGX_OBJ_ARTICLE
			item.CreateTime = time.Now()
			item.ViewTime = v.CreateTime
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			if strings.Contains(v.CategoryName, "固收") {
				item.ChartPermissionName = utils.GU_SHOU_NAME
				item.ChartPermissionId = utils.GU_SHOU_ID_CHART
			}
			if strings.Contains(v.CategoryName, "策略") {
				item.ChartPermissionName = utils.CE_LUE_NAME
				item.ChartPermissionId = utils.CE_LUE_ID
			}
			items = append(items, item)
		}
	}
	//文章阅读记录内容 end

	//活动记录内容
	{
		condition = " AND  art.company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND a.activity_time > ?  "
		signUpDetailList, e := models.GetSignupDetailBySignupjoinactivity(condition+"  ORDER BY a.activity_time ASC ", pars)
		if e != nil {
			err = errors.New("GetSignupDetailBySignupjoinactivity, Err: " + e.Error())
			return
		}

		//文章阅读明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'activity' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillByActivity, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapActivityeBill := make(map[string]bool)
		for _, v := range listBillByActivity {
			mapActivityeBill[fmt.Sprint("UID_", v.Mobile, "SID_", v.SourceId)] = true
		}

		mapArticleBillDel := make(map[string]bool)
		for _, v := range signUpDetailList {
			mapArticleBillDel[fmt.Sprint("UID_", v.UserId, "SID_", v.ActivityId)] = true
		}

		mapDelActivityBillDel := make(map[string]bool)
		for _, v := range signUpDetailList {
			mapDelActivityBillDel[fmt.Sprint("UID_", v.UserId, "SID_", v.ActivityId)] = true
		}
		for _, v := range listBillByActivity {
			if !mapDelActivityBillDel[fmt.Sprint("UID_", v.UserId, "SID_", v.SourceId)] { // 如果内容存在就插入删除ID中
				delBillIds = append(delBillIds, v.BillId)
			}
		}

		for _, v := range signUpDetailList {
			if v.UserId == 0 && v.Mobile != "" {
				v.UserId = mapUserMobileUserId[v.Mobile] // 空降的部分联系人 userid 为0这里做一下修复
			}

			if mapActivityeBill[fmt.Sprint("UID_", v.Mobile, "SID_", v.ActivityId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = v.ActivityName
			if v.ActivityType == 1 {
				item.ServeTypeId = 1
				item.ServeTypeName = "线上活动"
			} else {
				item.ServeTypeId = 2
				item.ServeTypeName = "线下活动"
			}

			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			//item.RegisterPlatform = v.RegisterPlatform
			item.ServeCount = 1
			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.ActivityId
			item.Source = utils.CYGX_OBJ_ACTIVITY
			item.CreateTime = time.Now()
			item.ViewTime = v.ActivityTime
			item.ChartPermissionName = v.ChartPermissionName
			item.ChartPermissionId = v.ChartPermissionId
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			items = append(items, item)
		}
	}
	//活动记录内容 end

	//专项调研活动记录内容
	{
		condition = " AND  art.company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND a.activity_time > ?  "
		activitySpecialList, e := models.GetCygxActivitySpecialMeetingDetailList(condition+"  ORDER BY a.activity_time ASC ", pars)
		if e != nil {
			err = errors.New("GetCygxActivitySpecialMeetingDetailList, Err: " + e.Error())
			return
		}

		//专项调研活动明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'activityspecial' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillByActivitySpecial, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapActivitySpecial := make(map[string]bool)
		for _, v := range listBillByActivitySpecial {
			mapActivitySpecial[fmt.Sprint("UID_", v.UserId, "SID_", v.SourceId)] = true
		}

		mapDelActivitySpecial := make(map[string]bool)
		for _, v := range activitySpecialList {
			mapDelActivitySpecial[fmt.Sprint("UID_", v.UserId, "SID_", v.ActivityId)] = true
		}
		for _, v := range listBillByActivitySpecial {
			if !mapDelActivitySpecial[fmt.Sprint("UID_", v.UserId, "SID_", v.SourceId)] { // 如果内容存在就插入删除ID中
				delBillIds = append(delBillIds, v.BillId)
			}
		}

		for _, v := range activitySpecialList {
			if mapActivitySpecial[fmt.Sprint("UID_", v.UserId, "SID_", v.ActivityId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = v.ResearchTheme
			item.ServeTypeId = 3
			item.ServeTypeName = "专项调研"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			//item.RegisterPlatform = v.RegisterPlatform
			item.ServeCount = 1
			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.ActivityId
			item.Source = utils.CYGX_OBJ_ACTIVITYSPECIAL
			item.CreateTime = time.Now()
			item.ViewTime = v.ActivityTime
			item.ChartPermissionName = v.ChartPermissionName
			item.ChartPermissionId = v.ChartPermissionId
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			items = append(items, item)
		}
	}
	//专项调研活动记录内容 end

	//1v1路演
	{
		condition = " AND  art.company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND rs.start_date > ?  "
		calendarMeetingUserList, e := roadshow.GetRsCalendarMeetingUserList(condition+"  ORDER BY rs.start_date ASC ", pars)
		if e != nil {
			err = errors.New("GetRsCalendarMeetingUserList, Err: " + e.Error())
			return
		}
		var rsCalendarIds []int
		for _, v := range calendarMeetingUserList {
			rsCalendarIds = append(rsCalendarIds, v.RsCalendarId)
		}

		//获取研究员信息
		researchers, e := roadshow.GetRsCalendarResearcherListByIds(rsCalendarIds)
		if e != nil {
			err = errors.New("GetRsCalendarResearcherListByIds, Err: " + e.Error())
			return
		}
		mapResearcherName := make(map[int][]string)
		for _, v := range researchers {
			mapResearcherName[v.RsCalendarId] = append(mapResearcherName[v.RsCalendarId], v.ResearcherName)
		}

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

		var ceLueResearcherName []string
		var guShouResearcherName []string

		for _, v := range listEmail {
			if v.ChartPermissionName == utils.CE_LUE_NAME {
				ceLueResearcherName = append(ceLueResearcherName, v.Name)
			}
			if v.ChartPermissionName == utils.GU_SHOU_NAME {
				guShouResearcherName = append(guShouResearcherName, v.Name)
			}
		}

		//专项调研活动明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'rscalendar' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillByRscalendar, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapRscalendarBill := make(map[string]bool)
		for _, v := range listBillByRscalendar {
			mapRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.SourceId)] = true
		}

		mapDelRscalendarBill := make(map[string]bool)
		for _, v := range calendarMeetingUserList {
			mapDelRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RsCalendarId)] = true
		}
		for _, v := range listBillByRscalendar {
			if !mapDelRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.SourceId)] { // 如果内容存在就插入删除ID中
				delBillIds = append(delBillIds, v.BillId)
			}
		}

		for _, v := range calendarMeetingUserList {
			if mapRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RsCalendarId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = strings.Join(mapResearcherName[v.RsCalendarId], ",")
			item.ServeTypeId = 4
			item.ServeTypeName = "一对一路演"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			//item.RegisterPlatform = v.RegisterPlatform
			item.ServeCount = 1.5
			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.RsCalendarId
			item.Source = utils.CYGX_OBJ_RS_CALENDAR
			item.CreateTime = time.Now()
			item.ViewTime = v.StartDate + " " + v.StartTime
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			if utils.InArrayByStr(guShouResearcherName, item.Content) {
				item.ChartPermissionName = utils.GU_SHOU_NAME
				item.ChartPermissionId = utils.GU_SHOU_ID_CHART
			}
			if utils.InArrayByStr(ceLueResearcherName, item.Content) {
				item.ChartPermissionName = utils.CE_LUE_NAME
				item.ChartPermissionId = utils.CE_LUE_ID
			}
			items = append(items, item)
		}
	}
	//1v1路演 end

	//交流反馈
	{
		condition = " AND  company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND create_time > ?  "
		userFeedbackList, e := rai_serve.GetCygxUserFeedbackList(condition+"  ORDER BY  user_feedback_id ASC ", pars)
		if e != nil {
			err = errors.New("GetCygxUserFeedbackList, Err: " + e.Error())
			return
		}

		//交流反馈明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'userfeedback' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillByuserFeedback, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapRscalendarBill := make(map[string]bool)
		for _, v := range listBillByuserFeedback {
			mapRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.SourceId)] = true
		}

		mapDelRscalendarBill := make(map[string]bool)
		for _, v := range userFeedbackList {
			mapDelRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.UserFeedbackId)] = true
		}
		for _, v := range listBillByuserFeedback {
			if !mapDelRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.SourceId)] { // 如果内容存在就插入删除ID中
				delBillIds = append(delBillIds, v.BillId)
			}
		}

		for _, v := range userFeedbackList {
			if mapRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.UserFeedbackId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = v.Content
			item.ServeTypeId = 6
			item.ServeTypeName = "交流反馈"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			item.ServeCount = 1
			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.UserFeedbackId
			item.Source = utils.CYGX_OBJ_USER_FEEDBACK
			item.CreateTime = time.Now()
			item.ViewTime = v.CreateTime
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			items = append(items, item)
		}
	}
	//交流反馈 end

	//图表浏览记录
	{
		condition = " AND  b.company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND b.create_time > ?  GROUP BY  b.record_id   "
		userChartRecordList, e := models.GetCygxChartRecordListNoLimit(condition, pars)
		if e != nil {
			err = errors.New("GetCygxChartRecordListNoLimit, Err: " + e.Error())
			return
		}

		//图表浏览记录明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'newchart' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillByChart, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapRscalendarBill := make(map[string]bool)
		for _, v := range listBillByChart {
			mapRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] = true
		}

		for _, v := range userChartRecordList {
			if mapRscalendarBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = v.Title
			item.ServeTypeId = 7
			item.ServeTypeName = "图表阅读uv"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			item.ServeCount = 0.5
			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.ChartId
			item.RecordId = v.RecordId
			item.Source = utils.CYGX_OBJ_NEWCHART
			item.CreateTime = time.Now()
			item.ViewTime = v.CreateTime
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			items = append(items, item)
		}
	}
	//图表浏览记录 end

	//活动音频记录
	{
		condition = " AND  b.company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND b.create_time > ?  GROUP BY  b.id   "
		userActivityVoiceList, e := models.GetCygxActivityVoiceHistoryListNoLimit(condition, pars)
		if e != nil {
			err = errors.New("GetCygxActivityVoiceHistoryListNoLimit, Err: " + e.Error())
			return
		}

		//活动音频记录 明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'activityvoice' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillActivityVoice, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapActivityVoiceBill := make(map[string]bool)
		for _, v := range listBillActivityVoice {
			mapActivityVoiceBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] = true
		}

		for _, v := range userActivityVoiceList {
			if mapActivityVoiceBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = v.VoiceName
			item.ServeTypeId = 8
			item.ServeTypeName = "路演回放"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			item.ServeCount = 0.5
			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.ActivityVoiceId
			item.ActivityId = v.ActivityId
			item.RecordId = v.RecordId
			item.Source = utils.CYGX_OBJ_ACTIVITYVOICE
			item.CreateTime = time.Now()
			item.ViewTime = v.CreateTime
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			items = append(items, item)
		}
	}
	//活动音频记录 end

	//活动视频记录
	{
		condition = " AND  b.company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND b.create_time > ?  GROUP BY  b.id   "
		userActivityVideoList, e := models.GetCygxActivityVideoHistoryListNoLimit(condition, pars)
		if e != nil {
			err = errors.New("GetCygxChartRecordListNoLimit, Err: " + e.Error())
			return
		}

		//图表浏览记录明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'activityvideo' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillActivityVideo, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapActivityVideoBill := make(map[string]bool)
		for _, v := range listBillActivityVideo {
			mapActivityVideoBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] = true
		}

		for _, v := range userActivityVideoList {
			if mapActivityVideoBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = v.VideoName
			item.ServeTypeId = 8
			item.ServeTypeName = "路演回放"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			item.ServeCount = 0.5
			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.VideoId
			item.RecordId = v.RecordId
			item.ActivityId = v.ActivityId
			item.Source = utils.CYGX_OBJ_ACTIVITYVIDEO
			item.CreateTime = time.Now()
			item.ViewTime = v.CreateTime
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			items = append(items, item)
		}
	}
	//活动视频记录 end

	//报告精选阅读记录
	{
		condition = " AND  b.company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND b.create_time > ?  GROUP BY  b.id   "
		userReportSelectionList, e := models.GetCygxReportSelectionHistoryRecordRespLimit(condition, pars)
		if e != nil {
			err = errors.New("GetCygxChartRecordListNoLimit, Err: " + e.Error())
			return
		}

		//报告精选阅读记录 明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'reportselection' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillReportSelection, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapReportSelectionBill := make(map[string]bool)
		for _, v := range listBillReportSelection {
			mapReportSelectionBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] = true
		}

		for _, v := range userReportSelectionList {
			if mapReportSelectionBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = "重点公司"
			item.ServeTypeId = 5
			item.ServeTypeName = "阅读uv"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			item.ServeCount = 0.5
			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.ArticleId
			item.RecordId = v.RecordId
			item.Source = utils.CYGX_OBJ_REPORTSELECTION
			item.CreateTime = time.Now()
			item.ViewTime = v.CreateTime
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			items = append(items, item)
		}
	}
	//报告精选阅读记录 end

	//产品内测阅读记录
	{
		condition = " AND  b.company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND b.create_time > ?  GROUP BY  b.id   "
		userProductInteriorList, e := models.GetCygxProductInteriorHistoryListData(condition, pars)
		if e != nil {
			err = errors.New("GetCygxChartRecordListNoLimit, Err: " + e.Error())
			return
		}

		//产品内测阅读记录 明细
		var conditionBill string
		var parsBill []interface{}
		conditionBill = " AND source = 'productinterior' AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
		parsBill = append(parsBill, companyIds, startWeekDate)
		listBillProductInterior, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

		mapProductInteriorBill := make(map[string]bool)
		for _, v := range listBillProductInterior {
			mapProductInteriorBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] = true
		}

		for _, v := range userProductInteriorList {
			if mapProductInteriorBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiServeBill)
			item.Content = v.Title
			item.ServeTypeId = 5
			item.ServeTypeName = "阅读uv"
			item.UserId = v.UserId
			item.Mobile = v.Mobile
			item.Email = v.Email
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.RealName = v.RealName
			item.ServeCount = 0.5
			if mapUserMaker[v.UserId] {
				item.IsKp = 1
				item.ServeCount = item.ServeCount * 3
			}
			item.SourceId = v.ProductInteriorId
			item.RecordId = v.RecordId
			item.Source = utils.CYGX_OBJ_PRODUCTINTERIOR
			item.CreateTime = time.Now()
			item.ViewTime = v.CreateTime
			item.WeekStartDate, item.WeekEndDate = utils.GetMondayAndSundayByTimeString(item.ViewTime)
			item.MonthStartDate, item.MonthEndDate = utils.GetFirstAndLastDayOfMonth(item.ViewTime)
			items = append(items, item)
		}
	}
	//产品内测阅读记录 end

	if len(items) > 0 {
		var itemsAdd []*rai_serve.CygxRaiServeBill
		for k, v := range items {
			itemsAdd = append(itemsAdd, v)
			if len(itemsAdd)%2000 == 0 {
				fmt.Println(k)
				e = rai_serve.AddCygxRaiServeBillMulti(itemsAdd)
				if e != nil {
					err = errors.New("AddCygxRaiServeBillMulti, Err: " + e.Error())
					return
				}
				itemsAdd = make([]*rai_serve.CygxRaiServeBill, 0)
			}
		}
		e = rai_serve.AddCygxRaiServeBillMulti(itemsAdd)
		if e != nil {
			err = errors.New("AddCygxRaiServeBillMulti, Err: " + e.Error())
			return
		}
	}

	fmt.Println("delBillIds", (delBillIds))
	fmt.Println("UpdateCygxRaiServeBillByCompanyIds end")
	return
}

// 更新周度服务明细
func UpdateCygxRaiServeBillWeek() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("批量更新企业服务明细记录失败： UpdateCygxRaiServeBillByCompanyIds Err"+err.Error(), 2)
		}
	}()

	now := time.Now()
	weeks := 12

	companyList, e := rai_serve.GetCygxRaiServeCompanyAllList()
	if e != nil {
		err = errors.New("GetCygxRaiServeCompanyAllList, Err: " + e.Error())
		return
	}
	var companyIds []int

	for _, v := range companyList {
		companyIds = append(companyIds, v.CompanyId)
	}

	listCompanyUserNum, e := models.GetWxUserNumByCompanyIds(companyIds)
	if e != nil {
		err = errors.New("GetWxUserisMakerByCompanyIds, Err: " + e.Error())
		return
	}
	mapCompanyUserNum := make(map[int]int) //企业对应的用户数量
	for _, v := range listCompanyUserNum {
		mapCompanyUserNum[v.CompanyId] = v.UserNum
	}
	lencompanyId := len(companyIds)
	//研选阅读明细
	var conditionBill string
	var parsBill []interface{}
	var startWeekDate = time.Now().AddDate(0, 0, -75).Format(utils.FormatDate) + " 23:59:59"
	conditionBill = "  AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
	parsBill = append(parsBill, companyIds, startWeekDate)
	listBillByYanxuanspecial, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
	if e != nil {
		err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
		return
	}

	mapWeekServeCount := make(map[string]float64)
	for _, v := range listBillByYanxuanspecial {
		mapWeekServeCount[fmt.Sprint("CID_", v.CompanyId, "WEEK_", v.WeekStartDate)] += v.ServeCount
	}

	fmt.Println(companyIds)
	var items []*rai_serve.CygxRaiServeWeekBill
	for _, v := range companyList {
		for i := 0; i < weeks; i++ {
			item := new(rai_serve.CygxRaiServeWeekBill)
			// 计算当前周的周一
			monday := now.AddDate(0, 0, -int(now.Weekday()-time.Monday)-i*7)
			// 计算当前周的周日
			sunday := monday.AddDate(0, 0, 6)
			item.WeekStartDate = monday.Format(utils.FormatDate)
			item.WeekEndDate = sunday.Format(utils.FormatDate)
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.UserTotal = mapCompanyUserNum[v.CompanyId]
			item.WeekServeCount = mapWeekServeCount[fmt.Sprint("CID_", v.CompanyId, "WEEK_", item.WeekStartDate)]
			if mapCompanyUserNum[v.CompanyId] > 0 {
				item.CoverageRate = item.WeekServeCount / float64(mapCompanyUserNum[v.CompanyId]) * 100
			}
			item.CreateTime = time.Now()
			item.ModifyTime = time.Now()
			items = append(items, item)
		}
	}
	e = rai_serve.AddCygxRaiServeWeekBillMulti(items)
	if e != nil {
		err = errors.New("AddCygxRaiServeWeekBillMulti, Err: " + e.Error())
		return
	}
	return
}

func UpdateCygxRaiServeBillWeekTask() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("批量更新企业服务明细记录失败： UpdateCygxRaiServeBillByCompanyIds Err"+err.Error(), 2)
		}
	}()
	fmt.Println("UpdateCygxRaiServeBillWeekTask start")
	now := time.Now()
	weeks := 11

	companyList, e := rai_serve.GetCygxRaiServeCompanyAllList()
	if e != nil {
		err = errors.New("GetCygxRaiServeCompanyAllList, Err: " + e.Error())
		return
	}
	var companyIds []int

	for _, v := range companyList {
		companyIds = append(companyIds, v.CompanyId)
	}

	listCompanyUserNum, e := models.GetWxUserNumByCompanyIds(companyIds)
	if e != nil {
		err = errors.New("GetWxUserisMakerByCompanyIds, Err: " + e.Error())
		return
	}
	mapCompanyUserNum := make(map[int]int) //企业对应的用户数量
	for _, v := range listCompanyUserNum {
		mapCompanyUserNum[v.CompanyId] = v.UserNum
	}
	lencompanyId := len(companyIds)
	if lencompanyId == 0 {
		return
	}
	//明细
	var conditionBill string
	var parsBill []interface{}
	var startWeekDate = time.Now().AddDate(0, 0, -75).Format(utils.FormatDate) + " 23:59:59"
	conditionBill = "  AND   company_id IN  (" + utils.GetOrmInReplace(lencompanyId) + ")  AND view_time > ?  "
	parsBill = append(parsBill, companyIds, startWeekDate)
	listBill, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
	if e != nil {
		err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
		return
	}

	mapWeekServeCount := make(map[string]float64)
	for _, v := range listBill {
		mapWeekServeCount[fmt.Sprint("CID_", v.CompanyId, "WEEK_", v.WeekStartDate)] += v.ServeCount
	}

	var conditionWeek string
	var parsWeek []interface{}

	conditionWeek = ` AND week_start_date > ? `
	parsWeek = append(parsWeek, startWeekDate)

	listWeekBill, e := rai_serve.GetCygxRaiServeWeekBillListAll(conditionWeek, parsWeek)
	if e != nil {
		err = errors.New("GetCygxRaiServeWeekBillListAll, Err: " + e.Error())
		return
	}
	//return

	mapWeekbill := make(map[string]bool)
	mapWeekbill2 := make(map[string]int)
	mapWeekbillUserTotal := make(map[string]int)
	mapWeekbillWeekServeCount := make(map[string]float64)
	mapWeekbillWeekCoverageRate := make(map[string]float64)
	for _, v := range listWeekBill {
		mapWeekbill[fmt.Sprint("CID_", v.CompanyId, "WEEK_", v.WeekStartDate)] = true
		mapWeekbill2[fmt.Sprint("CID_", v.CompanyId, "WEEK_", v.WeekStartDate)] = v.CompanyId
		mapWeekbillUserTotal[fmt.Sprint("CID_", v.CompanyId, "WEEK_", v.WeekStartDate)] = v.UserTotal
		mapWeekbillWeekServeCount[fmt.Sprint("CID_", v.CompanyId, "WEEK_", v.WeekStartDate)] = v.WeekServeCount
		mapWeekbillWeekCoverageRate[fmt.Sprint("CID_", v.CompanyId, "WEEK_", v.WeekStartDate)] = v.CoverageRate
	}

	var items []*rai_serve.CygxRaiServeWeekBill
	var itemsUpdate []*rai_serve.CygxRaiServeWeekBill
	for _, v := range companyList {
		for i := 0; i < weeks; i++ {
			if i == 10 {
				continue
			}
			item := new(rai_serve.CygxRaiServeWeekBill)
			// 计算当前周的周一
			monday := now.AddDate(0, 0, -int(now.Weekday()-time.Monday)-i*7)
			// 计算当前周的周日
			sunday := monday.AddDate(0, 0, 6)
			item.WeekStartDate = monday.Format(utils.FormatDate)
			item.WeekEndDate = sunday.Format(utils.FormatDate)
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			//超过本周的，互动总人数不做修改
			if i > 0 && mapWeekbillUserTotal[fmt.Sprint("CID_", v.CompanyId, "WEEK_", item.WeekStartDate)] > 0 {
				item.UserTotal = mapWeekbillUserTotal[fmt.Sprint("CID_", v.CompanyId, "WEEK_", item.WeekStartDate)]
			} else {
				item.UserTotal = mapCompanyUserNum[v.CompanyId]
			}
			item.WeekServeCount = mapWeekServeCount[fmt.Sprint("CID_", v.CompanyId, "WEEK_", item.WeekStartDate)]
			if mapCompanyUserNum[v.CompanyId] > 0 {
				item.CoverageRate = item.WeekServeCount / float64(mapCompanyUserNum[v.CompanyId]) * 100
			}
			item.CreateTime = time.Now()
			item.ModifyTime = time.Now()
			if mapWeekbill[fmt.Sprint("CID_", v.CompanyId, "WEEK_", item.WeekStartDate)] {
				if mapWeekbillUserTotal[fmt.Sprint("CID_", v.CompanyId, "WEEK_", item.WeekStartDate)] == item.UserTotal && mapWeekbillWeekServeCount[fmt.Sprint("CID_", v.CompanyId, "WEEK_", item.WeekStartDate)] == item.WeekServeCount {
					continue // 如果互动量相等，且人数相等，就不修改
				}
				itemsUpdate = append(itemsUpdate, item)
			} else {
				items = append(items, item)
			}
		}
	}

	fmt.Println("itemsadd", len(items))
	if len(items) > 0 {
		e = rai_serve.AddCygxRaiServeWeekBillMulti(items)
		if e != nil {
			err = errors.New("AddCygxRaiServeWeekBillMulti, Err: " + e.Error())
			return
		}
	}
	fmt.Println("itemsUpdate111", len(itemsUpdate))
	if len(itemsUpdate) > 0 {
		e = rai_serve.UpdateCygxRaiServeWeekBillMulti(itemsUpdate)
		if e != nil {
			err = errors.New("AddCygxRaiServeWeekBillMulti, Err: " + e.Error())
			return
		}
	}

	fmt.Println("UpdateCygxRaiServeBillWeekTask end")
	return
}

//func init() {
//	UpdateWeekAvg()
//}

// 更新最近四周平均覆盖率，是否标红，权限，时间，金额
func UpdateWeekAvg() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("批量更新企业服务明细记录失败： UpdateCygxRaiServeBillByCompanyIds Err"+err.Error(), 2)
		}
	}()
	fmt.Println(" UpdateWeekAvg  start")
	now := time.Now()
	weeks := 3
	monday := now.AddDate(0, 0, -int(now.Weekday()-time.Monday)-weeks*7)

	startDate := monday.Format(utils.FormatDate)

	var condition string
	var pars []interface{}

	condition = ` AND week_start_date >= ? `
	pars = append(pars, startDate)

	listWeekBill, e := rai_serve.GetCygxRaiServeWeekBillListAll(condition, pars)
	if e != nil {
		err = errors.New("GetCygxRaiServeWeekBillListAll, Err: " + e.Error())
		return
	}

	mapWeekServeCount := make(map[int]float64) //四周平均率总合
	for _, v := range listWeekBill {
		mapWeekServeCount[v.CompanyId] += v.CoverageRate
	}

	//获取近四周含有Kp 的公司
	condition = ""
	pars = make([]interface{}, 0)
	condition += ` AND week_start_date >= ? AND is_kp = 1  GROUP BY  company_id  `
	pars = append(pars, startDate)
	listIsKpWeekBill, e := rai_serve.GetCygxRaiServeBillListAll(condition, pars)
	if e != nil {
		err = errors.New("GetCygxRaiServeWeekBillListAll, Err: " + e.Error())
		return
	}

	mapWeekIsKp := make(map[int]bool) //最近四周是否包含KP
	for _, v := range listIsKpWeekBill {
		mapWeekIsKp[v.CompanyId] = true
	}

	companyList, e := rai_serve.GetCygxRaiServeCompanyAllList()
	if e != nil {
		err = errors.New("GetCygxRaiServeCompanyAllList, Err: " + e.Error())
		return
	}
	var formalCompanyIds []int   // 当前正式客户ID
	var formalNoCompanyIds []int // 当前非正式客户ID

	//永续客户当做正式客户处理
	for _, v := range companyList {
		if v.Status == "正式" || v.Status == "永续" {
			formalCompanyIds = append(formalCompanyIds, v.CompanyId)
		} else {
			formalNoCompanyIds = append(formalNoCompanyIds, v.CompanyId)
		}
	}

	var itemsUpdate []*rai_serve.CygxRaiServeCompany
	if len(formalCompanyIds) > 0 { //正式客户信息
		condition = ""
		pars = make([]interface{}, 0)
		condition = `    AND product_id = 2 AND company_id IN  (` + utils.GetOrmInReplace(len(formalCompanyIds)) + `) AND status = 1  AND  end_date > ? `
		pars = append(pars, formalCompanyIds, time.Now())
		listCompanyContract, e := company.GetCompanyContractList(condition, pars)
		if e != nil {
			err = errors.New("GetCompanyContractList, Err: " + e.Error())
			return
		}
		companyMoney := make(map[int]float64)
		for _, v := range listCompanyContract {
			companyMoney[v.CompanyId] += v.Money
		}

		permissionNameMapByCompanyId, e := GetCompanyReportPermissionNameMapByCompanyId(formalCompanyIds)
		if e != nil {
			err = errors.New("GetCompanyReportPermissionNameMapByCompanyId, Err: " + e.Error())
			return
		}
		for _, v := range formalCompanyIds {
			item := new(rai_serve.CygxRaiServeCompany)
			item.CompanyId = v
			item.Money = companyMoney[v]
			item.PermissionName = permissionNameMapByCompanyId[v]
			item.ServeCoverageRate = utils.SubFloatToString(mapWeekServeCount[v]/4, 2)
			item.IsUserMaker = -1
			if mapWeekIsKp[v] {
				item.IsUserMaker = 1
			}
			itemsUpdate = append(itemsUpdate, item)
		}
	}

	//正式客户数据修改
	e = rai_serve.UpdateCygxRaiServeCompanyMulti(itemsUpdate)
	if e != nil {
		err = errors.New("UpdateCygxRaiServeCompanyMulti, Err: " + e.Error())
		return
	}

	var itemsUpdateFormalNo []*rai_serve.CygxRaiServeCompany         //非正式客户数据修改
	var itemsUpdateFormalNoContract []*rai_serve.CygxRaiServeCompany //非正式客户没有合同的客户修改

	mapContractCompanyIds := make(map[int]bool) //签过合同的试用客户ID
	if len(formalNoCompanyIds) > 0 {            //非正式客户信息
		condition = ""
		pars = make([]interface{}, 0)
		condition = `    AND product_id = 2 AND company_id IN  (` + utils.GetOrmInReplace(len(formalNoCompanyIds)) + `) AND status = 1  AND  end_date < ?  GROUP BY	company_id  ORDER BY	company_contract_id DESC `
		pars = append(pars, formalNoCompanyIds, time.Now())
		listCompanyContractLastId, e := company.GetCompanyContractLastList(condition, pars) //获取关联的最后一笔合同信息
		if e != nil {
			err = errors.New("GetCompanyContractLastList, Err: " + e.Error())
			return
		}
		var companyContractIds []int
		for _, v := range listCompanyContractLastId {
			companyContractIds = append(companyContractIds, v.CompanyContractId)
		}

		condition = ""
		pars = make([]interface{}, 0)
		condition = `    AND product_id = 2 AND company_id IN  (` + utils.GetOrmInReplace(len(formalNoCompanyIds)) + `) AND status = 1  AND company_contract_id IN  (` + utils.GetOrmInReplace(len(companyContractIds)) + `)   AND    end_date < ?  GROUP BY	company_id  ORDER BY	company_contract_id DESC `
		pars = append(pars, formalNoCompanyIds, companyContractIds, time.Now())
		listCompanyContractLast, e := company.GetCompanyContractList(condition, pars)
		if e != nil {
			err = errors.New("GetCompanyContractList, Err: " + e.Error())
			return
		}

		permissionNameMapByContractId, e := GetCompanyContractPermissionNameMapById(companyContractIds)
		if e != nil {
			err = errors.New("GetCompanyReportPermissionNameMapByCompanyId, Err: " + e.Error())
			return
		}
		for _, v := range listCompanyContractLast {
			item := new(rai_serve.CygxRaiServeCompany)
			item.CompanyId = v.CompanyId
			item.Money = v.Money
			item.StartDate = v.StartDate
			item.EndDate = v.EndDate
			item.ServeCoverageRate = utils.SubFloatToString(mapWeekServeCount[v.CompanyId]/4, 2)
			item.IsUserMaker = -1
			if mapWeekIsKp[v.CompanyId] {
				item.IsUserMaker = 1
			}
			item.PermissionName = permissionNameMapByContractId[v.CompanyContractId]
			itemsUpdateFormalNo = append(itemsUpdateFormalNo, item)
			mapContractCompanyIds[v.CompanyId] = true
		}

		for _, v := range formalNoCompanyIds {
			if mapContractCompanyIds[v] {
				continue
			}
			//fmt.Println(v)
			item := new(rai_serve.CygxRaiServeCompany)
			item.CompanyId = v

			item.ServeCoverageRate = utils.SubFloatToString(mapWeekServeCount[v]/4, 2)
			item.IsUserMaker = -1
			if mapWeekIsKp[v] {
				item.IsUserMaker = 1
			}
			itemsUpdateFormalNoContract = append(itemsUpdateFormalNoContract, item)
		}
	}
	e = rai_serve.UpdateCygxRaiServeCompanyFormalNoMulti(itemsUpdateFormalNo)
	if e != nil {
		err = errors.New("UpdateCygxRaiServeCompanyFormalNoMulti, Err: " + e.Error())
		return
	}

	e = rai_serve.UpdateCygxRaiServeCompanyFormalNoContractMulti(itemsUpdateFormalNoContract)
	if e != nil {
		err = errors.New("UpdateCygxRaiServeCompanyFormalNoMulti, Err: " + e.Error())
		return
	}
	fmt.Println(" UpdateWeekAvg  end")
	return
}
