package yb

import (
	"fmt"
	"hongze/hongze_open_api/models/tables/company"
	"hongze/hongze_open_api/models/tables/company_product"
	"hongze/hongze_open_api/models/tables/qs_event"
	"hongze/hongze_open_api/models/tables/qs_event_user"
	"hongze/hongze_open_api/models/tables/user_view_statistics"
	"hongze/hongze_open_api/models/tables/wx_user"
	"hongze/hongze_open_api/services/alarm_msg"
	"hongze/hongze_open_api/services/quanshi"
	"hongze/hongze_open_api/utils"
	"strings"
	"time"
)

// SyncUser 用户同步
func SyncUser(qsEventId int) (err error) {
	errMsgList := make([]string, 0)
	defer func() {
		if err != nil {
			errMsgList = append(errMsgList, err.Error())
		}
		if len(errMsgList) > 0 {
			//for _, v := range errMsgList {
			//	fmt.Println(v)
			//}
			go alarm_msg.SendAlarmMsg("同步全时会议参会人员数据失败:"+strings.Join(errMsgList, "/n"), 3)
		}
	}()
	qsEventInfo, err := qs_event.GetQsEventByQsEventId(qsEventId)
	if err != nil {
		return
	}

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

	companyProductMap := make(map[string]*company_product.CompanyProduct)
	companyMap := make(map[string]*company.Company)
	people := 0 //参与人数

	productIdList := []int{1, 2}               //ficc和权益
	companyIdProductIdMap := make(map[int]int) //客户与产品的id  map

	if qsData.Summary != nil {
		for _, v := range qsData.Summary {
			if v.Mobile == "" { //如果手机号为空，那么就不处理了，进入下一个循环
				continue
			}
			tmpQsEventUser, tmpErr := qs_event_user.GetQsEventUserByQsId(qsEventInfo.QsId, v.Mobile)
			if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
				errMsgList = append(errMsgList, fmt.Sprintf("路演id：%d，用户手机号：%s，会议用户入库失败,err：%s", qsEventInfo.QsId, v.Mobile, err.Error()))
				continue
			}
			// 如果已经有数据了，那么不需要再处理了
			if tmpQsEventUser != nil {
				continue
			}
			people++
			mobile := v.Mobile
			trimMobile := mobile
			countryCode := "86"
			var companyProductInfo *company_product.CompanyProduct
			var companyInfo *company.Company
			var wxUserInfo *wx_user.WxUser
			if mobile != "" {
				trimMobileSlice := strings.Split(v.Mobile, "-")
				lenTrimMobileSlice := len(trimMobileSlice)
				if lenTrimMobileSlice > 1 {
					trimMobile = trimMobileSlice[1]
					countryCode = strings.Replace(trimMobileSlice[0], "+", "", -1)
				}
				wxUserInfo, _ = wx_user.GetWxUserByMobileCountryCode(trimMobile, countryCode)
				if wxUserInfo != nil && wxUserInfo.CompanyId != 1 {
					//获取客户产品信息
					productId, ok := companyIdProductIdMap[wxUserInfo.CompanyId]
					if ok { //已经查询过
						if productId > 0 {
							// 获取客户产品信息
							key := fmt.Sprint(wxUserInfo.CompanyId, "_", productId)

							if tmpCompanyProductInfo, ok := companyProductMap[key]; ok {
								companyProductInfo = tmpCompanyProductInfo
							}

						}
					} else {
						for _, productId := range productIdList {
							key := fmt.Sprint(wxUserInfo.CompanyId, "_", productId)
							companyProductInfo, _ = company_product.GetCompanyProductByCompanyIdAndProductId(wxUserInfo.CompanyId, productId)
							if companyProductInfo != nil {
								companyProductMap[key] = companyProductInfo
								companyIdProductIdMap[wxUserInfo.CompanyId] = productId
								//退出产品查询
								break
							}
						}
						if companyProductInfo == nil {
							companyIdProductIdMap[wxUserInfo.CompanyId] = 0
						}
					}

					// 获取客户信息
					key := fmt.Sprint(wxUserInfo.CompanyId)
					if tmpCompanyInfo, ok := companyMap[key]; ok {
						companyInfo = tmpCompanyInfo
					} else {
						companyInfo, _ = company.GetCompanyById(wxUserInfo.CompanyId)
						if companyInfo != nil {
							companyMap[key] = companyInfo
						}
					}
				}
			}

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

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

				qsEventUserInfo.UserId = int(wxUserInfo.UserId)
				qsEventUserInfo.Name = wxUserInfo.RealName
				qsEventUserInfo.CompanyId = companyProductInfo.CompanyId
				qsEventUserInfo.ProductId = companyProductInfo.ProductId
				qsEventUserInfo.CompanyName = companyInfo.CompanyName
				qsEventUserInfo.Status = companyProductInfo.Status
				qsEventUserInfo.SellerId = companyProductInfo.SellerId
				qsEventUserInfo.SellerName = companyProductInfo.SellerName
				qsEventUserInfo.CompanyViewTotal = companyProductInfo.ViewTotal
				qsEventUserInfo.CompanyRoadTotal = companyProductInfo.RoadShowTotal
			}
			_ = qs_event_user.AddQsEventUser(qsEventUserInfo)
		}
	}

	qsEventInfo.IsSync = 1
	qsEventInfo.QsStatus = 2
	qsEventInfo.People = qsEventInfo.People + people
	err = qsEventInfo.Update([]string{"IsSync", "QsStatus", "People"})
	return
}

// SyncVideo 录音同步
func SyncVideo(qsEventId int, videoUrl string) (err error) {
	qsEventInfo, err := qs_event.GetQsEventByQsEventId(qsEventId)
	if err != nil {
		return
	}
	qsEventInfo.VideoUrl = videoUrl
	err = qsEventInfo.Update([]string{"VideoUrl"})
	return
}
