<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\DischargeTask;
use App\Facilitator;
use App\Filters\FacilitatorExternalFilters;
use App\Services\common\ExportService;
use App\Services\DischargeTaskService;
use App\Services\FacilitatorService;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class FacilitatorExternalController extends Controller
{
    // 卸货队可访问的页面
    use AsyncResponse;

    // 查询页面
    public function index(Request $request,$id)
    {
        $facilitator =  Facilitator::query()->fromQuery('select * from facilitators where MD5(id) = ?',[$id])->first();
        if(!$facilitator)return redirect('exception.404');

        $request['id'] = $id;
        $filters = new FacilitatorExternalFilters($request);

        $facilitatorStatements = DischargeTask::query()
            ->selectRaw('sum( discharge_tasks.expenditure_total_cost ) total_cost,' . ' count( 1 ) sum , ' . ' facilitators.name facilitators_name,' . ' facilitators.id id,' . " DATE_FORMAT( discharge_tasks.created_at, '%Y-%m' ) months ")
            ->leftJoin('facilitators', 'discharge_tasks.facilitator_id', '=', 'facilitators.id')
            ->filter($filters)
            ->groupBy('months', 'facilitator_id')
            ->orderByDesc('months')
            ->paginate($request['paginate'] ?? 50);

        return view('personnel.discharge.facilitator.external.index',compact('facilitatorStatements','id'));
    }

    // 下载
    public function export(Request $request,$id)
    {
        $request['id'] = $id;
        $filters = new FacilitatorExternalFilters($request);

        /** @var Collection $facilitatorStatements */
        $facilitatorStatements = DischargeTask::query()
            ->filter($filters)
            ->with('facilitator')
            ->select(['id', 'facilitator_id', 'expenditure_amount', 'expenditure_unit', 'expenditure_unit_price', 'expenditure_total_cost', 'expenditure_remark', 'created_at'])
            ->whereNotNull('facilitator_id')
            ->where('facilitator_id', '!=', '0')
            ->orderByDesc('id')->get();

        $row = ['日期', '装卸队', '数量', '单位', '单价', '总金额合计'];
        $json = app('DischargeTaskService')->getFacilitatorStatementsJson($facilitatorStatements);

        return app(ExportService::class)->json($row, $json, "卸货结算报表");
    }

}
