package jobs

import (
	"context"
	"errors"
	"gadmin/config"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"github.com/sirupsen/logrus"
	"gorm.io/gen"
	"gorm.io/gorm"
	"os"
)

// 处理客服聊天记录中accId和name为空的数据
var SyncChatLogDiscover = new(JobSyncChatLogDiscover)

type JobSyncChatLogDiscover struct{}

func (j *JobSyncChatLogDiscover) Run() {
	if os.Getenv("ADMIN_PLATFORM") != "wechat" {
		logrus.Warn("客服聊天记录目前只有微信平台")
		return
	}
	logrus.Info("处理客服聊天记录数据...")
	var (
		ctx          = context.Background()
		chatLogQuery = query.Use(config.DB).CustomerServiceChatLog
		chatLogModel = chatLogQuery.WithContext(ctx)
	)
	//获取聊天记录
	count, err := chatLogModel.Distinct(chatLogQuery.OpenID).Where(chatLogQuery.PlayerName.Eq("")).Count()
	if err != nil {
		logrus.Errorf("JobSyncChatLogDiscover 统计mysql客服记录失败:%s", err.Error())
	}
	if count == 0 {
		logrus.Info("客服聊天记录数据无需处理...")
		return
	}
	//处理数据
	results := make([]*model.CustomerServiceChatLog, 0)
	err = chatLogModel.Where(chatLogQuery.AccID.Eq(0)).Or(chatLogQuery.PlayerName.Eq("")).Group(chatLogQuery.OpenID).FindInBatches(&results, 500, func(tx gen.Dao, batch int) error {
		//查询account
		for _, item := range results {
			var account model.UserAccount
			err = config.LDB.WithContext(ctx).Scopes(model.UserAccountTableByKey(&model.UserAccount{}, item.OpenID)).Where("openid = ?", item.OpenID).First(&account).Error
			if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
				return err
			}
			if account.ID == 0 {
				logrus.Infof("用户不存在,openId:%s", item.OpenID)
				continue
			}
			//更新数据
			updates, err := chatLogModel.Where(chatLogQuery.OpenID.Eq(item.OpenID)).Updates(model.CustomerServiceChatLog{AccID: account.AccID, PlayerName: account.Nickname})
			if err != nil {
				return err
			}
			if updates.Error != nil {
				return updates.Error
			}
		}
		return nil
	})
	if err != nil {
		logrus.Errorf("JobSyncChatLogDiscover 处理mysql客服记录失败:%s", err.Error())
		return
	}
	logrus.Info("处理客服聊天记录数据完成...")
}
