<?php

namespace App\Http\Controllers;

use App\Process;
use App\Services\common\ExportService;
use App\Services\ProcessStatisticService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;

class ProcessStatisticController extends Controller
{
    public function index(Request $request){
        if(!Gate::allows('二次加工管理-查询')){ return redirect('denied');  }
        /** @var ProcessStatisticService $processStatistics */
        $processStatistics=app("ProcessStatisticService")->paginate($request->input());
        $owners=app("OwnerService")->getIntersectPermitting();
        $processMethods=app("ProcessMethodService")->getSelection();
        return view('process.statistic',['processStatistics'=>$processStatistics,'params'=>$request->input(),'owners'=>$owners,'processMethods'=>$processMethods]);
    }

    public function export(){
        if(!Gate::allows('二次加工管理-查询')){ return '没有权限';  }
        if (request("checkAllSign")){
            \request()->offsetUnset("checkAllSign");
            $processes = app('ProcessStatisticService')->get(\request()->input());
        }else $processes = app('ProcessStatisticService')->get(["process_id"=>\request("data")]);

        $row = ["任务号","接单人", "货主", "开始日期", "完成日期","创建日期", "单价", "预期数量", "完成数量", "收入合计",
            "完成时间(天)'", "总工时", "加工类型", "最高日产能", "最低日产能", "日均产能", "合计成本", "毛利润",
            "毛利率", "状态","加工备注","结算备注"];
        $list = [];

        foreach ($processes as $process){
            $list[] = [
                $process->process->code ?? "",
                $process->operatorLog->user->name ?? "",
                $process->process->owner->name ?? "",
                $process->started_at,
                $process->ended_at,
                $process->process->created_at ?? "",
                $process->process->unit_price ?? "",
                $process->process->amount ?? "",
                $process->process->completed_amount ?? "",
                $process->revenue,
                $process->duration_days,
                $process->duration_man_hours,
                $process->process->method->name ?? "",
                $process->top_capacity,
                $process->bottom_capacity,
                $process->average_capacity,
                $process->total_cost,
                $process->gross_profit,
                ($process->gross_profit_rate*100)."%",
                $process->process->status ?? "",
                $process->process->remark ?? "",
                $process->process->balance_remark ?? "",
            ];
        }
        return app(ExportService::class)->json($row,$list,"二次加工统计记录");
    }
}
