<?php

namespace app\command;

use app\common\Error;
use app\model\Orders as OrdersModel;
use app\server\Orders;
use app\server\Orders as ServerOrders;
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, " . date('Y-m-d H:i:s'));

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

            if (ServerOrders::isDaishiyong($order)) {
                $order = ServerOrders::syncFromThirdV2($order);
            }

            if ( $order &&
                ($order->os == 1 && $order->order_status != 3)
                || ($order->os == 2 && $order->order_status != 4)
                || ($order->os == 3 && $order->order_status != 1)
            ) {
                $this->output($output, "单号 {$order->sn} ： 状态已修改");
                continue;
            }

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

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

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

            $order->next_remind_time = $order->next_remind_time + 10 * 24 * 60 * 60;
            $order->save();
        }

        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
    {
        $startTime = strtotime(date('Y-m-d H:i:00'));
        $endTime = strtotime(date('Y-m-d H:i:59'));

        $list = OrdersModel::where('admin_id', '>', 0)->whereRaw(OrdersModel::AllOssStatusSql[1])
            ->whereBetween('next_remind_time', [$startTime, $endTime])
            ->select()->all();
        return $list;
    }
}
