<?php

namespace App\Console\Commands;

use App\Managers\IMManager;
use App\Utils\ImUtil;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Throwable;

class SyncTencentIm extends Command
{
    protected $signature = 'sync:tencent-im';

    protected $description = '从腾讯云下im聊天记录的命令';

    protected $date;
    protected $compressFiles = [];
    protected $jsonFiles = [];

    protected $imManager;

    public function __construct(IMManager $imManager)
    {
        parent::__construct();
        $this->imManager = $imManager;
    }

    /**
     * 每天凌晨
     *
     *
     */
    public function handle()
    {
        try {
            $this->downloadFromTencent();
            $this->unCompressFile();
            $this->readFromFile();
        } catch (Throwable $exception) {
            throw $exception;
        }
    }

    public function downloadFromTencent()
    {
        $im = new ImUtil();

        // 昨天的数据
        $endTime = strtotime(date('Ymd'));
        $startTime = $endTime - 86400;

        for ($step = 0; $step < 24; $step++) {
            $timeString = date('Ymd', $startTime) . sprintf('%02d', $step);
            $message = $im->downloadMessages($timeString);
            $message = json_decode($message);

            if (!$message->ErrorCode) {
                $i = 0;
                foreach ($message->File as $file) {
                    $filePath = storage_path("app/{$timeString}_{$i}_" . uniqid() . '.gz');
                    file_put_contents($filePath, '');
                    $url = $file->URL;
                    $client = new Client();
                    $response = $client->request('GET', $url, ['stream' => true]);

                    $body = $response->getBody();
                    while (!$body->eof()) {
                        file_put_contents($filePath, $body->read(1024), FILE_APPEND);
                    }

                    $this->compressFiles[$filePath] = $timeString;
                    $i++;
                }
            }
        }
    }

    public function unCompressFile()
    {
        $i = 0;
        foreach ($this->compressFiles as $compressFile => $timeString) {
            $jsonPath = storage_path("app/{$timeString}_{$i}_" . uniqid() . '.json');

            file_put_contents($jsonPath, '');

            $cfp = gzopen($compressFile, 'rb');

            while (!gzeof($cfp)) {
                file_put_contents($jsonPath, gzread($cfp, 1024), FILE_APPEND);
            }
            gzclose($cfp);
            $this->jsonFiles[$jsonPath] = $timeString;
            $i++;
        }
    }

    public function readFromFile()
    {
        foreach ($this->jsonFiles as $jsonFile => $timeString) {
            $fp = fopen($jsonFile, 'r');

            while (!feof($fp)) {
                $content = fgets($fp);

                $message = json_decode($content, true);

                if ($message) {
                    $fromAccount = $message['From_Account'];
                    $toAccount = $message['To_Account'];
                    $msgRandom = $message['MsgRandom'];
                    $msgTime = $message['MsgTimestamp'];
                    $msgSeq = $message['MsgSeq'];

                    $this->imManager->createUserMessageByAccount(
                        $fromAccount,
                        $fromAccount,
                        $toAccount,
                        $msgTime,
                        $msgRandom,
                        $msgSeq,
                        $message
                    );

                    $this->imManager->createUserMessageByAccount(
                        $toAccount,
                        $fromAccount,
                        $toAccount,
                        $msgTime,
                        $msgRandom,
                        $msgSeq,
                        $message
                    );
                }
            }
        }
    }
}
