<?php

namespace app\admin\command;

use think\console\Command;
use app\admin\model\Operation as OperationModel;
use app\admin\model\Recharge;
use app\admin\model\Withdraw;
use app\admin\model\Order;
use app\admin\model\User;
use think\console\Input;
use think\console\Output;

class Operation extends Command
{
    public function configure()
    {
        $this->setName('operation')
            ->setDescription('统计昨日的充值提现订单等数据（每天00:00 之后执行）');
    }

    public function execute(Input $input, Output $output)
    {
        echo ('开始执行统计充值提现订单等数据任务...');

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

    public function addYesterdayOperationData()
    {
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $data = [
            'date' => $yesterday,
            'recharge' => 0,
            'user_total_money' => 0,
        ];
        $start_time = strtotime($yesterday . ' 00:00:00');
        $end_time = strtotime($yesterday . ' 23:59:59');

        $data['recharge'] = Recharge::where('status', 1)
            ->where('operation_time', '>=', $start_time)
            ->where('operation_time', '<=', $end_time)
            ->sum('actual_received');

        $data['withdraw'] = Withdraw::where('status', 1)
            ->where('operation_time', '>=', $start_time)
            ->where('operation_time', '<=', $end_time)
            ->sum('actual_received');

        $data['balance_difference'] = $data['recharge'] - $data['withdraw'];
        $data['total_price'] = Order::where('create_time', '>=', $start_time)
            ->where('create_time', '<=', $end_time)
            ->whereIn('status', [1, 2, 3, 4, 5])->sum('amount');

        $data['user_total_money'] = User::sum('money');

        $info = OperationModel::where('date', $data['date'])->find();
        if ($info) {
            OperationModel::update($data, ['date' => $data['date']]);
        } else {
            OperationModel::create($data);
        }
        return true;
    }

}
