<?php

namespace app\command;

use app\model\Admins;
use app\model\LiveRoomWorks;
use app\model\Orders;
use app\model\Sales;
use app\model\Works;
use Carbon\Carbon;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use think\facade\Db;

class LiveRoomWorkCommand extends Command
{

    protected static $defaultName = 'LiveRoomWorkCommand';
    protected static $defaultDescription = '直播间排班表处理';

    protected function configure()
    {
        $this
            ->setName('LiveRoomWorkCommand')
            ->setDescription('直播间排班表处理')
            ->setDefinition(
                new InputDefinition(array(
                    new InputOption('room_id', 'd', InputOption::VALUE_REQUIRED),
                ))
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln('LiveRoomWorkService start');
        // 找出直播已结束的排班
        $now = Carbon::now()->toDateTimeString();
        $endRooms = LiveRoomWorks::where([['end', '<', $now]])->whereNull('orders')->select();

        // 统计排班数据
        foreach ($endRooms as $endRoom) {
            $orderSum = Orders::where('live_room_work_id', $endRoom->id)
                ->fieldRaw('count(1) as order_num')
                ->fieldRaw('sum(total_price) as total_price')
                ->find();
            LiveRoomWorks::where('id', $endRoom->id)->update(['orders' => $orderSum->order_num ?? 0, 'total' => $orderSum->total_price ?? 0]);
        }

        $output->writeln('LiveRoomWorkService end');
        return 1;
    }
}