<?php

declare(strict_types=1);

namespace app\common\library\scrm\spider;

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

/**
 * 星河云控蜘蛛
 */
class XingheSpider extends AbstractScrmSpider
{
    private const API_LIST = '/share/share/api_yinliu_count.html';

    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'     => 'GET',
            'paginationMode' => self::MODE_FETCH,
            'authActions'    => [
                ['type' => 'wait', 'ms' => 2000],
            ],
        ];
    }

    protected function extractListTotalPages($listFirstPageData, $countData = null)
    {
        $total = (int) ($listFirstPageData['count'] ?? 0);
        $this->unifiedData->total = $total;
        $this->unifiedData->todayNewCount = (int) ($listFirstPageData['totalRow']['day_sum'] ?? 0);
        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' => '.layui-laypage-next',
            'waitMs'          => 2000,
        ];
    }

    protected function parseToUnifiedData($detailData, array $allListPagesData): UnifiedScrmData
    {
        $unifiedData = $this->unifiedData;
        foreach ($allListPagesData as $pageRaw) {
            $records = $pageRaw['data'] ?? [];
            foreach ($records as $item) {
                if (empty($item['user'])) {
                    continue;
                }
                $number = (string) $item['user'];
                $isOnline = isset($item['online']) && (int) $item['online'] === 1;
                $unifiedData->addNumber($number, $isOnline, (int) ($item['day_sum'] ?? 0));
            }
        }
        return $unifiedData;
    }
}
