<?php

namespace app\command;

use app\common\Error;
use app\model\Orders as OrdersModel;
use app\server\Orders;
use support\Redis;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;


class NotUsedOrderSms extends Command
{
    protected static $defaultName = 'sms:notusedorder';
    protected static $defaultDescription = '给带使用订单发送短信。';

    /**
     * @return void
     */
    protected function configure()
    {
        // $this->addArgument('name', InputArgument::OPTIONAL, 'Name description');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->output($output, self::$defaultName . " started");

        $orders = $this->orders();
        $total = count($orders);

        $this->output($output, "got {$total} orders");

        if (1 > $total) {
            return self::SUCCESS;
        }

        foreach($orders as $order) {
            if (empty($order->mobile)) {
                continue;
            }

            $result = Orders::reminderOrders($order);
            $text = '已发送提醒。';

            if (Error::is($result)) {
                $text = '发送短信失败,' . $result['message'] ?? '';
            }

            $this->output($output, "单号 {$order->sn} : {$text}");
        }

        return self::SUCCESS;
    }

    private function output(OutputInterface $output, string $message) 
    {
        $output->writeln(sprintf('{"time":"%s", "message":"%s"}', date('Y-m-d H:i:s'), $message));
    }

    /**
     * @return OrdersModel[]
     */
    private function orders(): array
    {
        $list = OrdersModel::where('admin_id', '>', 0)->whereRaw(OrdersModel::AllOssStatusSql[1])->select()->all();
        return $list;
    }
}