<?php

declare(strict_types=1);

namespace app\common\library\scrm\spider;

use app\common\library\scrm\AbstractScrmSpider;
use app\common\library\scrm\UnifiedScrmData;

/**
 * 海王云控蜘蛛
 */
class HaiwangSpider extends AbstractScrmSpider
{
    private const API_LIST = '/webApi/accountshow/list';

    private const DEFAULT_PER_PAGE_COUNT = 10;

    private string $pageUrl;

    private string $account;

    private string $password;

    private UnifiedScrmData $unifiedData;

    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->unifiedData = new UnifiedScrmData();
    }

    protected function getSpiderConfig(): array
    {
        return [
            'pageUrl'        => $this->pageUrl,
            'listApi'        => self::API_LIST,
            'listMethod'     => 'POST',
            'paginationMode' => self::MODE_UI,
            'authActions'    => [
                ['type' => 'type', 'selector' => 'input[type="password"]', 'value' => $this->password],
                ['type' => 'press', 'key' => 'Enter'],
                ['type' => 'wait', 'ms' => 2000],
            ],
        ];
    }

    protected function extractListTotalPages($listFirstPageData, $countData = null)
    {
        $total = (int) ($listFirstPageData['data']['total'] ?? 0);
        $this->unifiedData->total = $total;
        if ($total <= self::DEFAULT_PER_PAGE_COUNT) {
            return 1;
        }
        return (int) ceil($total / self::DEFAULT_PER_PAGE_COUNT);
    }

    protected function buildListPageParams(int $page): array
    {
        return ['page' => $page, 'limit' => self::DEFAULT_PER_PAGE_COUNT];
    }

    protected function getUiPaginationConfig(): array
    {
        return [
            'nextBtnSelector' => '.btn-next',
            'waitMs'          => 2000,
        ];
    }

    protected function parseToUnifiedData($detailData, array $allListPagesData): UnifiedScrmData
    {
        $unifiedData = $this->unifiedData;
        foreach ($allListPagesData as $pageRaw) {
            $records = $pageRaw['data']['items'] ?? [];
            foreach ($records as $item) {
                if (empty($item['acclist_account'])) {
                    continue;
                }
                $number = (string) $item['acclist_account'];
                $isOnline = isset($item['acclist_status']) && (int) $item['acclist_status'] === 2;
                $unifiedData->addNumber(
                    $number,
                    $isOnline,
                    (int) ($item['account_statistics_today_effective'] ?? 0)
                );
            }
        }
        if (!empty($allListPagesData[0]['data']['shareStatistics']['sharecode_statistics_today_contact_effective'])) {
            $unifiedData->todayNewCount = (int) $allListPagesData[0]['data']['shareStatistics']['sharecode_statistics_today_contact_effective'];
        }
        return $unifiedData;
    }
}
