<?php

namespace App\Http\Controllers;

use App\Exports\Export;
use App\Services\WaveService;
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 WaveController extends Controller
{

    public function __construct()
    {
        app()->bind("WaveService",WaveService::class);
    }

    // 主页
    public function index(Request $request){
        if(!Gate::allows('订单管理-波次-查询')){ return redirect(url('/'));  }
        $waveService = app("WaveService");
        $waves = $waveService->queryWave($request);
        $param =  $waveService->getPageParameter($request);
        $search = $waveService->getSearchCondition($request);
        foreach ($waves as $index=>$wave){
            $wave->pickerPrint = '';
            $wave->pickerPrintTime = '';
            $wave->expressPrinting = '';
            $wave->expressPrintTime = '';
            if(!is_null($wave->userdefine1)){
                $str = $wave->userdefine1;
                $index = strpos($str,'-PK');
                $wave->pickerPrint = substr($str,0,$index);
                $wave->pickerPrintTime = substr($str,$index+3);
            }
            if(!is_null($wave->userdefine2)){
                $str = $wave->userdefine2;
                if(strpos($str,'-EX')){
                    $index = strpos($str,'-EX');
                    $wave->expressPrinting = substr($str,0,$index);
                    $wave->expressPrintTime = substr($str,$index+3);
                }else if(strpos($str,'-Auto')){
                    $index = strpos($str,'-Auto');
                    $wave->expressPrinting = substr($str,0,$index);
                    $wave->expressPrintTime = substr($str,$index+5);
                }
            }
        }
        return view("order/wave/search",compact('waves','param','search'));
    }

    public function cancelPrinting(Request $request){
        if(!Gate::allows('订单管理-波次-重置打印')){ return ['success'=>false,'fail_info'=>'没有权限，请联系管理员'];  }
        $waveService = app("WaveService");
        $ids = $request->input("ids");
        /** @var WaveService $waveService */
        $meg = $waveService->cancelPrint($ids);
        if($meg['fail_info']){
            return $meg;
        }
        app('LogService')->log(__METHOD__,'重置打印标记'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return $meg;
    }

    public function exportExcelOnParams(Request $request){
        $sql = app("WaveService")->getSql($request);
        $post = Http::post(config('go.export.url'),['type'=>'orderWave','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',
        ]);
    }

}
