<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Aldzn\UserTotalPay;
use App\Aldzn\UserCoupon;
use App\Aldzn\UserRefund;
use App\Aldzn\UserForbid;

class SearchRefund extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'search:refund {channel : 渠道ID} {ouid : 账号ID}';

    /**
     * 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()
    {
        $channel = $this->argument('channel');
        $ouid = $this->argument('ouid');
        $refund = UserRefund::where('channel_id', $channel)->where("ouid", $ouid)->first(['id']);
        if (!empty($refund)) {
            $this->line("历史数据");
            $this->info(json_encode($refund, JSON_PRETTY_PRINT));
            return;
        }
        $payRow = UserTotalPay::where("channel_id", $channel)->where("ouid", $ouid)->first();
        $this->line($channel ." -> " . $ouid);
        $totalPay = UserTotalPay::where("channel_id", $channel)->where("ouid", $ouid)->sum('total_payamount');
        $coupon = UserCoupon::where("channel_id", $channel)->where("ouid", $ouid)->sum('coupon');
        $unblock = UserForbid::where("channel", $channel)->where("accid", $ouid)->value('unblock');
        $isBlock = 0;
        if ($unblock === 0) {
            $isBlock = 1;
        }
        
        $oCoin = 0;
        if ($coupon > 0) {
            $oCoin = ceil($coupon / 10);
        }
        if ($oCoin > $totalPay) {
            $oCoin = ceil($totalPay);
        }
        
        if ($isBlock == 1) {
            $oCoin = 0;
        }
        
        $userRefund = new UserRefund();
        $userRefund->platform_id = $payRow['platform_id'] ?? '';
        $userRefund->channel_id = $channel;
        $userRefund->ouid = $ouid;
        $userRefund->coupon = $coupon;
        $userRefund->total_pay = $totalPay;
        $userRefund->is_block = $isBlock;
        $userRefund->o_coin = $oCoin;
        $userRefund->save();
        $this->info(json_encode($userRefund, JSON_PRETTY_PRINT));
    }
}
