<?php

namespace App\Console\Commands;

use App\Jobs\ProcurementCheckConfirmInform;
use App\ProcurementCheckSheet;
use App\ProcurementTotalBill;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

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

    /**
     * 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 int
     */
    public function handle()
    {
        $date=$this->getDate();
        $procurementCheckSheets=ProcurementCheckSheet::query()
            ->selectRaw('procurements.supplier_id supplier_id,procurement_check_sheets.created_at created_at,procurement_check_sheets.status status,SUM(procurement_check_sheets.account_payable) account_payable')
            ->leftJoin('procurement_deliveries','procurement_check_sheets.procurement_delivery_id','procurement_deliveries.id')
            ->leftJoin('procurements','procurement_deliveries.procurement_id','procurements.id')
            ->where('procurement_check_sheets.created_at','like',$date."%")
            ->groupBy('supplier_id')
            ->get();
        $totalBill=[];
        foreach ($procurementCheckSheets as $procurementCheckSheet){
            if ($procurementCheckSheet->account_payable<1) continue;
            $totalBill[]=[
                'counting_month'=>$date.'-01',
                'supplier_id'=>$procurementCheckSheet->supplier_id,
                'total_payable'=>$procurementCheckSheet->account_payable,
                'status'=>$procurementCheckSheet->status,
                'created_at'=>date('Y-m-01 00:00:00'),
                'updated_at'=>date('Y-m-01 00:00:00'),
            ];
        }
        if (count($totalBill)>0){
            DB::table("procurement_total_bills")->insert($totalBill);
            app('LogService')->log(__METHOD__,"采购管理-生成月账单报表",json_encode($totalBill));
            $procurementTotalBills=ProcurementTotalBill::query()
                ->withCount('procurement')
                ->with(['supplier.user.userDetail'])
                ->where('counting_month',$date.'-01')
                ->get();
            dispatch(new ProcurementCheckConfirmInform($procurementTotalBills));
        }
    }

    private function getDate(){//获取当前日期的上月 月份
        $month = (int)date('m');
        $year = (int)date('Y');
        if ($month == 1){
            $year--;
            $lastMonth = '12';
        }else{
            $lastMonth = ($month-1) < 10 ? "0".($month-1) : ($month-1);
        }
        $date=$year."-".$lastMonth;
        return $date;
    }
}
