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

type TaskAccountUnlockPlugin struct {
}

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

	// 查询当前所有账号
	accountService := services.InitTwitterAccountService()
	// 判断是否是补偿任务
	var accountList []models.TwitterAccount
	accountList = accountService.GetAvailableAccount(&models.TwitterAccount{
		Status: "账号锁定",
	})
	if task.Data.Compensate == 1 {
		// 补偿任务
		accountList = accountService.GetAccountListByStatus(&models.TwitterAccount{
			Status: "解锁失败",
		})
	} else {
		// 清空当前运行的账号状态
		accountService.ClearAccountStatus(&models.TwitterAccount{
			Status: "解锁成功",
		})
	}

	// 获取并发数
	appConfig, _ := config.LoadConfig()
	num := math.Ceil(float64(len(accountList)) / 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(accountList) {
				break
			}
			time.Sleep(10 * time.Second)
			globalWait.Add(1)
			sem <- struct{}{} // 阻塞直到有空位
			go func() {
				defer func() {
					<-sem // 释放信号量
					globalWait.Done()
				}()
				unlockWork(task, accountList[taskIndex].ID)
			}()
		}
	}
	globalWait.Wait()

	task.Message <- "Success"
}

func unlockWork(task *paramsTypes.Task, id int64) {
	AccountService := services.InitTwitterAccountService()
	var TwitterService services.BitBrowserService
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Goroutine panic: %v\nStack: %s", r, debug.Stack())
			AccountService.ChangeAccountLoginStatus(int(id), "账号下线")
			// TwitterService.Logout(int(id))
		}
	}()
	res := TwitterService.AccountUnlock(id)
	// 开始登录
	// res := TwitterService.Login(int(id))
	AccountService.ChangeAccountLoginStatus(int(id), res.Msg)
	// if res.Code == 200 {
	// 	// 开始拟人
	// 	// res = TwitterService.ChangeAccountInfo(int(id))
	// 	AccountService.ChangeAccountStatus(int(id), res.Msg)
	// 	time.Sleep(3 * time.Second)

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

	log.Println(task.ID)
}
