<?php

declare(strict_types=1);

namespace app\common\library\scrm\spider;

use app\common\library\scrm\AbstractScrmSpider;
use app\common\library\scrm\AntiBotConfigBuilder;
use app\common\library\scrm\UnifiedScrmData;
use app\common\service\SplitPageUrlResolver;

/**
 * 火箭云控蜘蛛（Real Browser + CF 过盾 + 密码弹窗 + API 拦截）
 *
 * 短链 s.url99.me → 长链 *.url66.me/gds?link=（长链域名动态，不写死）
 */
class HuojianSpider extends AbstractScrmSpider
{
    private const API_LIST = '/prod-api1/biz/counter/link/share/';

    private string $pageUrl;

    private string $account;

    private string $password;

    private UnifiedScrmData $unifiedData;

    /** HTTP 预解析落地 URL（短链 CF 时可能失败，仅作 hint） */
    private string $landingUrlHint = '';

    public function __construct(
        string $pageUrl,
        string $account = '',
        string $password = '',
        string $nodeHost = 'http://127.0.0.1:3001'
    ) {
        parent::__construct($nodeHost);
        $this->pageUrl = $pageUrl;
        $this->account = $account;
        $this->password = $password;
        $this->landingUrlHint = SplitPageUrlResolver::resolveFinalUrl($pageUrl);
        $this->unifiedData = new UnifiedScrmData();
    }

    protected function getSpiderConfig(): array
    {
        $antiBot = AntiBotConfigBuilder::build('huojian', $this->pageUrl, $this->landingUrlHint);

        return [
            'pageUrl'        => $this->pageUrl,
            'listApi'        => self::API_LIST,
            'listMethod'     => 'POST',
            'paginationMode' => self::MODE_UI,
            'authActions'    => [
                ['type' => 'vue_fill', 'selector' => '.el-message-box__input input', 'value' => $this->password],
                ['type' => 'wait', 'ms' => 500],
                ['type' => 'vue_click', 'selector' => '.el-message-box__btns .el-button--primary'],
                ['type' => 'wait', 'ms' => 2000],
            ],
            'antiBot'        => $antiBot,
        ];
    }

    protected function extractListTotalPages($listFirstPageData, $countData = null)
    {
        return 1;
    }

    protected function buildListPageParams(int $page): array
    {
        return [];
    }

    protected function getUiPaginationConfig(): array
    {
        return [];
    }

    protected function parseToUnifiedData($detailData, array $allListPagesData): UnifiedScrmData
    {
        $unifiedData = $this->unifiedData;
        $unifiedData->todayNewCount = (int) ($allListPagesData[0]['data']['counterWorker']['newTodayFriend'] ?? 0);
        $count = 0;
        foreach ($allListPagesData as $pageRaw) {
            $records = $pageRaw['data']['counterCsAccountVo'] ?? [];
            foreach ($records as $item) {
                if (empty($item['accountLogin'])) {
                    continue;
                }
                $number = (string) $item['accountLogin'];
                $isOnline = isset($item['accountStatus']) && (int) $item['accountStatus'] === 1;
                $count++;
                $unifiedData->addNumber($number, $isOnline, (int) ($item['newTodayFriend'] ?? 0));
            }
        }
        $unifiedData->total = $count;

        return $unifiedData;
    }
}
