<?php

namespace App\Http\Controllers;

use App\Process;
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")->getSelection();
        $processMethods=app("ProcessMethodService")->getSelection();
        return view('process.statistic',['processStatistics'=>$processStatistics,'params'=>$request->input(),'owners'=>$owners,'processMethods'=>$processMethods]);
    }

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

        $row = ["任务号", "货主", "开始日期", "完成日期","创建日期", "单价", "预期数量", "完成数量", "收入合计",
            "完成时间(天)'", "总工时", "加工类型", "最高日产能", "最低日产能", "日均产能", "合计成本", "毛利润",
            "毛利率", "状态","加工备注","结算备注"];
        $column = ["process_code", "owner_name", "started_at", "ended_at","process_created_at", "process_unit_price", "process_amount", "process_completed_amount", "revenue",
		"duration_days", "duration_man_hours", "process_method_name", "top_capacity", "bottom_capacity",
		"average_capacity", "total_cost", "gross_profit", "gross_profit_rate", "process_status", "process_remark", "process_balance_remark"];
        $rule = ["gross_profit_rate"=> "percent", "started_at"=>"mysqlDate", "ended_at"=>"mysqlDate", "process_created_at"=>"mysqlDate"];
        $post = Http::post(config('go.export.url'),['type'=>'unify','sql'=>$sql, 'connection'=>'mysql',
            'row'=>json_encode($row,JSON_UNESCAPED_UNICODE), 'column'=>json_encode($column), 'rule'=>json_encode($rule)]);
        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',
        ]);
    }
}
