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"
)

//func init() {
//	UpdateCygxRaiCompanyUserBill()
//}

// 权益正式，试用客户近四周互动记录
func UpdateCygxRaiCompanyUserBillDate(cont context.Context) (err error) {
	//func UpdateCygxRaiCompanyUserBillDate() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("定时任务处理权权益正式，试用客户近四周互动记录 失败 UpdateCygxRaiCompanyUserBillDate  ，err：", err.Error()), 2)
		}
	}()

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

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

	return
}

// 批量更新权益正式，试用客户近四周互动记录
func UpdateCygxRaiCompanyUserBill() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("批量更新权益正式，试用客户近四周互动记录  失败： UpdateCygxRaiCompanyUserBill Err"+err.Error(), 2)
		}
	}()
	var delBillIds []int
	var startWeekDate = time.Now().AddDate(0, 0, -28).Format(utils.FormatDate) + " 23:59:59"
	fmt.Println("UpdateCygxRaiCompanyUserBill start")
	companyList, e := company.GetRaiCompanyProductCompanyids()
	if e != nil {
		err = errors.New("GetCygxRaiServeCompanyAllList, Err: " + e.Error())
		return
	}
	var companyIds []int
	var items []*rai_serve.CygxRaiCompanyUserBill
	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 user_id, yanxuan_special_id  ORDER BY 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)
		}
		yanxuanspecialIds = append(yanxuanspecialIds, 0)
		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.GetCygxRaiCompanyUserBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiCompanyUserBillListAll, 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.CygxRaiCompanyUserBill)
			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.GetCygxRaiCompanyUserBillListAll(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.CygxRaiCompanyUserBill)
			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.GetCygxRaiCompanyUserBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiCompanyUserBillListAll, 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 mapActivityeBill[fmt.Sprint("UID_", v.Mobile, "SID_", v.ActivityId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiCompanyUserBill)
			item.Content = v.ActivityName
			if v.ActivityType == 1 {
				item.ServeTypeId = 1
				item.ServeTypeName = "线上活动"
			} else {
				item.ServeTypeId = 2
				item.ServeTypeName = "线下活动"
			}
			if v.UserId == 0 && v.Mobile != "" {
				v.UserId = mapUserMobileUserId[v.Mobile] // 空降的部分联系人 userid 为0这里做一下修复
			}

			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.GetCygxRaiCompanyUserBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiCompanyUserBillListAll, 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.CygxRaiCompanyUserBill)
			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.GetCygxRaiCompanyUserBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiCompanyUserBillListAll, 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.CygxRaiCompanyUserBill)
			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.GetCygxRaiCompanyUserBillListAll(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.CygxRaiCompanyUserBill)
			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.GetCygxRaiCompanyUserBillListAll(conditionBill, parsBill)
		if e != nil {
			err = errors.New("GetCygxRaiServeBillListAll, Err: " + e.Error())
			return
		}

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

		for _, v := range userChartRecordList {
			if mapChartBill[fmt.Sprint("UID_", v.UserId, "SID_", v.RecordId)] { // 如果内容存在就不插入
				continue
			}
			item := new(rai_serve.CygxRaiCompanyUserBill)
			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.GetCygxRaiCompanyUserBillListAll(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.CygxRaiCompanyUserBill)
			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.RecordId = v.RecordId
			item.ActivityId = v.ActivityId
			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.GetCygxRaiCompanyUserBillListAll(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.CygxRaiCompanyUserBill)
			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.GetCygxRaiCompanyUserBillListAll(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.CygxRaiCompanyUserBill)
			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.GetCygxRaiCompanyUserBillListAll(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.CygxRaiCompanyUserBill)
			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

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

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

// 更新权益客户最近四周是否有决策人互动记录
func UpdateCompanyProductIsUserMaker() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("更新权益客户最近四周是否有决策人互动记录 失败： UpdateCompanyProductIsUserMaker Err"+err.Error(), 2)
		}
	}()
	fmt.Println(" UpdateCompanyProductIsUserMaker  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 >= ?  AND is_kp = 1  GROUP BY company_id `
	pars = append(pars, startDate)

	//获取近四周之内含有KP的公司
	listKpCompanyId, e := rai_serve.GetCygxRaiCompanyUserBillListAll(condition, pars)
	if e != nil {
		err = errors.New("GetCygxRaiCompanyUserBillListAll, Err: " + e.Error())
		return
	}

	var companyIds []int
	for _, v := range listKpCompanyId {
		companyIds = append(companyIds, v.CompanyId)
	}
	companyIds = append(companyIds, 0)
	//if len(companyIds) == 0 {
	//	return
	//}
	//fmt.Println(len(companyIds))

	e = company.UpdateRaiCompanyProductIsUserMakerByCompanyids(companyIds)
	if e != nil {
		err = errors.New("UpdateRaiCompanyProductIsUserMakerByCompanyids, Err: " + e.Error())
		return
	}
	fmt.Println(" UpdateCompanyProductIsUserMaker  end")
	return
}

//func init() {
//	initCRm_16_9_v2()
//}

func initCRm_16_9() {

	var conditionBill string
	var parsBill []interface{}
	conditionBill = " AND  month_start_date = '' LIMIT 10000  "
	listBillByYanxuanspecial, e := rai_serve.GetCygxRaiCompanyUserBillListAll(conditionBill, parsBill)
	if e != nil {
		fmt.Println(e)
		return
	}

	for _, v := range listBillByYanxuanspecial {
		v.MonthStartDate, v.MonthEndDate = utils.GetFirstAndLastDayOfMonth(v.ViewTime)
	}

	e = rai_serve.UpdateCygxRaiCompanyUserBillMulti(listBillByYanxuanspecial)
	if e != nil {
		fmt.Println(e)
		return
	}
	fmt.Println("end")
}

func initCRm_16_9_v2() {

	var conditionBill string
	var parsBill []interface{}
	conditionBill = " AND  month_start_date = '' LIMIT 10000  "
	listBillByYanxuanspecial, e := rai_serve.GetCygxRaiServeBillListAll(conditionBill, parsBill)
	if e != nil {
		fmt.Println(e)
		return
	}

	for _, v := range listBillByYanxuanspecial {
		v.MonthStartDate, v.MonthEndDate = utils.GetFirstAndLastDayOfMonth(v.ViewTime)
	}

	e = rai_serve.UpdateCygxRaiServeBillMulti(listBillByYanxuanspecial)
	if e != nil {
		fmt.Println(e)
		return
	}
	fmt.Println("end")
}
