<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\common\command;


use app\common\enum\OrderEnum;
use app\common\enum\OrderLogEnum;
use app\common\enum\PayEnum;
use app\common\enum\YesNoEnum;
use app\common\model\Order;
use app\common\model\OrderLog;
use app\common\service\ConfigService;
use app\api\logic\Order\OrderLogic;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\facade\Log;

/**
 * 订单自动完成
 * Class OrderFinish
 * @package app\common\command
 */
class OrderConfirm extends Command
{

    protected function configure()
    {
        $this->setName('order_confirm')
            ->setDescription('系统自动确认收货');
    }

    protected function execute(Input $input, Output $output)
    {
        $now = time();
        $ableAuto = ConfigService::get('transaction', 'automatically_confirm_receipt');
        $confirmTime = ConfigService::get('transaction', 'automatically_confirm_receipt_days') * 24 * 60 * 60;

        if ($ableAuto == YesNoEnum::NO) {
            return true;
        }

        $orders = Order::where([
            'order_status' => OrderEnum::STATUS_WAIT_RECEIVE,
            'pay_status' => PayEnum::ISPAID
        ])->whereRaw("create_time+$confirmTime < $now")->select();

        if (empty($orders)) {
            return true;
        }

        try {
            foreach ($orders as $order) {
                //更新订单状态
                Order::update([
                    'order_status' => OrderEnum::STATUS_FINISH,
                    'confirm_take_time' => time(),
                    'after_sale_deadline' => OrderLogic::getAfterSaleDeadline(), //售后截止时间
                ], ['id' => $order['id']]);

                //订单日志
                (new OrderLog())->record([
                    'type' => OrderLogEnum::TYPE_USER,
                    'channel' => OrderLogEnum::USER_CONFIRM_ORDER,
                    'order_id' => $order['id']
                ]);
            }
        } catch (\Exception $e) {
            Log::write('订单自动确认失败,失败原因:' . $e->getMessage());
        }
    }
}