<?php


swoole_set_process_name('php-email-sync-list');

$pm = new \Swoole\Process\Manager();


$pm->addBatch(60,function ($work_id) {

    include_once __DIR__."/../vendor/autoload.php";

    $number = 0;
    while (true){
        if($number > 500){  break;  }

        // 需要同步的id
        $id = redis()->lPop('sync_email_lists');

        if($id && is_numeric($id)){
            // 占用当前的id,占用2小时
            if(redis()->add('just_sync_'.$id,time(),600)){
                $number++;

                try{
                    // 开始同步
                    $email = db()->cache(3600)->first(\Model\emailSql::first($id));
                    if($email){
                        $sync = new \Service\SyncMail($email);
                        $search = new \Lib\Imap\ImapSearch();
                        // 第一次同步 只同步当天的
                        if(!db()->cache(600)->count(\Model\listsSql::first('`id` > 0'))){
                            $sync->search($search->dateGt($email['created_at']));
                        }else{

                            if(strtotime("-2 day") > strtotime($email['created_at'])){
                                $sync->search(
                                    $search->dateGt(
                                        date('Y-m-d',
                                            strtotime("-2 day")
                                        )
                                    )
                                );
                            }else{
                                $sync->search(
                                    $search->dateGt($email['created_at'])
                                );
                            }

                        }

                        $sync->sync();

                        $sync = null;
                        unset($sync);
                    }

                }catch (Throwable $e){
                    logs('sync : '.$e->getMessage());
                }

                // 30秒后 消除占用
                redis()->expire('just_sync_'.$id,120);

            }
        }
        else{
            sleep(1);
        }

    }
});


$pm->start();