<?php

namespace App\Console\Commands;

use App\Models\FrontUserModel;
use App\Models\Order;
use App\Models\DealRecord;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class BatchExportUserPhone extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'batch:export:user:phone';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导出学员电话';

    protected $logFile = '';

    protected $frontUserModel;

    protected $orderModel;

    protected $dealRecordModel;

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle() {
        $this->frontUserModel = new FrontUserModel();
        $this->orderModel = new Order();
        $this->dealRecordModel = new DealRecord();

        $line = 1;

        $frontUserWhere = [
            'deleted_at' => null,
        ];
        $frontUserWhere[] = ['phone', '<>', ''];

        //日志文件
        $this->logFile = 'user_phone.txt';

        $frontUserORM = DB::table('yh_front_user')->where($frontUserWhere);
        $frontUserORM->chunkById(100, function($list) use(&$line) {
            $userList = $list->toArray();

            foreach ($userList as $userInfo) {
                $userInfo = (array)$userInfo;

                // 行号+1并打印显示进度
                var_dump($line);
                $line++;

                if (!checkPhone($userInfo['phone'])) {
                    continue;
                }

                // 判断当前用户是否下单过
                $orderInfo = $this->orderModel->findDataWithField(['user_id' => $userInfo['id']]);
                if (!empty($orderInfo)) {
                    continue;
                }

                // 判断当前电话是否存在交易记录列表里
                $dealRecordInfo = $this->dealRecordModel->findDataWithField(['class_phone' => $userInfo['phone']]);
                if (!empty($orderInfo)) {
                    continue;
                }

                $this->log($userInfo['phone']);

            }


        });

    }

    // 记录日志
    protected function log($msg) {
        file_put_contents($this->logFile, trim($msg) . "\n", FILE_APPEND);
    }


}
