<?php

namespace app\controller\Bus;

use app\controller\utils;
use app\model\Vinlicense;
use think\db\exception\DbException;
use think\facade\Db;

class BusBill extends utils
{
    /**
     * @throws DbException
     */
    public function DataStatistics($start_time, $end_time): \think\response\Json
    {
        $DateWithMess = [];
        $message = Vinlicense::column('EvcInfoNo');
        $date = $this->getDateFromRange($start_time, $end_time);
        $i = 0;
        foreach (array_unique($message) as $a) {
            $DateWithMess[$i]['序号'] = $i + 1;
//            $DateWithMess[$i]['EvcInfoNo'] = $a;
            $DateWithMess[$i]['车牌号'] = Vinlicense::where("EvcInfoNo", $a)->value("ParkNo");
            $DateWithMess[$i]['车号'] = Vinlicense::where("EvcInfoNo", $a)->value("SelfCode");
            $TotalCharge = 0;
            foreach ($date as $d) {
                $TotalPower = Db::table("charge_order_gongjiao")->where('EvcInfoNo', $a)->whereDay('charge_date', $d)->sum('TotalPower');
                $TotalCharge += $TotalPower;
                $DateWithMess[$i][$d] = round($TotalPower, 3);
            }

            $DateWithMess[$i]['充电电量(度)'] = round($TotalCharge, 3);
            $DateWithMess[$i]['充电电费(元)'] = round(Db::table("charge_order_gongjiao")->where('EvcInfoNo', $a)->whereBetweenTime('charge_date', $start_time, $end_time)->sum('ElecMoney'), 2);
            if ($DateWithMess[$i]['充电电量(度)'] != 0) {
                $DateWithMess[$i]['平均电费'] = round($DateWithMess[$i]['充电电费(元)'] / $DateWithMess[$i]['充电电量(度)'], 3);
            }
            $charge_pile_number = Db::table("charge_order_gongjiao")->where('EvcInfoNo', $a)->value("Equipment_number");
            $ddd = Db::table("charge_pile,charge_station")->where('charge_pile_number', $charge_pile_number)->where("charge_pile.charge_station_id=charge_station.charge_station_id")->value("charge_station_number");
            $DateWithMess[$i]['充电服务费单价(元)'] = $this->Fee($ddd, "o-wLg5DGWU_rYwfmp1-1Wck1lKGw")['ServiceFee'][0]['univalence'];
            $DateWithMess[$i]['充电服务费(元)'] = round(Db::table("charge_order_gongjiao")->where('EvcInfoNo', $a)->whereBetweenTime('charge_date', $start_time, $end_time)->sum('SeviceMoney'), 2);
            $DateWithMess[$i]['充电费用(元)'] = round(Db::table("charge_order_gongjiao")->where('EvcInfoNo', $a)->whereBetweenTime('charge_date', $start_time, $end_time)->sum('TotalMoney'), 2);
            $i += 1;
        }
        return $this->ResponseJson($DateWithMess, 200, "Request Success");
    }
}