package plugin

import (
	"go-account-register/config"
	"go-account-register/models"
	"go-account-register/services"
	paramsTypes "go-account-register/types"
	"log"
	"math"
	"runtime/debug"
	"sync"
	"time"
)

var TwitterService services.TwitterService

type TaskViewPostPlugin struct{}

func (*TaskViewPostPlugin) Run(task *paramsTypes.Task) {

	// 查询当前所有账号
	userService := services.InitTwitterAccountService()
	// 判断是否是补偿任务
	var userList []models.TwitterAccount
	userList = userService.GetAvailableAccount(&models.TwitterAccount{
		Type: "view",
	})

	if task.Data.Compensate == 1 {
		// 补偿任务
		userList = userService.GetAccountListByStatus(&models.TwitterAccount{
			Status: "查看成功",
			Type:   "view",
		})
	} else {
		// 清空当前运行的账号状态
		userService.ClearAccountStatus(&models.TwitterAccount{
			Type: "view",
		})
	}
	log.Println("可用账号数量：", len(userList))
	// 获取并发数
	appConfig, _ := config.LoadConfig()
	num := math.Ceil(float64(len(userList)) / float64(appConfig.Limit.BrowserRunMax))
	sem := make(chan struct{}, appConfig.Limit.BrowserRunMax) // 全局并发上限
	var globalWait sync.WaitGroup
	for i := 0; i < int(num); i++ {
		select {
		case <-task.Ctx.Done():
			log.Println("中断任务")
			return
		default:
		}
		log.Println("批次：", i+1)
		for j := 0; j < appConfig.Limit.BrowserRunMax; j++ {
			log.Println(i*appConfig.Limit.BrowserRunMax + j)
			taskIndex := i*appConfig.Limit.BrowserRunMax + j
			if taskIndex >= len(userList) {
				break
			}
			time.Sleep(10 * time.Second)
			globalWait.Add(1)
			sem <- struct{}{} // 阻塞直到有空位
			go func() {
				defer func() {
					<-sem // 释放信号量
					globalWait.Done()
				}()
				changeAccountWork(task, userList[taskIndex].ID)
			}()
		}
	}
	globalWait.Wait()

	task.Message <- "Success"
}

func changeAccountWork(task *paramsTypes.Task, id int64) {
	UserService := services.InitTwitterAccountService()
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Goroutine panic: %v\nStack: %s", r, debug.Stack())
			UserService.ChangeAccountLoginStatus(int(id), "账号下线")
			TwitterService.Logout(int(id))
		}
	}()

	// 开始登录

	res := TwitterService.Login(int(id))
	UserService.ChangeAccountLoginStatus(int(id), res.Msg)
	if res.Code == 200 {
		// 开始拟人
		res = TwitterService.LoopViewPost(int(id))
		UserService.ChangeAccountStatus(int(id), res.Msg)
		time.Sleep(3 * time.Second)

		TwitterService.Logout(int(id))
		UserService.ChangeAccountLoginStatus(int(id), "账号下线")
	}

	log.Println(task.ID)
}
