<?php

namespace App\Console\Commands;

use App\Models\DealRecord;
use App\Models\DealRecordGoods;
use App\Models\DealRecordUser;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class BatchUpdateDealRecordCourt extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'batch:update:dealRecord:court';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '批量更新法院状态';

    protected $logFile = '';

    protected $dealRecordModel;

    protected $dealRecordUserModel;

    protected $dealRecordGoodsModel;

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle() {
        $this->dealRecordModel = new DealRecord();
        $this->dealRecordUserModel = new DealRecordUser();
        $this->dealRecordGoodsModel = new DealRecordGoods();

        $line = 1;

        $dealRecordWhere = [
            'deleted_at' => null,
            'contain_court' => '',
        ];

        $dealRecordORM = DB::table('yh_deal_record')->where($dealRecordWhere);
        $dealRecordORM->chunkById(100, function($list) use(&$line) {
            $dealRecordList = $list->toArray();

            foreach ($dealRecordList as $dealRecordInfo) {
                $dealRecordInfo = (array)$dealRecordInfo;

                $updateData = [
                    'contain_court' => '',
                ];

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

                // 查询当前交易记录的学员信息
                $dealUserWhere = [];
                $dealUserWhere['deal_record_id'] = $dealRecordInfo['id'];
                $dealUserInfo = $this->dealRecordUserModel->selectDataWithField($dealUserWhere, ['*']);

                $allCourt = [];
                foreach ($dealUserInfo as $dealUser) {
                    $allCourt[] = $dealUser['is_court'];
                }

                $allCourt = array_unique($allCourt);
                if (!empty($allCourt)) {
                    $updateData['contain_court'] = implode('%%', $allCourt);
                }

                $updateRes = $this->dealRecordModel->updateData(['id' => $dealRecordInfo['id']], $updateData);
                if (false === $updateRes) {
                    var_dump('第' . $line . '行更新失败');
                }
            }
        });

    }

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


}
