<?php

namespace App\Http\Controllers;

use App\Exports\Export;
use App\WaybillFinancialSnapshot;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;
use Maatwebsite\Excel\Facades\Excel;

class WaybillFinancialSnapshotsController extends Controller
{
    public function conditionQuery(Request $request,$waybillFinancialSnapshots){
        if ($request->input('created_at_start')){
            $created_at_start=$request->input('created_at_start')." 00:00:00";
            $waybillFinancialSnapshots=$waybillFinancialSnapshots->where('created_at','>=',$created_at_start);
        }
        if ($request->input('created_at_end')){
            $created_at_end=$request->input('created_at_end')." 23:59:59";
            $waybillFinancialSnapshots=$waybillFinancialSnapshots->where('created_at','<=',$created_at_end);
        }
        $waybillFinancialSnapshots=$waybillFinancialSnapshots->paginate(50);
        return $waybillFinancialSnapshots;
    }
    public function index(Request $request)
    {
        if(!Gate::allows('财务报表-查询')){ return redirect(url('/'));  }
        $waybillFinancialSnapshots=WaybillFinancialSnapshot::query()->orderBy('id', 'DESC');
        $type='';
        if ($request->type=='ZF'){
            $waybillFinancialSnapshots=$waybillFinancialSnapshots->where('json_content','like','%直发车%');
            $type='ZF';
        }
        if ($request->type=='ZX'){
            $waybillFinancialSnapshots=$waybillFinancialSnapshots->where('json_content','like','%专线%');
            $type='ZX';
        }
        $waybillFinancialSnapshots=$this->conditionQuery($request,$waybillFinancialSnapshots);
        return view('transport.waybill.waybillFinancialSnapshot.index',['waybillFinancialSnapshots'=>$waybillFinancialSnapshots,'filterData'=>$request->input(),'type'=>$type]);
    }
    public function export(Request $request){
        if(!Gate::allows('财务报表-查询')){ return '没有权限';  }
        if ($request->checkAllSign){
            $param = $request->input();
            unset($param['checkAllSign']);
            $sql = app('WaybillFinancialService')->getSql($param);
        }else{
            $sql = app('WaybillFinancialService')->getSql(['waybill_id'=>$request->data]);
        }
        $post = Http::post(config('go.export.url'),['type'=>'waybillFinancial','sql'=>$sql]);
        if ($post->status() == 500){
            throw new Exception($post->header("Msg"));
        }
        return response($post,200, [
            "Content-type"=>"application/octet-stream",
            "Content-Disposition"=>"attachment; filename=财务报表-".date('ymdHis').'.xlsx',
        ]);
    }
}
