<?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 BatchGetDealRecordOrderNo extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'batch:get: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() {
        $dealRecordModel = new DealRecord();
        $dealRecordUserModel = new DealRecordUser();
        $dealRecordGoodsModel = new DealRecordGoods();

        $line = 1;

        $fileName = '217.txt';

        // 打开文件
        $fp = fopen($fileName, "r");

        $line = 1;

        while(!feof($fp)) {
            var_dump($line);

            $row = fgets($fp);
            $row = str_replace("\n", '', trim($row));
            $data = explode("	", $row);

            if (empty($data)) {
                break;
            }

            // 先获取学员信息
            $dealRecordUserInfo = $dealRecordUserModel->selectDataWithField(['deal_record_no' => $data[0]], ['*']);
            if (empty($dealRecordUserInfo)) {
                $this->info($line . '行: 单号不存在');
                $line++;
                continue;
            }

            foreach ($dealRecordUserInfo as $userInfo) {
                // 匹配交易记录商品信息
                $dealRecordGoodsInfo = $dealRecordGoodsModel->findDataWithField(['deal_record_user_id' => $userInfo['id'], 'goods_name' => $data[1]]);
                if (empty($dealRecordGoodsInfo)) {
                    continue;
                }

                var_dump($dealRecordGoodsInfo['order_no']);
                $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;
    }

}
