<?php

namespace App\Console\Commands;

use App\OwnerAreaReport;
use App\Services\LogService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'create owner bill report';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 1号生成账单确认，确认金额由人工填写 原始金额默认为：即时账单月记录金额+仓储计费与面积计算金额
     *
     * @return void
     */
    public function handle()
    {
        $year = (int)date('Y');
        $month = (int)date('m');
        if ($month == 1){
            $year--;
            $lastMonth = '12';
        }else $lastMonth = ($month-1) < 10 ? "0".($month-1) : ($month-1);
        $sql = "SELECT owner_id,SUM(work_fee)+SUM(logistic_fee) AS total FROM owner_fee_details WHERE worked_at LIKE ? AND (type = '发货' AND logistic_fee IS NOT NULL AND work_fee IS NOT NULL) OR (type <> '发货' AND work_fee IS NOT NULL)  GROUP BY owner_id";
        $billDetails = DB::select(DB::raw($sql),[$year."-".$lastMonth."%"]);

        $areas = OwnerAreaReport::query()->with("ownerStoragePriceModel")->where("counting_month","like",$year."-".$lastMonth."%")->get();
        $map = [];
        foreach($areas as $area){
            if (isset($map[$area->owner_id."_".$area->counting_month])){
                if (!$area->ownerStoragePriceModel)continue;
                $map[$area->owner_id."_".$area->counting_month] += app('OwnerStoragePriceModelService')
                    ->calculationAmount($area->ownerStoragePriceModel,$area->accounting_area,$area->owner_id,$area->counting_month);
            }else{
                if (!$area->ownerStoragePriceModel)continue;
                $map[$area->owner_id."_".$area->counting_month] = app('OwnerStoragePriceModelService')
                    ->calculationAmount($area->ownerStoragePriceModel,$area->accounting_area,$area->owner_id,$area->counting_month);
            }
        }

        $chunks = array_chunk($billDetails,50);
        foreach ($chunks as $bills){
            $date = date('Y-m-d H:i:s');
            $createOwnerBillReport = [];
            foreach ($bills as $bill){
                $key = $bill->owner_id."_".$year."-".$lastMonth;
                $total = $bill->total;
                if (isset($map[$key]))$total += $map[$key];
                $createOwnerBillReport[] = [
                    "owner_id"          => $bill->owner_id,       //项目ID
                    "counting_month"    => $year."-".$lastMonth."-01", //结算月
                    "initial_fee"       => $total,    //原始账单金额
                    "created_at"        => $date,
                ];
            }
            LogService::log(__METHOD__,"客户管理-生成确认账单",json_encode($createOwnerBillReport));
            DB::table("owner_bill_reports")->insert($createOwnerBillReport);
        }
    }
}
