<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Operation;
use App\Models\FundsRecord;
use App\Models\Order;
use App\Models\Wallet;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class OperationData extends Command
{
    /**
     * 命令名称和签名
     *
     * @var string
     */
    protected $signature = 'operation:data';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '统计昨日的充值提现订单等数据（每天00:00 之后执行）';
    /**
     * 执行命令
     *
     * @return int
     */
    public function handle()
    {
        $this->info('开始执行统计充值提现订单等数据任务...');

        $this->addYesterdayOperationData();
        $this->info('结束执行统计充值提现订单等数据任务');
    }

    public function addYesterdayOperationData()
    {
        $yesterday = Carbon::yesterday()->format('Y-m-d');
        $data = [
            'date' => $yesterday,
            'recharge' => 0,
            'user_total_money' => 0,
        ];
        $data['recharge'] = FundsRecord::whereIn('change_type', ['充值','人工充值','三方充值'])
            ->where('created_at', '>=', "{$yesterday} 00:00:00")
            ->where('created_at', '<=', "{$yesterday} 23:59:59")
            ->sum('amount');

        $data['withdraw'] = FundsRecord::whereIn('change_type', ['提现','三方提现'])
            ->where('created_at', '>=', "{$yesterday} 00:00:00")
            ->where('created_at', '<=', "{$yesterday} 23:59:59")
            ->sum('amount');

        $data['balance_difference'] = $data['recharge'] - $data['withdraw'];
        $data['total_price'] = Order::where('create_time', '>=', strtotime($yesterday.' 00:00:00'))
            ->where('create_time', '<=',  strtotime($yesterday.' 23:59:59'))
            ->where('status', 1)
            ->where('pay_status', 1)
            ->where('return_status', 0)
            ->sum('amount');

        $data['user_total_money'] = Wallet::query()->sum('available_balance');

        $info = Operation::where('date', $data['date'])->first();
        
        if (!$info) {
            DB::table('bot_operation')->insert($data);
        } else {
            Operation::where('date', $data['date'])->update($data);
        }
        return true;
    }

}
