<?php

namespace App\Console\Commands;

use App\Order;
use App\OrderBin;
use App\OrderPackageCountingRecord;
use App\Services\BatchService;
use App\Services\common\BatchUpdateService;
use App\Services\DocWaveHeaderService;
use App\Services\LogService;
use App\ValueStore;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class CreateWeightStatistic extends Command
{
    protected $signature = 'create:weightStatistic';

    protected $description = 'every day create weight statistic data';

    public function handle()
    {
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $sql = <<<sql
SELECT DATE_FORMAT(order_packages.created_at,'%Y-%m-%d') date,
SUM(CASE WHEN order_packages.weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
COUNT(1) total FROM order_packages LEFT JOIN orders ON order_packages.order_id=orders.id WHERE orders.wms_status != '订单取消' 
AND order_packages.created_at BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' GROUP BY date
sql;
        $result = DB::selectOne(DB::raw($sql));
        if (!$result)$obj = [
            "targeted_at"    => $yesterday,
            "un_weigh_count" => 0,
            "total_count"    => 0
        ]; else $obj = [
            "targeted_at"    => $result->date,
            "un_weigh_count" => $result->count,
            "total_count"    => $result->total,
        ];
        /** @var \stdClass $model */
        $model = OrderPackageCountingRecord::query()->create($obj);
        Cache::put("weight.".$yesterday,[
            "date"=>$yesterday,
            "total"=>$model->total_count,
            "count"=>$model->un_weigh_count,
            "value"=>$model->total_count ? intval(($model->un_weigh_count/$model->total_count)*100) : 0
        ]);
    }
}
