<?php

/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/21
 * Time: 下午2:12
 */

namespace App\Console\Commands;

use App\Libs\Pay\SandPay;
use App\Libs\PayHelper;
use App\Modules\Finance\Models\WithdrawCash;
use App\Modules\Finance\Services\AdvancedPaymentService;
use App\Modules\Finance\Services\BatchPaymentService;
use App\Modules\Finance\Services\LiquidatedStatService;
use App\Modules\Finance\Services\PaymentService;
use App\Modules\Finance\Services\WithdrawCashService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PaymentQueryTask extends Command
{

    /**
     * 执行命令   php artisan payment_query_task
     *
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'payment_query_task';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '支付通道打款结果查询';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        print_r("======支付通道打款结果查询 【任务执行开始】=====" . date("y-m-d H:i:s" . "\n"));
        Log::info("======支付通道打款结果查询 【任务执行开始】=====" . date("y-m-d H:i:s" . "\n"));

        $this->BatchPaymentQuery();
     
        Log::info("======支付通道余额结果查询 【任务执行结束】=====[" . date("y-m-d H:i:s" . "\n"));
        print_r("======支付通道余额结果查询 【任务执行结束】=====" . date("y-m-d H:i:s" . "\n"));
    }


    private function BatchPaymentQuery()
    {
        $pay_service = new SandPay;
        $payment_service = new AdvancedPaymentService;
        $payments = $payment_service->findPayingBatchPayments();
        foreach ($payments as $pay) {
            $result = $pay_service->queryOrder([
                'order_no'  => $pay->trade_no,
                'pay_time' => $pay->pay_time,
            ], $pay->is_company == 0);
            if ($result['result'] == 'success' && $result['content']->respCode == '0000' && $result['content']->resultFlag == 0) {
                print_r(($pay->id) . '---执行---start---' . "\n");
                $sand_serial = property_exists($result['content'],'sandSerial') ? $result['content']->sandSerial : '0000';
                $payment_service->updateBatchPaymentStatus($pay, AdvancedPaymentService::auto_success, 0, $result, $sand_serial);
                print_r(($pay->id) . '---执行---end---' . "\n");
            } else if ($result['result'] == 'failure') {
                $payment_service->updateBatchPaymentStatus($pay, AdvancedPaymentService::auto_failure, 0, $result);
            } else {
                $pay->pay_merchant_source_msg = json_encode($result);
                $pay->pay_merchant_source_result = '正在处理中';
                $pay->save();
            }
        }
    }
}