<?php


namespace App\Services;


use App\Http\helper\NumConfig;
use Illuminate\Support\Facades\DB;

class Stock
{
    public function todayRes($where)
    {
        $date = [];
        for ($h = 1; $h <= 24; $h++) {
            if ($h < 10) {
                $h = (string)'0' . $h;
            }
            $date[] = $h;
        }

        $query = DB::table('agent.dbo.stock_change')
            ->where($where)
            ->selectRaw("substring(CONVERT(varchar(120), mydate, 120),12,2) mydate,sum(stock) stock")
            ->groupBy(DB::raw('substring(CONVERT(varchar(120), mydate, 120),12,2)'))
            ->pluck('stock', 'mydate')->toArray();

        $list = [];

        $start_time = $where[1][2] ?? '';

        if (!empty($start_time)) {
            $start_time = strtotime($start_time);
        }

        $now = time();
        foreach ($date as $key => $val) {

            if ($now > $start_time && !empty($start_time)) {
                $list[] = isset($query[$val]) ? number_float($query[$val] / NumConfig::NUM_VALUE) : 0;
            } else {
                $list[] = isset($query[$val]) ? number_float($query[$val] / NumConfig::NUM_VALUE) : number_float(end($query) / NumConfig::NUM_VALUE);
            }


        }

        return compact('list', 'date');
    }


    function allDay($start_time, $end_time, $where = [])
    {
        $date = $this->getDateFromRange($start_time, $end_time);

        $query = DB::connection('read')->table('agent.dbo.stock_change')
            ->where('identifier', 1)
            ->where($where)
            ->where('mydate', '>=', $start_time)
            ->where('mydate', '<', $end_time)
            ->selectRaw('sum(stock) as stock,CONVERT(varchar(100),mydate,23) mydate')
            ->groupBy(DB::raw('CONVERT(varchar(100),mydate,23)'))
            ->pluck('stock', 'mydate')->toArray();

        $list = [];
        foreach ($date as $key => $val) {

            $list[] = isset($query[$val]) ? number_float($query[$val] / 100) : number_float(end($query) / NumConfig::NUM_VALUE);
//            foreach ($query as &$value) {
//                $list[] = $value->mydate == $val ? number_float($value->stock / 100) : 0;
//            }
        }

        return compact('list', 'date');
    }

    function getDateFromRange($startdate, $enddate)
    {
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);  // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400; // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('Y-m-d', $stimestamp + (86400 * $i));
        }
        return $date;
    }
}
