<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\adminapi\controller\collect;

use app\adminapi\controller\BaseAdminController;

/**
 * 用户数据采集
 * Class UserController
 * @package app\adminapi\controller\user
 */
class UserCollect extends BaseAdminController
{
    // DZ用户数据采集
    public function insertUserDZ()
    {
        $list = $this->request->post('list');
        $page = $this->request->post('page');

        $saveData=[];

        foreach($list as $v){
            $saveData[]=[
                "code"=>"DZ",
                "register_source"=>0,
                "dz_uid"=>intval($v['uid']),
                "nickname"=>$v['username'],
                "account"=>$v['username'],
                "avatar"=>$v['avatar'],
                "password"=>$v['password'],
                "user_integral"=>$v['freeze'],//积分
                "salt"=>$v['salt'],//md5(md5($password).$user['salt'])
                'ip'=>$v['regip'],
                'login_ip'=>$v['regip'],
                'ip_address'=>$v['regip'],
                'level'=>1,
            ];
        }

        try{

            // $res = \app\common\model\User::insertAll($saveData,false, 'IGNORE');

            $res = \think\facade\Db::name('user')
            ->extra('IGNORE')
            ->insertAll($saveData);

            // 记录当前页数 用于下次断点采集
            \app\common\service\ConfigService::set('user_collect','dz_page',$page);

            return \show(1,'导入成功');
        }catch(\Exception $e){
            return \show(0,'导入失败'.$e->getMessage());
        }
        
    }

    // 删除所有dz采集的用户数据
    public function delAllDZUser()
    {
        \app\common\model\User::whereNotNull("dz_uid")->select()->delete();
        return \show(1,'删除成功');
    }

    // 查询上一次采集到第几页
    public function dzPageRecord()
    {
        $page=\app\common\service\ConfigService::get('user_collect','dz_page',0);
        return \show(1,['page'=>$page]);
    }

    // 清楚断点采集记录
    public function dzPageRecordDel()
    {
        $page=\app\common\service\ConfigService::set('user_collect','dz_page',0);
        return \show(1,['page'=>$page]);
    }

    /**
     * 发送带自定义Header的GET请求
     * 
     * @param string $url 请求的URL地址
     * @param array $headers 自定义请求头，格式：['Header-Name: Value', ...]
     * @param bool $followRedirect 是否跟随重定向
     * @param int $timeout 超时时间(秒)
     * @return array 响应结果，包含状态码、响应头和响应体
     */
    public function http_get_with_headers($url, $headers = [], $followRedirect = true, $timeout = 10) {
        // 初始化cURL
        $ch = curl_init();
        
        // 设置基本选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应内容而非直接输出
        curl_setopt($ch, CURLOPT_HEADER, true); // 包含响应头信息
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // 超时设置
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $followRedirect); // 是否跟随重定向
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // 最大重定向次数
        
        // 设置自定义请求头
        if (!empty($headers) && is_array($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        
        // 执行请求
        $response = curl_exec($ch);
        
        // 获取错误信息
        $error = curl_error($ch);
        if ($error) {
            curl_close($ch);
            return [
                'success' => false,
                'error' => '请求失败: ' . $error
            ];
        }
        
        // 获取响应状态码
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // 获取响应头大小
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        
        // 分离响应头和响应体
        $responseHeaders = substr($response, 0, $headerSize);
        $responseBody = substr($response, $headerSize);
        
        // 解析响应头为数组
        $parsedHeaders = [];
        $headerLines = explode("\r\n", trim($responseHeaders));
        foreach ($headerLines as $line) {
            $colonPos = strpos($line, ':');
            if ($colonPos !== false) {
                $key = trim(substr($line, 0, $colonPos));
                $value = trim(substr($line, $colonPos + 1));
                $parsedHeaders[$key] = $value;
            }
        }
        
        // 关闭cURL资源
        curl_close($ch);
        
        // 返回结果
        return [
            'success' => true,
            'status_code' => $statusCode,
            'headers' => $parsedHeaders,
            'body' => $responseBody,
            // 尝试自动解析JSON响应体
            'json' => json_decode($responseBody, true)
        ];
    }

}