<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\Finance\Services\WithdrawCashService;
use App\Modules\OfficialAccount\Models\DistributionSelfDefineConfig;
use App\Modules\Finance\Services\FinancialStatService;

class AutoWithdrawCash extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'AutoWithdrawCash';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动申请提现';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->start();
    }

    public function start(){
    	\Log::info('auto_withdraw_cash_start');
    	// 获取自动提现的渠道列表
    	$distributionSelfDefineConfigs = DistributionSelfDefineConfig::getDistributionsByType('auto_withdraw_cash');
    	foreach($distributionSelfDefineConfigs as $distributionSelfDefineConfig){
    		try{
    			$distribution_channel_id = $distributionSelfDefineConfig->distribution_channel_id;
    			\Log::info('auto_withdraw_start:'.$distribution_channel_id);
    			$financialStat = FinancialStatService::getFinancialStatSingle($distribution_channel_id);
    			\Log::info($financialStat);
    			if($financialStat['enable_withdrawal_amount'] >= 100){
    				$amount = intval(($financialStat['enable_withdrawal_amount']*100))/100;
    				\Log::info('real_amount:'.$amount.' orgin_amount:'.$financialStat['enable_withdrawal_amount']);
    				$res = WithdrawCashService::auto_add_withdrawCash($distribution_channel_id,$amount,'系统自动申请提现');
    				\Log::info('auto_withdraw:'.json_encode($res,JSON_UNESCAPED_UNICODE));
    			}else{
    				\Log::info('auto_withdraw_not_enough:'.$distribution_channel_id.' amount:'.$financialStat['enable_withdrawal_amount']);
    			}
    		}catch(Exception $e){
    			\Log::info('auto_withdraw_cash_ept:'.$e->getMessage());
    		}
    		
    	}
    	\Log::info('auto_withdraw_cash_end');
    }
}
