RelayInquiryTest.php 36.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
<?php
/**
 * Created by PhpStorm.
 * User: zhl
 * Date: 2024/09/30
 * Time: 11:51
 */
namespace App\Console\Commands\Inquiry;

use App\Helper\Common;
use App\Helper\Gpt;
use App\Helper\Translate;
use App\Helper\Validate;
use App\Models\Ai\AiCommand;
use App\Models\Inquiry\ReInquiryConfig;
use App\Models\Inquiry\ReInquiryDetail;
use App\Models\Inquiry\ReInquiryDetailLog;
use App\Models\Inquiry\ReInquiryForm;
use App\Models\Inquiry\ReInquiryTask;
use App\Models\Inquiry\ReInquiryText;
use App\Models\Project\InquiryFilterConfig;
use App\Models\Project\Project;
use App\Models\WebSetting\WebLanguage;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

/**
 * Class RelayInquiry
 * @package App\Console\Commands\Inquiry
 */
class RelayInquiryTest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'relay_inquiry_test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '重启失败的转发询盘';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 模拟访问来源占比
     * @var array
     */
    protected $lyzb = [
        'https://www.google.com/' => 630,
        'http://www.google.com/' => 30,
        'http://www.bing.com/' => 20,
        'https://www.bing.com/' => 5,
        'https://www.youtube.com/' => 5,
        'https://search.yahoo.com/' => 5,
        'https://www.facebook.com/' => 5,
    ];

    /**
     * 俄语站 模拟访问来源占比
     * @var array
     */
    protected $eylyzb = [
        'https://www.yandex.com/' => 630,
        'https://www.google.com/' => 30,
        'http://www.google.com/' => 30,
        'http://www.bing.com/' => 20,
        'https://www.bing.com/' => 5,
        'https://www.youtube.com/' => 5,
        'https://search.yahoo.com/' => 5,
        'https://www.facebook.com/' => 5,
    ];

    /**
     * PC端访问头信息
     * @var array
     */
    protected $pc_ua = [
        0  => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
        1  => 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
        2  => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
    ];

    /**
     * 移动端访问头信息
     * @var array
     */
    protected $mobile_ua = [
        0  => 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko; googleweblight) Chrome/38.0.1025.166 Mobile Safari/535.19',
    ];

    /**
     * google域名后缀
     * @var string[]
     */
    protected $suffix = [
        'co.jp' => '日本',
        'com.tr' => '土耳其',
        'nl' => '荷兰',
        'ru' => '俄罗斯',
        'fr' => '法国',
        'co.kr' => '韩国',
        'fi' => '芬兰',
        'be' => '比利时',
        'lt' => '立陶宛',
        'es' => '西班牙',
        'it' => '意大利',
        'com.au' => '澳大利亚',
        'no' => '挪威',
        'al' => '阿尔巴尼亚',
        'pt' => '葡萄牙',
        'lv' => '拉脱维亚',
        'hu' => '匈牙利',
        'cz' => '捷克',
        'de' => '德国',
        'ca' => '加拿大',
        'co.in' => '印度',
        'co.uk' => '英国',
        'com.vn' => '越南',
        'com.br' => '巴西',
        'co.il' => '以色列',
        'pl' => '波兰',
        'com.eg' => '埃及',
        'co.th' => '泰国',
        'sk' => '斯洛伐克',
        'ro' => '罗马尼亚',
        'com.mx' => '墨西哥',
        'com.my' => '马来西亚',
        'com.pk' => '巴基斯坦',
        'co.nz' => '新西兰',
        'co.za' => '南非',
        'com.ar' => '阿根廷',
        'com.kw' => '科威特',
        'com.sg' => '新加坡',
        'com.co' => '哥伦比亚',
        'co.id' => '印度尼西亚',
        'gr' => '希腊',
        'bg' => '保加利亚',
        'mn' => '蒙古',
        'dk' => '丹麦',
        'com.sa' => '沙特阿拉伯',
        'com.pe' => '秘鲁',
        'com.ph' => '菲律宾',
        'com.ua' => '乌克兰',
        'ge' => '格鲁吉亚',
        'ae' => '阿拉伯联合酋长国',
        'tn' => '突尼斯',
    ];

    protected $otherzb = [700, 300]; //模拟访问来源占比 (非美国) google.com|google.其他后缀

    /**
     * 手机号过滤 0去掉+  1不转发手机  2不处理
     * @var int[]
     */
    protected $filter_phone = [30,12,58];

    /**
     * 需要多个ip访问的国家
     * @var
     */
    protected $multiple_ip_visit_country = [
        '阿尔及利亚',
        '埃及',
        '埃塞俄比亚',
        '安哥拉',
        '贝宁',
        '博茨瓦纳',
        '布基纳法索',
        '布隆迪',
        '赤道几内亚',
        '多哥',
        '厄立特里亚',
        '佛得角',
        '冈比亚',
        '刚果共和国',
        '刚果民主共和国',
        '吉布提',
        '几内亚',
        '几内亚比绍共和国',
        '加纳',
        '加蓬',
        '津巴布韦',
        '喀麦隆',
        '科摩罗',
        '科特迪瓦',
        '肯尼亚',
        '莱索托',
        '利比里亚',
        '利比亞',
        '留尼汪',
        '卢旺达',
        '马达加斯加',
        '马拉维',
        '马里',
        '马约特',
        '毛里求斯',
        '毛里塔尼亚',
        '摩洛哥',
        '莫桑比克',
        '纳米比亚',
        '南非',
        '南苏丹',
        '尼日尔',
        '尼日利亚',
        '塞拉利昂',
        '塞内加尔',
        '塞舌尔',
        '圣多美和普林西比',
        '圣赫勒拿',
        '斯威士兰',
        '索马里',
        '坦桑尼亚',
        '突尼斯',
        '乌干达',
        '西撒哈拉',
        '赞比亚',
        '乍得',
        '中非共和国',
        '阿富汗',
        '阿联酋',
        '阿曼',
        '阿塞拜疆',
        '澳门',
        '巴基斯坦',
        '巴勒斯坦',
        '巴林',
        '不丹',
        '东帝汶',
        '菲律宾',
        '格鲁吉亚',
        '哈萨克斯坦',
        '韩国',
        '吉尔吉斯斯坦',
        '柬埔寨',
        '卡塔尔',
        '科威特',
        '老挝',
        '黎巴嫩',
        '马尔代夫',
        '马来西亚',
        '蒙古',
        '孟加拉国',
        '缅甸',
        '尼泊尔',
        '日本',
        '塞浦路斯',
        '沙特阿拉伯',
        '斯里兰卡',
        '塔吉克斯坦',
        '泰国',
        '土耳其',
        '土库曼斯坦',
        '文莱',
        '乌兹别克斯坦',
        '新加坡',
        '亚美尼亚',
        '也门',
        '伊拉克',
        '以色列',
        '印度尼西亚',
        '约旦',
        '越南',
    ];

    /**
     * @return bool
     */
    public function handle()
    {
        while (true) {
            $inquiry = ReInquiryForm::where('created_at', '>', '2025-05-19 00:00:00')
                ->where('created_at', '<', '2025-05-22 18:00:00')
                ->where(['status' => ReInquiryForm::STATUS_FORGO])
                ->where('remark', '超时72小时未处理!')
                ->orderBy('id', 'asc')->get();

            if ($inquiry->isEmpty()){
                $this->output('未发现待处理询盘!');
                sleep(60);
                continue;
            }

            $this->output('开始处理本轮询盘!');
            foreach ($inquiry as $key=>$val) {
                $this->output('询盘ID:' . $val->id);


                $detail_ids =  ReInquiryDetail::where('form_id', $val->id)->pluck('id')->toArray();

                $inquiry_log = ReInquiryDetailLog::whereIn('detail_id', $detail_ids)->where('type', ReInquiryDetailLog::TYPE_INQUIRY)->first();
                //有询盘的了 就跳过
                if($inquiry_log){
                    continue;
                }

                // 询盘对应广告
                $ad_task = $this->getAdTask($val->ad_id);
                // 没有获取到转发任务
                if (empty($ad_task)) {
                    $val->status = ReInquiryForm::STATUS_FORGO;
                    $val->remark = '未找到需要转发的广告任务!';
                    $val->save();
                    continue;
                }
                // 未设置对法对象
                $target_num_arr = array_map(function ($item) {
                    return count($item['target']) + count($item['shop_site']) + count($item['fob_pro']);
                }, $ad_task);
                if (!array_sum($target_num_arr)) {
                    $val->status = ReInquiryForm::STATUS_FORGO;
                    $val->remark = '广告任务转发对象为空!';
                    $val->save();
                    continue;
                }
                //是否要过滤
                $filter_res = $this->filter($val);
                if($filter_res !== true){
                    $val->status = ReInquiryForm::STATUS_FORGO;
                    $val->remark = $filter_res;
                    $val->save();
                    continue;
                }
                //验证手机号 无效 号码不推送
                if(!Validate::phone($val->phone)){
                    $val->phone = '';
                }
                try {
                    $res = false;
                    foreach ($ad_task as $task){
                        $res += $this->relayDetail($task, $val);
                        $res += $this->relayShopDetail($task, $val);
                        $res += $this->relayFobDetail($task, $val);
                    }
                    $val->status = $res ? ReInquiryForm::STATUS_SUCCESS : ReInquiryForm::STATUS_FORGO;
                    $val->save();
                } catch (\Exception $e) {
                    $this->logChannel()->info('执行询盘错误:',[$e->getMessage(), $e->getFile(), $e->getLine()]);
                    $this->output('执行询盘错误:' . $e->getMessage());
                }
            }
            $this->output('本轮询盘处理结束!');
        }
        return true;
    }


    public function filter($data)
    {
        //通用过滤规则
        $config = InquiryFilterConfig::getCacheInfoByProjectId(Project::DEMO_PROJECT_ID);
        //FB询盘的全局过滤规则
        $fb_config = ReInquiryConfig::getDefaultConfigCache(ReInquiryConfig::TYPE_FILTER_WORDS);

        $fb_config['filter_contents'] = array_filter(explode("\r\n", $fb_config['filter_contents']??''));
        $fb_config['filter_emails'] = array_filter(explode("\r\n", $fb_config['filter_emails']??''));
        $fb_config['filter_mobiles'] = array_filter(explode("\r\n", $fb_config['filter_mobiles']??''));
        $fb_config['filter_names'] = array_filter(explode("\r\n", $fb_config['filter_names']??''));

        $config['filter_contents'] = array_unique(array_merge($fb_config['filter_contents'],$config['filter_contents']));
        $config['filter_emails'] = array_unique(array_merge($fb_config['filter_emails'],$config['filter_emails']));
        $config['filter_mobiles'] = array_unique(array_merge($fb_config['filter_mobiles'],$config['filter_mobiles']));
        $config['filter_names'] = array_unique(array_merge($fb_config['filter_names'],$config['filter_names']));

        //过滤内容
        if(!empty($data['message']) && !empty($config['filter_contents'])) {
            foreach ($config['filter_contents'] as $filter_content) {
                if (Str::contains(strtolower($data['message']), strtolower($filter_content))) {
                    return '过滤内容:' . $filter_content;
                }
            }
        }
        //过滤邮箱
        if(!empty($data['email']) && !empty($config['filter_emails'])){
            foreach ($config['filter_emails'] as $filter_email){
                if(Str::contains(strtolower($data['email']), strtolower($filter_email))){
                    return '过滤邮箱:' . $filter_email;
                }
            }
            //邮箱有效性
            if(!Validate::email($data['email'])){
                return '邮箱无效';
            }
        }
        //过滤电话
        if(!empty($data['phone']) && !empty($config['filter_mobiles'])){
            foreach ($config['filter_mobiles'] as $filter_mobile){
                if(Str::contains(strtolower($data['phone']), strtolower($filter_mobile))){
                    return '过滤电话:' . $filter_mobile;
                }
            }
        }
        //过滤姓名
        if(!empty($data['full_name'] && !empty($config['filter_names']))){
            foreach ($config['filter_names'] as $filter_name){
                if(Str::contains(strtolower($data['full_name']), strtolower($filter_name))){
                    return '过滤姓名:' . $filter_name;
                }
            }
        }
        return true;
    }

    /**
     * 创建转发详情
     * TODO 通过任务生成转发对象, 更具转发对象获取对应数据, 写入着陆记录
     * @param $task
     * @param $form
     * @return bool
     */
    public function relayDetail($task, $form)
    {
        $this->output('获取转发对象');
        if(empty($task['target'] )){
            $this->output('没有独立站转发对象');
            return 0;
        }
        //是否有必选的渠道 渠道有一个及以上必选 就在组内随机一个
        $require_agent_group = [];
        foreach ($task['target'] as $item) {
            if (!empty($item['is_require'])) {
                $require_agent_group[] = $item['agent_group'];
            }
        }
        $require_agent_group = array_unique($require_agent_group);
        $require_agent_group_data = collect($task['target'])->whereIn('agent_group', $require_agent_group)->groupBy('agent_group');
        $require_data = $require_agent_group_data->keys()->random(count($require_agent_group))->map(function ($group) use ($require_agent_group_data) {
            return $require_agent_group_data[$group]->random();
        })->all();
        //代理商组 一个组只发一个
        $agent_group = collect($task['target'])->whereNotIn('agent_group', $require_agent_group)->groupBy('agent_group');
        // 获取转发对象 重置num数量, array_rand数量不足会报错
        $task['num'] = $task['num'] - count($require_agent_group);
        $num = $task['num'] > count($agent_group) ? count($agent_group) : $task['num'];
        $random_data = $agent_group->keys()->random($num)->map(function ($group) use ($agent_group) {
            return $agent_group[$group]->random();
        })->all();
        $random_data = array_merge($require_data, $random_data);

        if (empty($random_data)) {
            $this->logChannel()->info('当前任务未发现转发对象!', ['广告任务ID:' . $task['id'], '询盘ID:' . $form->id]);
            $form->remark = $form->remark . '当前任务未发现转发对象,广告ID: ' . $form->ad_id . '!';
            return false;
        }
        $this->logChannel()->info('随机域名', array_column($random_data, 'url'));
        foreach ($random_data as $item) {
            $times = 1;
            $inquiry_time = 1;

            //需要多个ip访问的国家 随机2-5次访问,只有一次询盘
            if (in_array($form->country_name, $this->multiple_ip_visit_country)) {
                $times = mt_rand(1, 2); //随机次数
                $inquiry_time = mt_rand(1, $times); //第几次询盘
                $this->output('多次访问模拟:' . $times .',第' . $inquiry_time . '次询盘');
            }
            for ($i = 1; $i <= $times; $i++) {
                $is_inquiry = ($inquiry_time == $i);
                if($is_inquiry){
                    $this->output('第' . $i . '次询盘');
                }
                //手机号过滤
                $phone = $form->phone;
                $filter_phone = $this->get_rand($this->filter_phone);
                if($filter_phone == 0){
                    $phone = trim(str_replace("+", '', $phone));
                }elseif($filter_phone == 1){
                    $phone = '';
                }

                // 推送站点
                $domain = $item['url'];
                $is_v6 = $item['is_v6'];
                $re_website = 'https://' . $domain . '/';

                //urls
                list($urls, $lang, $inquiry_product_url) = $this->getUrls($is_v6, $domain, $re_website, $form, $task);
                if(!$urls){
                    continue;
                }

                //ip
                $ip_data = $this->getIpData($form->country_name);
                $ip = $ip_data->ip;
                $country_name = $ip_data->ip_area;

                //message
                $message = '';
                $message_id = 0;
                $msg_lang = '';
                if($is_inquiry) {
                    list($message, $message_id, $msg_lang) = $this->getMessage($task, $form->message, $domain, $inquiry_product_url);
                }
                $lang = $lang ?: $msg_lang;

                $this->output('获取转发设备信息');
                // 客户端 头信息 来源
                $device_port = $form->email ? '1' : '2'; //1 pc 2移动端
                $user_agent = $form->email ? Arr::random($this->pc_ua) : Arr::random($this->mobile_ua);
                $referrer = $this->getReferer($country_name, $lang);
                $this->output('写入数据');

                $pre = 0;
                $start_time = strtotime($form->inquiry_date);
                if($start_time < time()){
                    $start_time = time();
                    $seconds = rand(0, 72 * 3600);   // 3天内发完
                }else{
                    $seconds = rand(100, 2 * 3600);
                }
                $email = '';
                if($is_inquiry) {
                    $exists = ReInquiryDetail::where('re_website', $domain)->where('email', $form->email)->first();
                    if ($exists) {
                        $this->output('转发站点邮件已存在');
                       // continue;
                    }
                    $email = $form->email;
                }
                dump(date('Y-m-d H:i:s', $start_time + $seconds));
                // 写入推送详情
                $re_detail = ReInquiryDetail::createInquiry($task['id'], $form->id, $domain, $country_name, $ip, $form->full_name, $email, $phone, $message, $message_id, $device_port,
                    $user_agent, $referrer, $urls, $is_v6, date('Y-m-d H:i:s', $start_time + $seconds));
                foreach ($urls as $k=>$v){
                    $pre++;
                    $seconds += rand(5,60);
                    ReInquiryDetailLog::createInquiryLog($re_detail->id, ReInquiryDetailLog::TYPE_VISIT, $pre, $v, date('Y-m-d H:i:s', $start_time + $seconds));
                    // 最后一次访问询盘 加上询盘
                    if($is_inquiry && ($k+1) == count($urls)){
                        $this->output('第' . ($k+1) . '个链接询盘');
                        $seconds += rand(30,120);
                        $pre++;
                        ReInquiryDetailLog::createInquiryLog($re_detail->id, ReInquiryDetailLog::TYPE_INQUIRY, $pre, $v, date('Y-m-d H:i:s', $start_time + $seconds));
                    }
                }
            }
        }
        return true;
    }

    public function relayShopDetail($task, $form)
    {
        $this->output('获取商城转发对象');

        if(empty($task['shop_site'])){
            $this->output('没有商城转发对象');
            return 0;
        }

        $num = $task['num'] > count($task['shop_site']) ? count($task['shop_site']) : $task['num'];
        $shop_site = collect($task['shop_site'])->random($num)->all();

        foreach ($shop_site as $item) {
            //手机号过滤
            $phone = $form->phone;
            // 推送站点
            $domain = $item;
            $re_website = 'https://' . $domain . '/';
            $paths = ['', 'contact-us'];
            $url = $re_website . $paths[array_rand($paths)];
            //ip
            $ip_data = $this->getIpData($form->country_name);
            $ip = $ip_data->ip;
            $country_name = $ip_data->ip_area;

            //message
            list($message, $message_id, $lang) = $this->getMessage($task, $form->message, $domain);

            $device_port = $form->email ? '1' : '2'; //1 pc 2移动端
            $user_agent = $form->email ? Arr::random($this->pc_ua) : Arr::random($this->mobile_ua);
            $referrer = $this->getReferer($country_name, $lang);

            $start_time = strtotime($form->inquiry_date);
            if($start_time < time()){
                $start_time = time();
                $seconds = rand(0, 48 * 3600);   // 开始时间 从5-2小时后开始
            }else{
                $seconds = rand(100, 2 * 3600);
            }
            dump(date('Y-m-d H:i:s', $start_time + $seconds));
            $exists = ReInquiryDetail::where('re_website', $domain)->where('email', $form->email)->first();
            if($exists){
                $this->output('转发站点邮件已存在');
                continue;
            }
            $re_detail = ReInquiryDetail::createInquiry($task['id'], $form->id, $domain, $country_name, $ip, $form->full_name, $form->email, $phone, $message, $message_id,
                $device_port, $user_agent, $referrer, [$url], 0, date('Y-m-d H:i:s', $start_time + $seconds), ReInquiryDetail::STATUS_INIT, 2);

            ReInquiryDetailLog::createInquiryLog($re_detail->id, ReInquiryDetailLog::TYPE_INQUIRY, 1, $url, date('Y-m-d H:i:s', $start_time + $seconds));
        }
        return true;
    }


    public function relayFobDetail($task, $form)
    {
        $this->output('获取FOB转发对象');

        if(empty($task['fob_pro'])){
            $this->output('没有FOB转发对象');
            return 0;
        }

        foreach ($task['fob_pro'] as $item) {
            //手机号过滤
            $phone = $form->phone;
            // 推送站点
            $postid = $item;
            //message
            list($message, $message_id, $lang) = $this->getMessage($task, $form->message, $postid);

            $device_port = $form->email ? '1' : '2'; //1 pc 2移动端
            $user_agent = $form->email ? Arr::random($this->pc_ua) : Arr::random($this->mobile_ua);

            $start_time = strtotime($form->inquiry_date);
            if($start_time < time()){
                $start_time = time();
                $seconds = rand(0, 10 * 3600);   // 开始时间 从5-2小时后开始
            }else{
                $seconds = rand(100, 2 * 3600);
            }
            dump(date('Y-m-d H:i:s', $start_time + $seconds));
            $exists = ReInquiryDetail::where('re_website', $postid)->where('email', $form->email)->first();
            if($exists){
                $this->output('转发站点邮件已存在');
                continue;
            }
            $re_detail = ReInquiryDetail::createInquiry($task['id'], $form->id, $postid, $country_name??'', $ip??'', $form->full_name, $form->email, $phone,
                $message, $message_id, $device_port, $user_agent, $referrer??'', [$postid], 0, date('Y-m-d H:i:s', $start_time + $seconds), ReInquiryDetail::STATUS_INIT, 3);

            ReInquiryDetailLog::createInquiryLog($re_detail->id, ReInquiryDetailLog::TYPE_INQUIRY, 1, $postid, date('Y-m-d H:i:s', $start_time + $seconds));
        }
        return true;
    }

    public function getIpData($country_name){
        $this->output('获取转发ip');
        $country = $country_name;
        // 有国家 通过国家查询, 如果没有获取到就随机获取
        $where = [];
        $country && $where['ip_area'] = $country;
        $ip_data = DB::table('gl_xunpan_ipdata')->where($where)->inRandomOrder()->first();
        if (empty($ip_data)) {
            $ip_data = DB::table('gl_xunpan_ipdata')->inRandomOrder()->first();
        }
        return $ip_data;
    }

    public function getMessage($task, $message, $domain, $inquiry_product_url = ''){
        $this->output('转发内容');
        $form_message = $message;
        $message_id = 0;

        // TODO 当原始询盘内容长度大于15个字符, 60%几率直接发送原始内容。
        if (strlen($message) >= 15) {
            $not_use_probability = AiCommand::where('key', 'fb_inquiry_text')->value('not_use_probability');
            $randomNumber = rand(0, 100);
            if($randomNumber < $not_use_probability){
                //原内容非英语,转为对应语种
                if (is_numeric($form_message)) { //数字会被识别为中文
                    $lang = 'en';
                } else {
                    $translateSl = Translate::translateSl($form_message);
                    $lang = $translateSl['texts']['sl'] ?? 'en';
                }
                return [$message, $message_id, $lang??''];
            }
        }

        //开启文案替换
        if ($task['is_replace_text'] == 2) {
            //AI生成
            $error = 0;
            while ($error<3){
                $message = $this->ai_send($task['ai_param'], $message, $inquiry_product_url);
                if(!$message){
                    $this->output('AI文案生成失败');
                    $error++;
                    if($error==2){
                        $task['is_replace_text'] = 1;
                        $this->output('AI文案生成失败,使用文案库');
                    }
                }else{
                    break;
                }
            }
        }
        if ($task['is_replace_text'] == 1 || strlen($message) <= 4) {
            //配置文案库替换或者字符少于4个,直接替换文案
            $use_ids = ReInquiryDetail::where(['re_website' => $domain])->where('status', '<>', ReInquiryDetail::STATUS_FAIL)->pluck('text_id')->toArray();
            $text = ReInquiryText::whereNotIn('id', $use_ids)->where('status', ReInquiryText::STATUS_USABLE)->inRandomOrder()->first();
            $message = $text->content;
            $message_id = $text->id;
            // 获取后,使用次数+1
            $text->use_time += 1;
            $text->save();

            //原内容非英语,转为对应语种
            if (is_numeric($form_message)) { //数字会被识别为中文
                $lang = 'en';
            } else {
                $translateSl = Translate::translateSl($form_message);
                $lang = $translateSl['texts']['sl'] ?? 'en';
            }

            if ($lang != 'en' && !Str::contains($lang, 'zh')) {
                $message = Translate::tran($message, $lang);
            }
        }
        return [$message, $message_id, $lang??''];
    }

    public function getUrls($is_v6, $domain, $re_website, $form, $task){
        $this->output('转发对象:' . $domain);
        $this->output('获取转发链接');
        // v6:有邮箱推送主站,没有邮箱推送AMP站;v5:仅推送有邮箱到主站
        $lang = '';
        if ($is_v6) {
            // 获取语种, 6.0是可以确定语种的
            $project = Project::getProjectByDomain($domain);
            if (empty($project)) {
                $this->logChannel()->info('广告任务ID:' . $task['id'] . ', 转发对象:' . $re_website . '非v6链接,转发失败;', ['广告任务ID:' . $task['id'], '询盘ID:' . $form->id]);
                return [[], $lang];
            }
            $lang = WebLanguage::getLangById($project->main_lang_id ?? 1)['short'];

            // 获取访问明细和着陆页
            $product_url = $this->getLinksFromSitemap($re_website . 'product_sitemap.xml');
            $product_cate_url = $this->getLinksFromSitemap($re_website . 'product_category_sitemap.xml');
            $keywords_url = $this->getLinksFromSitemap($re_website . 'product_keywords_sitemap.xml');
            $page_url = $this->getLinksFromSitemap($re_website . 'page_sitemap.xml');
        } else {
            if($form->email){
                //通过sitemap拿访问页面
                $product_url = $this->getLinksFromSitemap($re_website . 'sitemap_post.xml');
                $product_cate_url = $this->getLinksFromSitemap($re_website . 'sitemap_category.xml');
                $keywords_url = $this->getLinksFromSitemap($re_website . 'sitemap_post_tag.xml');
                $page_url = $this->getLinksFromSitemap($re_website . 'sitemap_page.xml');
            }else{
                //m站先就往contact-us着陆
                $product_url = $product_cate_url = $keywords_url = [];
                $page_url = [$re_website . 'contact-us/'];
            }
        }

        // 所有可用url
        $urls = $inquiry_urls = [];
        //入口url 首页30%,单页10%,聚合页60%
        $type = getRandByRatio([30,10,60]);
        $inlet = $re_website;
        $type == 1 && $inlet = $page_url ? Arr::random($page_url) : $re_website;
        $type == 2 && $inlet = $keywords_url ? Arr::random($keywords_url) : $re_website;
        $urls[] = $inquiry_urls[] = $inlet;
        $all_urls = array_merge($urls, $product_url, $product_cate_url, $keywords_url, $page_url);
        $inquiry_urls = array_merge($urls, $product_cate_url, $keywords_url, $page_url);

        // 随机访问1-6个页面
        $deep = rand(1,6);
        if($deep > 2) {
            $visit_urls = Arr::random($all_urls, rand(1, count($all_urls) > 4 ? 4 : count($all_urls)));
            $urls = array_merge($urls, $visit_urls);
        }
        if($deep > 1) {
            // 推送着落页只能是 首页、产品分类、单页面、聚合页
            if (!in_array(end($urls), $inquiry_urls)) {
                $urls[] = Arr::random($inquiry_urls);
            }
        }
        //着陆页是否是产品页面或产品列表页
        $inquiry_product_url = '';
        if(in_array(Arr::last($urls), $product_url) || in_array(Arr::last($urls), $product_cate_url)){
            $inquiry_product_url = Arr::last($urls);
        }

        return [$urls, $lang, $inquiry_product_url];
    }
    /**
     * 获取待处理询盘表单
     * @param int $num
     * @return mixed
     */
    public function getInquiry($num = 10)
    {
        $result = ReInquiryForm::where(['status' => ReInquiryForm::STATUS_INIT])->orderBy('id', 'asc')->limit($num)->get();
        return $result;
    }

    /**
     * 获取广告任务配置数据
     * @param $ad_id
     * @return array
     */
    public function getAdTask($ad_id)
    {
        $cache_key = 'inquiry_ads_tasks';
        $ads = Cache::get($cache_key, function () use ($cache_key) {
            $ads = ReInquiryTask::where(['status' => ReInquiryTask::STATUS_OPEN])->get(['id', 'ad_id', 'num', 'target', 'is_replace_text', 'ai_param', 'shop_site', 'fob_pro']);
            $array = [];
            foreach ($ads as $key=>$val) {
               $ad_ids = explode(',', $val['ad_id']);
               foreach ($ad_ids as $ad_id){
                   $array[$ad_id][] = $val;
               }
            }
            if ($array)
                Cache::put($cache_key, $array, 60);
            return $array;
        });
        return empty($ads[$ad_id]) ? [] : $ads[$ad_id];
    }

    /**
     * 获取头信息
     * @param $ip_area
     * @param $lang
     * @return int|string
     */
    public function getReferer($ip_area, $lang)
    {
        if($lang == 'ru'){
            return $this->get_rand($this->eylyzb);
        }
        if($ip_area == '美国'){
            $referer = $this->get_rand($this->lyzb);
        }else{
            $referer = 'https://www.google.com/';
            $suffix = array_search($ip_area, $this->suffix);
            if($suffix){
                $res_qtzb = $this->get_rand($this->otherzb);
                if($res_qtzb == 1){
                    $referer = 'https://www.google.'.$suffix.'/';
                }
            }
        }
        return $referer;
    }

    /**
     * 概率算法
     * @param $proArr
     * @return int|string
     */
    protected function get_rand($proArr)
    {
        $result = '';
        $proSum = array_sum($proArr);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    /**
     * 获取sitemap内容
     * @param $sitemapUrl
     * @return array|mixed
     */
    function getLinksFromSitemap($sitemapUrl) {
        try {
            //忽略cert证书 先下载到临时文件
            $result = Http::withoutVerifying()->get($sitemapUrl)->body();
            $tempFilePath = tempnam(sys_get_temp_dir(), 'remote_file_');
            file_put_contents($tempFilePath, $result);
            $xml = simplexml_load_file($tempFilePath);
            $links = [];
            foreach ($xml->url as $url) {
                $loc = (string) $url->loc;
                if(!Str::contains($loc, ['404', 'thanks', 'test'])){
                    $links[] = $loc;
                }
            }
            //随机取20个
            $total = count($links);
            return Arr::random($links, $total > 20 ? 20 : $total);
        }catch (\Exception $e){
            echo date('Y-m-d H:i:s') . 'sitemap获取失败:' . $e->getMessage() . PHP_EOL;
            return $links??[];
        }
    }

    public function ai_send($ai_param, $incontent, $inquiry_product_url)
    {
        $ai_command = AiCommand::where('key', 'fb_inquiry_text')->value('ai');
        if (!$ai_command) {
            return '';
        }
        $translateSl = Translate::translateSl($incontent);
        $lang = $translateSl['texts']['sl'] ?? 'en';
        if ($lang == 'en' || $lang == 'ja' || $lang == 'ko' || Str::contains($lang, 'zh')) {
            $language = '英文';
            $lang = 'en';
        }else{
            $language = Translate::getTls($lang);
        }



        //着陆页是否是产品页面或产品列表页
        if($inquiry_product_url){
            $title = Common::getUrlTitle($inquiry_product_url);
            if($title){
                $ai_command = str_replace('{mkeywords}', $title, $ai_command);
            }
        }
        $ai_command = str_replace('{mkeywords}', Arr::random(explode("\r\n", $ai_param['mkeywords'])), $ai_command);
        $ai_command = str_replace('{incontent}', Arr::random(explode("\r\n", $incontent)), $ai_command);
        $ai_command = str_replace('{characters}', Arr::random(explode("\r\n", $ai_param['characters'])), $ai_command);
//        $ai_command = str_replace('{language}', Arr::random(explode("\r\n", $language)), $ai_command);
        $ai_command = str_replace('{language}', '英语', $ai_command); //输出英文 后面再翻译
        $ai_command = str_replace('{inkeywords}', Arr::random(explode("\r\n", $ai_param['inkeywords'])), $ai_command);
        $ai_command = str_replace('{suoxie}', Arr::random(explode("\r\n", $ai_param['suoxie'])), $ai_command);
        //中括号里的根据概率使用
        preg_match_all("/\[([^\]]+)\]/", $ai_command, $matches);
        foreach ($matches[1] as $k => $match){
            //按比例使用
            $matche_arr = explode('|', $match);
            $percentage = intval(trim($matche_arr[0], "%"));
            if(rand(1,100) <= $percentage){
                //使用
                $ai_command = str_replace($matches[0][$k], $matche_arr[1], $ai_command);
            }else{
                //删除中括号
                $ai_command = str_replace($matches[0][$k], '', $ai_command);
            }
        }

        $text = Gpt::instance()->openai_chat_qqs($ai_command);
        if ($lang != 'en' && !Str::contains($lang, 'zh')) {
            $text = Translate::tran($text, $lang);
        }
        $this->logChannel()->info("AI询盘文案", [$ai_command, $text]);
        return Common::deal_str($text);
    }

    /**
     * @return \Psr\Log\LoggerInterface
     */
    public function logChannel()
    {
        return Log::channel('inquiry_relay');
    }

    public function output($message)
    {
        echo date('Y-m-d H:i:s') . ' | ' . $message . PHP_EOL;
    }
}