<?php

declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

use think\facade\Db;

class CheckPaymentError extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('app\command\checkpaymenterror')
            ->setDescription('the app\command\checkpaymenterror command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 取得未完付款的訂單
        $orders = Db::name('order_info')
            ->alias('oi')
            ->leftjoin('payment p', 'oi.pay_id=p.pay_id')
            ->field('oi.*,p.pay_code,p.pay_desc')
            ->where('oi.order_status', '=', 1)
            ->where('oi.pay_status', '<>', 2)
            ->where('oi.pay_id', '>', 0)
            ->select();

        print_r($orders);

        // 根據付款方式檢查時間是否過期
        foreach ($orders as $key => $val) {
            $is_expire = false;
            switch ($val['pay_code']) {
                case 'eccredit':
                    if ($val['add_time'] + 3600 < time()) {
                        $is_expire = true;
                        break;
                    }
                    break;
                case 'ecatm':
                    if ($val['add_time'] + 86400 < time()) {
                        $is_expire = true;
                        break;
                    }
                    break;
                case 'eccvs':
                    if ($val['add_time'] + 86400 < time()) {
                        $is_expire = true;
                        break;
                    }
                    break;
                default:
                    break;
            }
            if($is_expire){
                $data['order_status'] = 3;
                $data['pay_status'] = 3;
                Db::name('order_info')
                    ->where('order_id', $val['order_id'])
                    ->update($data);

                //更新訂單操縱紀錄
                $order_action = [
                    'order_id' => $val['order_id'],
                    'action_user' => '綠界科技',
                    'order_status' => $val['order_status'],
                    'shipping_status' => $val['shipping_status'],
                    'pay_status' => $val['pay_status'],
                    'action_note' => $val['pay_desc'].': '.$val['pay_code'].'.付款逾時, 訂單無效',
                    'log_time' => time(),
                ];
                Db::name('order_action')->insert($order_action);
            }
        }

        // 指令输出
        $output->writeln('檢查支付過期');
    }
}
