<?php

declare(strict_types=1);

namespace app\common\library\scrm\spider;

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

/**
 * Chatknow SCRM 云控蜘蛛（UI 翻页 + 列表 API 拦截）
 */
class ChatknowSpider extends AbstractScrmSpider
{
    private const API_LIST = '/user/user/UserInfoChildChannel/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();
    }

    /** @return array<string, mixed> */
    protected function getSpiderConfig(): array
    {
        return [
            'pageUrl'        => $this->pageUrl,
            'listApi'        => self::API_LIST,
            'listMethod'     => 'GET',
            'paginationMode' => self::MODE_UI,
            'authActions'    => [
                ['type' => 'wait', 'ms' => 4000],
            ],
        ];
    }

    /**
     * @param array<string, mixed>|null $listFirstPageData
     * @param array<string, mixed>|null $countData
     */
    protected function extractListTotalPages($listFirstPageData, $countData = null)
    {
        $total = (int) ($listFirstPageData['total'] ?? 0);
        $this->unifiedData->total = $total;
        $this->unifiedData->todayNewCount = (int) ($listFirstPageData['data']['today_num'] ?? 0);

        if ($total <= self::DEFAULT_PER_PAGE_COUNT) {
            return 1;
        }

        return (int) ceil($total / self::DEFAULT_PER_PAGE_COUNT);
    }

    /** @return array<string, mixed> */
    protected function buildListPageParams(int $page): array
    {
        return ['page' => $page, 'limit' => self::DEFAULT_PER_PAGE_COUNT];
    }

    /** @return array<string, mixed> */
    protected function getUiPaginationConfig(): array
    {
        return [
            'nextBtnSelector' => '.tabs-content .arco-pagination-item-next',
            'waitMs'          => 2000,
        ];
    }

    protected function parseToUnifiedData($detailData, array $allListPagesData): UnifiedScrmData
    {
        $unifiedData = $this->unifiedData;

        foreach ($allListPagesData as $pageRaw) {
            if (!is_array($pageRaw)) {
                continue;
            }
            $records = $pageRaw['rows'] ?? [];
            if (!is_array($records)) {
                continue;
            }
            foreach ($records as $item) {
                if (!is_array($item) || empty($item['username'])) {
                    continue;
                }
                $number = (string) $item['username'];
                $isOnline = isset($item['state']) && (int) $item['state'] === 1;
                $unifiedData->addNumber($number, $isOnline, (int) ($item['today_num'] ?? 0));
            }
        }

        return $unifiedData;
    }
}
