<?php
// Whatshub 工单平台

require_once __DIR__ . '/AbstractScrmSpider.class.php';

class Whatshub extends AbstractScrmSpider
{
    const API_LIST  = '/api/whatshub-counter/workShare/open/detail';    // 列表API地址
    const API_DETAILS = '/api/whatshub-counter/workShare/open/statistics';       // 详情API地址
    const API_COUNT = '';                                       // 总数API地址
    const DEFAULT_PER_PAGE_COUNT = 20;                          // List默认每页显示的数量
    private $pageUrl;
    private $account;
    private $password;
    private $unifiedData;
    
    // 实例化时动态传入账号和密码
    public function __construct($pageUrl, $account, $password, $nodeHost = 'http://127.0.0.1:3001')
    {
        parent::__construct($nodeHost);
        $this->account = $account;
        $this->password = $password;
        $this->pageUrl = $pageUrl;
        
        $this->unifiedData = new UnifiedScrmData();
    }

    protected function getSpiderConfig()
    {
        $host = (string) parse_url($this->pageUrl, PHP_URL_HOST);
        return [
            'pageUrl' => $this->pageUrl,
            'apiUrls' => [self::API_LIST, self::API_DETAILS],
            
            // 明确指派角色
            'listApi'   => self::API_LIST,                  // 必须
            
            'listMethod' => 'POST',
            'paginationMode' => self::MODE_UI,
            
            'authActions' => [
                // 1. 填入密码：寻找 class 包含 el-message-box__input 下面的任意 input
                // Node.js 会自动扫描所有匹配项，并只把密码强行注入到那个“肉眼可见”的框里
                ['type' => 'vue_fill', 'selector' => '.el-input__inner', 'value' => $this->password],
                
                // 2. 停顿 500ms，让 Vue 绑定的 v-model 彻底反应过来
                ['type' => 'wait', 'ms' => 500],
                
                // 3. 点击确认：寻找 MessageBox 底部的蓝色 primary 确认按钮
                // 同样利用 vue_click 的可见性过滤，无视隐藏的旧弹窗按钮
                ['type' => 'vue_click', 'selector' => '.vxe-button-group .theme--primary'],
                
                // 4. 等待弹窗淡出，接口开始请求
                ['type' => 'wait', 'ms' => 2200]
            ],
            // Whatshub 专用：Real Browser + Turnstile + Captcha API 兜底 + 会话复用
            'antiBot'        => [
                'enabled'            => true,
                'profile'            => 'real',
                'turnstile'          => true,
                'solverFallback'     => true,
                'sessionKey'         => 'whatshub:' . $host,
                'challengeTimeoutMs' => 60000,
            ],
        ];
    }

    // 只负责解析 List 的总页数
    protected function extractListTotalPages($listFirstPageData, $countData = null)
    {
        $default_per_page_count = self::DEFAULT_PER_PAGE_COUNT;
        $this->unifiedData->total = $listFirstPageData['data']['total'];
        
        if($this->unifiedData->total <= $default_per_page_count) {
            return 1;
        }
        
        return ceil($this->unifiedData->total/$default_per_page_count);
    }

    // 没有分页返回空数组
    protected function buildListPageParams($page)
    {
        return ['pageNum' => $page, 'pageSize' => self::DEFAULT_PER_PAGE_COUNT];
    }

    // 提供 List 的下一页按钮信息
    protected function getUiPaginationConfig()
    {
        return [
            'nextBtnSelector' => '.vxe-pager--next-btn', 
            'waitMs'          => 1500
        ];
    }

    // 清爽至极的数据清洗：详情是详情，列表是列表
    protected function parseToUnifiedData($detailData, $allListPagesData)
    {
        $unifiedData = $this->unifiedData;
        
        // 1. 如果捕获到了详情数据，提取今日新增
        if ($detailData) {
            $unifiedData->todayNewCount = (int)($detailData['data']['dayNewFans'] ?? 0);
        }

        // 2. 循环合并了所有页数的 List 数组
        foreach ($allListPagesData as $pageRaw) {
            $records = $pageRaw['data']['rows'] ?? []; 
            foreach ($records as $item) {
                if(!empty($item['account'])) {
                    $number = $item['account'] ?? null;
                    $isOnline = (isset($item['isOnline']) && $item['isOnline'] == 1);
                    
                    $unifiedData->addNumber($number, $isOnline, $item['dayNewFans']);
                }
            }
        }
        
        // 🚀 3. 终极统计：所有翻页数据均已入库，此时再统计真实的 Total 总数
        $unifiedData->total = count($unifiedData->numbers);

        return $unifiedData;
    }
}