<?php

namespace App\Http\Controllers;

use App\Services\OrderIssuePerformanceService;
use App\Services\OrderIssueWorkLoadService;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;

class OrderIssuePerformanceController extends Controller
{

    public function __construct()
    {
        app()->singleton('OrderIssueWorkLoadService', OrderIssueWorkLoadService::class);
        app()->singleton('service', OrderIssuePerformanceService::class);
    }

    public function index(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-绩效统计')) {
            return redirect(url('/'));
        }
        /** @var OrderIssuePerformanceService $service */
        $service = app('OrderIssuePerformanceService');
        $performance = $service->paginate($request->all());
        $options = ['timeFrame' => $request->input('timeFrame'), 'create_start' => $request->input('create_start') ?? '', 'create_end' => $request->input('create_end') ?? ''];
        return view('order.issue.performance', compact('performance', 'options'));
    }

    public function export(Request $request)
    {
        /** @var OrderIssuePerformanceService  $orderIssuePerformanceService */
        $orderIssuePerformanceService = app(OrderIssuePerformanceService::class);
        $sql = $orderIssuePerformanceService->getSql($request->all());
        $row = ['客服','客户','创建数','处理数','完结数','总数'];
        $column = ['userName','ownerName','created','process','end','sumNumber'];
        $post = Http::post(config('go.export.url'),['type'=>'unify','sql'=>$sql, 'connection'=>'mysql',
            'row'=>json_encode($row,JSON_UNESCAPED_UNICODE), 'column'=>json_encode($column)]);
        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',
        ]);
    }

    public function workLoadPage(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-工作量')) {
            return redirect(url('/'));
        }
        /** @var OrderIssueWorkLoadService $workLoadService */
        $workLoadService = app('OrderIssueWorkLoadService');
        $workLoads = $workLoadService->paginate($request->all());
        $users = $workLoadService->getUsers();
        $owners = $workLoadService->getOwners();
        $options =$workLoadService->getOptions($request->all());
        return view('order/issue/workload', compact('workLoads', 'owners', 'users','options'));
    }

    public function exportWorkLoad(Request $request)
    {
        $workLoadService = app('OrderIssueWorkLoadService');
        return $workLoadService->exportWorkLoad($request->all());
    }
}
