<?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;
use Overtrue\Pinyin\Pinyin;

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

    /**
     * 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_order_no' => '',
        ];

        $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_order_no' => '',
                ];

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

                // 查询当前交易记录的抵扣信息
                $dealGoodsWhere = [];
                $dealGoodsWhere['deal_record_id'] = $dealRecordInfo['id'];
                $dealGoodsInfo = $this->dealRecordGoodsModel->selectDataWithField($dealGoodsWhere, ['*']);

                $allOrderNo = [];
                foreach ($dealGoodsInfo as $dealGoods) {
                    if ($dealGoods['order_no'] === '') {
                        // 重新生成新的订单号
                        $newOrderNo = $this->generateOrderNo($dealRecordInfo['user_name'], $dealRecordInfo['created_at']);

                        // 更新
                        $updateRes = $this->dealRecordGoodsModel->updateData(['id' => $dealGoods['id']], ['order_no' => $newOrderNo]);
                        if (false === $updateRes) {
                            var_dump('第' . $line . '行抵扣信息更新失败');
                            continue;
                        }

                        $allOrderNo[] = $newOrderNo;
                    } else {
                        $allOrderNo[] = $dealGoods['order_no'];
                    }
                }

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

                $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);
    }

    protected function generateOrderNo($userName, $createdTime) {
        $userNamePinyin = Pinyin::abbr($userName)->join('');

        $cleaned = str_replace(['-', ' ', ':'], '', $createdTime);

        $cleaned .= mt_rand(1000000000, 2000000000);

        return $userNamePinyin . $cleaned;
    }

}
