package yb

import (
	"errors"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/advisory"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/utils"
	"strings"
	"sync"
	"time"
)

// MarkApplyRecord 标记申请记录
func MarkApplyRecord(applyRecordId, adminId, userId int) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	if applyRecordId > 0 {
		applyRecord, tErr := yb.GetApplyRecordById(applyRecordId)
		if tErr != nil {
			if tErr.Error() == utils.ErrNoRow() {
				err = errors.New(fmt.Sprint("申请记录不存在：", err))
			} else {
				err = tErr
			}
			return
		}
		if applyRecord.OpStatus != 0 {
			err = errors.New(fmt.Sprint("申请记录处理状态有误：", err))
			return
		}
		if userId > 0 && userId != applyRecord.UserId {
			err = errors.New(fmt.Sprint("申请记录ID与用户ID不匹配：", err))
			return
		}
		userId = applyRecord.UserId
		// 1.标记申请记录
		applyRecord.OpStatus = 1
		applyRecord.DealTime = time.Now()
		applyRecord.SysUserId = adminId
		updateCols := make([]string, 0)
		updateCols = append(updateCols, "OpStatus", "DealTime", "SysUserId")
		err = applyRecord.Update(updateCols)
		if err != nil {
			err = errors.New(fmt.Sprint("申请记录标记失败", err))
			return
		}
	}

	// 2.标记wx用户表
	wxUser, err := models.GetWxUserByUserId(userId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			err = nil // 用户可能在潜在用户列表直接被删除，那么直接不标记
			return
		}
		return
	}
	// 未处理过则进行标记
	if wxUser.IsDeal == 0 {
		wxUser.IsDeal = 1
		wxUser.LastUpdatedTime = time.Now()
		userUpdateCols := make([]string, 0)
		userUpdateCols = append(userUpdateCols, "IsDeal", "LastUpdatedTime")
		err = wxUser.Update(userUpdateCols)
		if err != nil {
			err = errors.New(fmt.Sprint("对应用户信息标记失败", err))
			return
		}
	}

	return
}

func GetUserViewTotalByMobiles(mobilesSlice []string) (mobileTotalMap map[string]int, lastTimeMap map[string]time.Time) {
	//根据手机号查询
	//手机号
	mobileTotalMap = make(map[string]int)
	lastTimeMap = make(map[string]time.Time)
	if len(mobilesSlice) > 0 {
		mobileStr := strings.Join(mobilesSlice, "','")
		mobileStr = "'" + mobileStr + "'"
		w := sync.WaitGroup{}
		//用户浏览数据
		var userViewMobileTotalList []*models.UserViewMobileTotalSlice
		w.Add(1)
		go func() {
			defer w.Done()
			userViewMobileTotalList, _ = models.GetCountUserViewHistoryByMobiles(mobileStr)
		}()

		//每日点评手机号数据
		var userReportViewMobileTotalList []*models.ReportViewMobileRecord
		w.Add(1)
		go func() {
			defer w.Done()
			userReportViewMobileTotalList, _ = models.GetReportViewMaxTimeByMobiles(mobileStr)
		}()

		//研报手机号数据
		var chartArticleViewMobileTotalList []*advisory.UserViewMobileTotalSlice
		w.Add(1)
		go func() {
			defer w.Done()
			chartArticleViewMobileTotalList, _ = advisory.GetCountUserViewHistoryByMobiles(mobileStr)
		}()

		var articleViewMobileTotalList []*models.UserViewMobileTotalSlice
		w.Add(1)
		go func() {
			defer w.Done()
			articleViewMobileTotalList, _ = models.GetCountCygxArticleHistoryRecordByMobiles(mobileStr)
		}()

		w.Wait()
		for _, userViewMobile := range userViewMobileTotalList {
			lastTimeMap[userViewMobile.Mobile] = userViewMobile.CreatedTime
			mobileTotalMap[userViewMobile.Mobile] = userViewMobile.Total
		}
		//每日点评手机号数据
		for _, item := range userReportViewMobileTotalList {
			if t, ok := lastTimeMap[item.Mobile]; ok {
				if t.Before(item.LastViewTime) {
					lastTimeMap[item.Mobile] = item.LastViewTime
				}
			} else {
				lastTimeMap[item.Mobile] = item.LastViewTime
			}

			mobileTotalMap[item.Mobile] += item.ViewTotal
		}

		for _, item := range chartArticleViewMobileTotalList {
			if t, ok := lastTimeMap[item.Mobile]; ok {
				if t.Before(item.CreatedTime) {
					lastTimeMap[item.Mobile] = item.CreatedTime
				}
			} else {
				lastTimeMap[item.Mobile] = item.CreatedTime
			}
			mobileTotalMap[item.Mobile] += item.Total
		}

		for _, item := range articleViewMobileTotalList {
			if t, ok := lastTimeMap[item.Mobile]; ok {
				if t.Before(item.CreatedTime) {
					lastTimeMap[item.Mobile] = item.CreatedTime
				}
			} else {
				lastTimeMap[item.Mobile] = item.CreatedTime
			}
			mobileTotalMap[item.Mobile] += item.Total
		}
	}
	return
}

func GetUserViewTotalByEmails(emailsSlice []string) (emailTotalMap map[string]int, lastTimeMap map[string]time.Time) {
	//根据邮箱查询
	lastTimeMap = make(map[string]time.Time)
	emailTotalMap = make(map[string]int)
	if len(emailsSlice) > 0 {
		emailStr := strings.Join(emailsSlice, "','")
		emailStr = "'" + emailStr + "'"
		w := sync.WaitGroup{}

		//用户浏览数据
		var userViewEmailTotalList []*models.UserViewEmailTotalSlice
		w.Add(1)
		go func() {
			defer w.Done()
			userViewEmailTotalList, _ = models.GetCountUserViewHistoryByEmails(emailStr)
		}()
		//每日点评手机号数据
		var userReportViewEmailTotalList []*models.ReportViewEmailRecord
		w.Add(1)
		go func() {
			defer w.Done()
			userReportViewEmailTotalList, _ = models.GetReportViewMaxTimeByEmails(emailStr)
		}()

		// advisory_user_chart_article_record
		var chartArticleTotalList []*advisory.UserViewEmailTotalSlice
		w.Add(1)
		go func() {
			defer w.Done()
			chartArticleTotalList, _ = advisory.GetCountUserViewHistoryByEmails(emailStr)
		}()

		// cygx_article_history_record_newpv
		var articleViewTotalList []*models.UserViewEmailTotalSlice
		w.Add(1)
		go func() {
			defer w.Done()
			articleViewTotalList, _ = models.GetCountCygxArticleHistoryRecordByEmails(emailStr)
		}()
		w.Wait()
		for _, userViewEmail := range userViewEmailTotalList {
			lastTimeMap[userViewEmail.Email] = userViewEmail.CreatedTime
			emailTotalMap[userViewEmail.Email] = userViewEmail.Total
		}

		for _, item := range userReportViewEmailTotalList {
			if t, ok := lastTimeMap[item.Email]; ok {
				if t.Before(item.LastViewTime) {
					lastTimeMap[item.Email] = item.LastViewTime
				}
			} else {
				lastTimeMap[item.Email] = item.LastViewTime
			}
			emailTotalMap[item.Email] += item.ViewTotal
		}

		for _, item := range chartArticleTotalList {
			if t, ok := lastTimeMap[item.Email]; ok {
				if t.Before(item.CreatedTime) {
					lastTimeMap[item.Email] = item.CreatedTime
				}
			} else {
				lastTimeMap[item.Email] = item.CreatedTime
			}
			emailTotalMap[item.Email] += item.Total
		}
		for _, item := range articleViewTotalList {
			if t, ok := lastTimeMap[item.Email]; ok {
				if t.Before(item.CreatedTime) {
					lastTimeMap[item.Email] = item.CreatedTime
				}
			} else {
				lastTimeMap[item.Email] = item.CreatedTime
			}
			emailTotalMap[item.Email] += item.Total
		}
	}

	return
}

// DeleteApplyUser 删除用户的申请记录
func DeleteApplyUser(userId int64) (err error) {
	err = yb.DelApplyRecordByUserId(userId)
	if err != nil {
		err = errors.New(fmt.Sprint("删除申请记录失败", err))
		return
	}
	return
}

// MarkGroupApplyRecord 标记申请记录和分组
func MarkGroupApplyRecord(applyRecordId, adminId, userId int, groupName string) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	if applyRecordId > 0 {
		applyRecord, tErr := yb.GetApplyRecordById(applyRecordId)
		if tErr != nil {
			if tErr.Error() == utils.ErrNoRow() {
				err = errors.New(fmt.Sprint("申请记录不存在：", err))
			} else {
				err = tErr
			}
			return
		}
		//if applyRecord.OpStatus != 0 {
		//	err = errors.New(fmt.Sprint("申请记录处理状态有误：", err))
		//	return
		//}
		if userId > 0 && userId != applyRecord.UserId {
			err = errors.New(fmt.Sprint("申请记录ID与用户ID不匹配：", err))
			return
		}
		userId = applyRecord.UserId
		// 1.标记申请记录
		applyRecord.OpStatus = 1
		applyRecord.DealTime = time.Now()
		applyRecord.SysUserId = adminId
		applyRecord.MarkGroup = groupName
		updateCols := make([]string, 0)
		updateCols = append(updateCols, "OpStatus", "DealTime", "SysUserId","MarkGroup")
		err = applyRecord.Update(updateCols)
		if err != nil {
			err = errors.New(fmt.Sprint("申请记录标记失败", err))
			return
		}
	}

	// 2.标记wx用户表
	wxUser, err := models.GetWxUserByUserId(userId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			err = nil // 用户可能在潜在用户列表直接被删除，那么直接不标记
			return
		}
		return
	}
	// 未处理过则进行标记
	if wxUser.IsDeal == 0 || wxUser.MarkGroup == "" {
		wxUser.IsDeal = 1
		wxUser.MarkGroup = groupName
		wxUser.LastUpdatedTime = time.Now()
		userUpdateCols := make([]string, 0)
		userUpdateCols = append(userUpdateCols, "IsDeal", "MarkGroup", "LastUpdatedTime")
		err = wxUser.Update(userUpdateCols)
		if err != nil {
			err = errors.New(fmt.Sprint("对应用户信息标记失败", err))
			return
		}
	}

	return
}