<?php

namespace App\Http\Controllers;

use App\OracleBasCustomer;
use App\Owner;
use App\Services\AllInventoryService;
use App\Services\InventoryDailyLogService;
use App\Services\InventoryService;
use App\Services\OwnerService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;

class InventoryController extends Controller
{
    public function __construct()
    {
        app()->singleton('inventoryService',InventoryService::class);
        app()->singleton('AllInventoryService',AllInventoryService::class);

    }
    //动库报表
    public function changeInventory(Request $request){
        if(!Gate::allows("库存管理-库存")){ return redirect(url('/'));  }
        $oracleActTransactingLogs=app('inventoryService')->paginate($request->input());
        $oracleActTransactingLogs=json_encode($oracleActTransactingLogs);
//        $owners=OracleBasCustomer::query()->select('customerid','descr_c')->where('customer_type','OW')->where('active_flag','Y')->get();
        $owners=Owner::filterAuthorities()->select(['code', 'name'])->get();
        $isTotalStock=false;
        $page = $request->page ?? 1;
        return view('inventory.statement.changeInventory',compact('oracleActTransactingLogs','page','owners','isTotalStock'));
    }
    //全部库存
    public function allInventory(Request $request){
        if(!Gate::allows("库存管理-库存")){ return redirect(url('/'));  }

        /** @var AllInventoryService $service */
        $service = app('AllInventoryService');
        $oracleActTransactingLogs= $service->paginate($request->input());
        $oracleActTransactingLogs=json_encode($oracleActTransactingLogs);
//        $owners=OracleBasCustomer::query()->select('customerid','descr_c')->where('customer_type','OW')->where('active_flag','Y')->get();
        $owners=Owner::filterAuthorities()->select(['code', 'name'])->get();
        $isTotalStock=true;
        $page = $request->page ?? 1;
        return view('inventory.statement.changeInventory',compact('oracleActTransactingLogs','page','owners','isTotalStock'));
    }
    public function exportData(Request $request){
        if(!Gate::allows("库存管理-库存")){ return redirect(url('/'));  }
        if ($request->checkAllSign){
            $params = $request->input();
            unset($params['checkAllSign']);
            $sql=app('inventoryService')->getSql($request->input());
            $post = Http::post(config('go.export.url'),['type'=>'inventory','sql'=>$sql]);
        }else {
            $post = Http::post(config('go.export.url'), ['type' => 'inventory', 'data' => $request->data]);
        }
        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 exportAllInventory(Request $request){
        if(!Gate::allows("库存管理-库存")){ return redirect(url('/'));  }
        if ($request->checkAllSign){
            $params = $request->input();
            unset($params['checkAllSign']);
            $sql=app('AllInventoryService')->getSql($request->input());
            $post = Http::post(config('go.export.url'),['type'=>'allInventory','sql'=>$sql]);
        }else{
            $post = Http::post(config('go.export.url'),['type'=>'allInventory','data'=>$request->data]);
        }
        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',
        ]);
    }

    /*
     *  库存体积
     */
    function dailyLog(Request $request,OwnerService $ownerService){
        if (!Gate::allows('库存管理-库存体积')){return redirect(url('/')); }
        /** @var InventoryDailyLogService*/
        $inventoryDailyLogs = app('InventoryDailyLogService')->paginate($request->input());
        $owners = $ownerService->getIntersectPermitting();
        $param = $request->input();
        return view('inventory.statement.dailyLog',compact('inventoryDailyLogs','owners','param'));
    }

    //获取记录监听货主
    function getLoggingOwner(){
        $loggingOwners = app('InventoryDailyLogService')->getInventoryDailyLoggingOwner('owner_id');
        return array_column($loggingOwners->toArray(),'owner_id');
    }
    //添加记录监听货主
    function addLoggingOwner(Request $request){
        if (!Gate::allows('库存管理-库存体积-管理监听货主')){return redirect(url('/')); }
        $owner_id = $request->owner_id;
        if (!$owner_id || !is_numeric($owner_id))return ['success'=>false,'data'=>'传递参数错误！'];
        $loggingOwner = app('InventoryDailyLogService')->firstOrCreate(['owner_id'=>$owner_id]);
        if (!$loggingOwner)return ['success'=>false,'data'=>'录入失败！'];
        return ['success'=>true,'data'=>$loggingOwner->owner_id];
    }
    //导出库存体积记录
    public function exportDailyLog(Request $request){
        if (!Gate::allows('库存管理-库存体积')){return redirect(url('/')); }
        if ($request->checkAllSign){
            $params = $request->input();
            unset($params['checkAllSign']);
            $sql=app('InventoryDailyLogService')->getSql($params);

        }else $sql=app('InventoryDailyLogService')->getSql(['id'=>$request->data]);

        $row = ["货主","日期","商品名称","商品编码","商品条码","属性仓","在库数量","长","宽","高","体积","总占用体积","总毛重"];
        $column = ["owner_name", "created_at", "commodity_name", "commodity_sku", "commodity_barcode_code","depository_name",
            "amount", "commodity_length", "commodity_width", "commodity_height", "commodity_volumn", "volumn_occupied", "gross_weight"];
        $rule = ["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',
        ]);
    }
}
