<?php

namespace App\Http\Controllers;

use App\OrderPackage;
use App\Services\OrderPackageService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;

class WeighExceptedController extends Controller
{
    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function indexCreate(Request $request)
    {
        if(!Gate::allows('称重管理-查看异常')){ return redirect(url('/'));  }
        /** @var OrderPackageService */
        $weightExcepteds = app('OrderPackageService')->createExceptionPaginate($request->paginate ?? 50);
        return view('weight.weightExcepted.index',['weightExcepteds'=>$weightExcepteds,'view'=>'indexCreate']);
    }

    public function indexIssued(Request $request)
    {
        if(!Gate::allows('称重管理-查看异常')){ return redirect(url('/'));  }
        $weightExcepteds=app('OrderPackageService')->issueExceptionPaginate($request->paginate ?? 50);
        return view('weight.weightExcepted.index',['weightExcepteds'=>$weightExcepteds,'view'=>'indexIssued']);
    }

   public function export($type ,Request $request){
       if(!Gate::allows('称重管理-查看异常')){ return redirect(url('/'));  }
       if ($type == 'indexIssued'){
           if ($request->checkAllSign){
               $params = $request->input();
               unset($params['checkAllSign']);
               $sql = app('WeighExceptedService')->getIssuedExceptionSql($params);
           }else $sql=app('WeighExceptedService')->getIssuedExceptionSql(['id'=>$request->data]);
           $post = Http::post(config('go.export.url'),['type'=>'packageIssuedException','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',
           ]);
       }else{
           if ($request->checkAllSign){
               $params = $request->input();
               unset($params['checkAllSign']);
               $sql = app('WeighExceptedService')->getCreateExceptionSql($params);
           }else $sql=app('WeighExceptedService')->getCreateExceptionSql(['id'=>$request->data]);
           $post = Http::post(config('go.export.url'),['type'=>'packageCreateException','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',
           ]);
       }
   }
}
