<?php

namespace App\Http\Controllers;

use App\Exports\Export;
use App\InventoryAccount;
use App\InventoryAccountMission;
use App\Services\InventoryAccountService;
use App\Services\OwnerService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;

class InventoryAccountController extends Controller
{
    public function __construct()
    {
        app()->singleton('inventoryAccountService', InventoryAccountService::class);
    }

    //创建盘点任务
    public function createStockInventoryMission(Request $request)
    {
        if (!Gate::allows("库存管理-盘点")) {
            return redirect(url('/'));
        }
//        $date_start=$request->input('formData.date_start');
//        $date_end=$request->input('formData.date_end');
//        $ownerId=$request->input('formData.owner_id')[0];
        $date_start = $request->input('date_start');
        $date_end = $request->input('date_end');
        $ownerId = $request->input('owner_id');
        $location = $request->input('location');
        $barcode = $request->input('barcode');
        $inventoryAccount = app('inventoryAccountService')->createMission($date_start, $date_end, $ownerId, $location, $barcode);
        $inventoryAccount = InventoryAccount::with('owner')->find($inventoryAccount->id);
        if (is_null($inventoryAccount)) return ['success' => false, 'data' => '参数错误!'];
        return ['success' => true, 'data' => $inventoryAccount];
    }

    //删除盘点任务
    public function deleteStockInventoryMission($id)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return ['success' => 0, 'status' => '没有权限'];
        }
        if (is_null($id)) {
            return ['success' => false, 'data' => '传入id为空'];
        }
        $inventoryAccount = InventoryAccount::where('id', $id)->delete();
        return ['success' => true, 'data' => $inventoryAccount];
    }

    public function inventoryChecked(Request $request)
    {
        if (!Gate::allows('库存管理-盘点-项目审核')) {
            return ['success' => false, 'msg' => '没有权限'];
        }
        $id = $request->id;
        if (is_null($id)) {
            return ['success' => false, 'msg' => '传入id为空'];
        }
        $inventoryAccount = InventoryAccount::query()->where('id', $id)->update([
            'auditor' => Auth::user()['id'],
            'status' => '已审核',
        ]);
        if ($inventoryAccount == 1) {
            $inventoryAccount = InventoryAccount::query()->with('userAuditor')->find($id);
            return ['success' => true, 'data' => $inventoryAccount];
        } else {
            return ['success' => false, 'msg' => '审核失败!'];
        }
    }

    //盘点-任务页面
    public function mission(Request $request, OwnerService $ownerService)
    {
        if (!Gate::allows("库存管理-盘点")) {
            return redirect(url('/'));
        }
        $paginateParams = $request->input();
        $queryParam = $request->all();
        $inventoryAccounts = app('inventoryAccountService')->paginate($queryParam);
        $owners = $ownerService->getIntersectPermitting();
        return view('inventory.stockInventory.mission', compact('owners', 'inventoryAccounts', 'paginateParams'));
    }

    //进入盘点中或复盘页面
    public function enterStockInventory($id, Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return redirect(url('/'));
        }
        if (!$id) return ['success' => false, 'data' => '参数错误!'];
        $inventoryAccount = InventoryAccount::with('owner')->find($id);
        $inventoryAccountMissions = InventoryAccountMission::with(['commodity.barcodes', 'stockInventoryPersons'])->where('inventory_account_id', $id)->orderBy('difference_amount', 'desc')->get();
        return view('inventory.stockInventory.inventoryMission', compact('inventoryAccount', 'inventoryAccountMissions'));
    }

    public function enterBlindReceive($id)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return redirect(url('/'));
        }
        if (!$id) return ['success' => false, 'data' => '参数错误!'];
        $inventoryAccount = InventoryAccount::with('owner')->find($id);
        return view('inventory.stockInventory.blindReceive', compact('inventoryAccount'));
    }

    //依据盘点任务id进行 --盘点
    public function stockInventory(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return redirect(url('/'));
        }
        $location = $request->input('location');
        $barcode = $request->input('barcode');
        $inventoryId = $request->input('inventoryId');
        $count = $request->input('count');
        $id = $request->input('id');
        if (is_null($count)) return ['success' => false, 'data' => '盘点数不能为空!'];
        /** @var InventoryAccountService $inventoryAccountService */
        $inventoryAccountService = app('inventoryAccountService');
        $inventoryAccountMission = $inventoryAccountService->stockInventory($id, $location, $barcode, $count, $inventoryId);
        if (!$inventoryAccountMission) return ['success' => false, 'data' => '参数错误!'];
        /** @var InventoryAccountService $inventoryService */
        $inventoryService = app('inventoryAccountService');
        $inventoryAccount = $inventoryService->updateInventory($inventoryId);
        $stockInventoryPersons = $inventoryAccountMission->stockInventoryPersons;
        return ['success' => true, 'inventoryMission' => $inventoryAccountMission, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
    }

    public function baseOnBlindReceive(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return redirect(url('/'));
        }
        $location = $request->input('location');
        $inventoryId = $request->input('inventoryId');
        $owner_code = $request->input('owner_code');
        $goodses = $request->input('goodses');
        if (!$location) return ['success' => false, 'fail_info' => '盘点库位不存在!'];
        if (count($goodses) < 1) return ['success' => false, 'fail_info' => '盘点商品不存在!'];
        //dd($location,$owner_code,$goodses,$inventoryId,$owner_id);
        /** @var InventoryAccountService $inventoryAccountMission */
        $inventoryAccountService = app('inventoryAccountService');
        $inventoryAccountMissions = $inventoryAccountService->baseOnBlindReceive($location, $owner_code, $goodses, $inventoryId);
        if (count($inventoryAccountMissions) < 0) return ['success' => false, 'fail_info' => '盲收盘点失败!'];
        /** @var InventoryAccountService $inventoryService */
        $inventoryService = app('inventoryAccountService');
        $inventoryAccount = $inventoryService->updateInventory($inventoryId);
        if ($inventoryAccountMissions && $inventoryAccount)
            $stockInventoryPersons = $inventoryAccountMissions[0]->stockInventoryPersons;
        return ['success' => true, 'inventoryMissions' => $inventoryAccountMissions, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
    }

    //根据该库存和产品条码查询该条盘点记录??
    public function searchStockInventoryRecord(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return redirect(url('/'));
        }
        $location = $request->input('location');
        $barcode = $request->input('barcode');
        $inventoryId = $request->input('inventoryId');
        /** @var InventoryAccountService $application */
        $application = app('inventoryAccountService');
        $inventoryAccountMissions = $application->searchStockInventoryRecord($location, $barcode, $inventoryId);
        if ($inventoryAccountMissions->isEmpty()) return ['success' => false, 'data' => '没有找到相应记录!'];
//        $stockInventoryPersons=$inventoryAccountMissions->stockInventoryPersons;
//        return ['success'=>true,'data'=>$inventoryAccountMissions,'stockInventoryPersons'=>$stockInventoryPersons];
        return ['success' => true, 'data' => $inventoryAccountMissions];
    }

    //盘点任务导出
    public function stockInventoryExport(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return redirect(url('/'));
        }
        ini_set('max_execution_time', 3500);
        ini_set('memory_limit', '3526M');
        if ($request->checkAllSign) {
            $request->offsetUnset('checkAllSign');
            $queryParam = $request->all();
            $inventoryAccounts = app('inventoryAccountService')->get($queryParam);
        } else {
            $queryParam = $request->all();
            $inventoryAccounts = app('inventoryAccountService')->some($queryParam);
        }
        $row = [[
            'id' => '盘点单号',
            'status' => '盘点状态',
            'created_at' => '创建时间',
            'owner_id' => '货主',
            'type' => '任务类型',
            'start_at' => '起始时间',
            'end_at' => '结束时间',
            'total' => '盘点任务数',
            'processed' => '盘点数量',
            'surplus' => '未盘数量',
            'ignored' => '跳过数量',
            'difference' => '差异数量',
            'returned' => '复盘归位',
            'proportion' => '盘点比例',
        ]];
        $list = [];
        for ($i = 0; $i < count($inventoryAccounts); $i++) {
            $inventoryAccount = $inventoryAccounts[$i];
            $w = [
                'id' => isset($inventoryAccount->id) ? $inventoryAccount->id : '',
                'status' => isset($inventoryAccount->status) ? $inventoryAccount->status : '',
                'created_at' => isset($inventoryAccount->created_at) ? $inventoryAccount->created_at : '',
                'owner_id' => isset($inventoryAccount->owner->name) ? $inventoryAccount->owner->name : '',
                'type' => isset($inventoryAccount->type) ? $inventoryAccount->type : '',
                'start_at' => isset($inventoryAccount->start_at) ? $inventoryAccount->start_at : '',
                'end_at' => isset($inventoryAccount->end_at) ? $inventoryAccount->end_at : '',
                'total' => isset($inventoryAccount->total) ? $inventoryAccount->total : '',
                'processed' => isset($inventoryAccount->processed) ? $inventoryAccount->processed : '',
                'surplus' => isset($inventoryAccount->surplus) ? $inventoryAccount->surplus : '',
                'ignored' => isset($inventoryAccount->ignored) ? $inventoryAccount->ignored : '',
                'difference' => isset($inventoryAccount->difference) ? $inventoryAccount->difference : '',
                'returned' => isset($inventoryAccount->returned) ? $inventoryAccount->returned : '',
                'proportion' => isset($inventoryAccount->processed) && isset($inventoryAccount->total) ? $inventoryAccount->processed.'/'.$inventoryAccount->total : '',
            ];
            $list[$i] = $w;
        }
        return Excel::download(new Export($row, $list), date('YmdHis', time()) . '-盘点任务记录单.xlsx');
    }

    public function stockInventoryEnd(Request $request)
    {
        if (!Gate::allows('库存管理-盘点-结束初盘')) {
            return ['success' => false, 'data' => '没有权限'];
        }
        $id = $request->input('id');
        if (!$id) return ['success' => false, 'data' => '参数错误!'];
        $inventoryAccount = InventoryAccount::query()->where('id', $id)->update(['status' => '复盘中']);
        app('LogService')->log(__METHOD__, '结束初盘任务' . __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
        if ($inventoryAccount > 0) return ['success' => true, 'data' => '复盘中'];
        return ['success' => false, 'data' => '参数错误!'];
    }

    public function syncOwners(OwnerService $ownerService)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return redirect(url('/'));
        }
        $owners = $ownerService->syncOwnersData();
        if (!$owners) return ['success' => false, 'data' => '同步货主失败!'];
        return ['success' => true, 'data' => $owners];
    }

    public function 修改质量状态(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return redirect(url('/'));
        }
        $id = $request->input('id');
        $location = $request->location;
        $sku = $request->sku;
        $quality = $request->quality;
        $ownerCode = $request->ownerCode;
        $inventoryAccountMission = app('inventoryAccountService')->修改质量状态($id, $location, $sku, $quality, $ownerCode);
        app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
        if ($inventoryAccountMission == null) return ['success' => false, 'data' => 'WMS中不存在该条记录！'];
        return ['success' => true, 'data' => '质量状态修改成功'];

    }

    public function 完结盘点任务($id)
    {
        if (!Gate::allows('库存管理-盘点-完结')) {
            return ['success' => false, 'status' => '没有权限'];
        }
        if (!$id) return ['success' => false, 'status' => '参数错误！'];
        $inventoryAccount = app('inventoryAccountService')->完结盘点任务($id);
        if (!$inventoryAccount) return ['success' => false, 'status' => '修改完结状态失败！'];
        return ['success' => true, 'data' => $inventoryAccount];

    }

    public function 增加系统之外的盘点记录(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return ['success' => false, 'data' => '没有权限'];
        }
        $location = $request->input('location');
        $barcode = $request->input('barcode');
        $inventoryId = $request->input('inventoryId');
        $count = $request->input('count');
        $owner_code = $request->input('owner_code');
        $param = $request->input('param');
        if (is_null($count)) return ['success' => false, 'data' => '盘点数不能为空!'];
        $inventoryAccountMission = app('inventoryAccountService')->增加系统之外的盘点记录($location, $barcode, $inventoryId, $count, $owner_code, $param);
        if (!$inventoryAccountMission) return ['success' => false, 'data' => '添加系统之外的库位记录失败！'];
        $inventoryAccountMission = InventoryAccountMission::with(['commodity.barcodes', 'stockInventoryPersons'])->where('id', $inventoryAccountMission->id)->first();
        $stockInventoryPersons = $inventoryAccountMission->stockInventoryPersons;
        return ['success' => true, 'inventoryAccountMission' => $inventoryAccountMission, 'stockInventoryPersons' => $stockInventoryPersons];
    }

    public function 盘点选中任务(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return ['success' => false, 'data' => '没有权限'];
        }
        $id = $request->input('id');
        $count = $request->count;
        $inventoryId = $request->input('inventoryId');
        $produced_at = $request->input('produced_at');
        $valid_at = $request->input('valid_at');
        $batch_number = $request->input('batch_number');
        if (is_null($count)) return ['success' => false, 'data' => '盘点数不能为空!'];
        if ($produced_at || $valid_at || $batch_number) {
            /** @var InventoryAccountService $inventoryAccountMission */
            $inventoryAccountService = app('inventoryAccountService');
            $inventoryAccountMission = $inventoryAccountService->盘点生产日期_失效日期_批号有改动任务($id, $count, $inventoryId, $produced_at, $valid_at, $batch_number);
            if (!$inventoryAccountMission) return ['success' => false, 'data' => '盘点生产日期_失效日期_批号有改动任务失败!'];
            /** @var InventoryAccountService $inventoryService */
            $inventoryService = app('inventoryAccountService');
            $inventoryAccount = $inventoryService->updateInventory($inventoryId);
            $stockInventoryPersons = $inventoryAccountMission[0]->stockInventoryPersons;
            return ['success' => true, 'inventoryMission' => $inventoryAccountMission, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
        } else {
            /** @var InventoryAccountService $inventoryAccountMission */
            $inventoryAccountService = app('inventoryAccountService');
            $inventoryAccountMission = $inventoryAccountService->盘点选中任务($id, $count, $inventoryId);
            if (!$inventoryAccountMission) return ['success' => false, 'data' => '盘点选中任务失败!'];
            /** @var InventoryAccountService $inventoryService */
            $inventoryService = app('inventoryAccountService');
            $inventoryAccount = $inventoryService->updateInventory($inventoryId);
            $stockInventoryPersons = $inventoryAccountMission->stockInventoryPersons;
            return ['success' => true, 'inventoryMission' => $inventoryAccountMission, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
        }
    }

    public function 删除盘点记录(Request $request)
    {
        if (!Gate::allows('库存管理-盘点-删除')) {
            return ['success' => false, 'data' => '没有权限'];
        }
        $inventoryAccountMissionId = $request->input('inventoryAccountMissionId');
        $inventoryAccountId = $request->input('inventoryAccountId');
        if (is_null($inventoryAccountMissionId)) {
            return ['success' => false, 'data' => '传入id为空'];
        }
        /** @var InventoryAccountService $inventoryService */
        $inventoryService = app('inventoryAccountService');
        $inventoryAccountMission = $inventoryService->删除盘点记录($inventoryAccountMissionId, $inventoryAccountId);
        return ['success' => true, 'data' => $inventoryAccountMission];
    }

    public function 跳过盘点记录(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return ['success' => false, 'data' => '没有权限'];
        }
        $inventoryAccountMissionId = $request->inventoryAccountMissionId;
        $inventoryAccountId = $request->input('inventoryAccountId');
        if (is_null($inventoryAccountMissionId)) {
            return ['success' => false, 'data' => '传入id为空'];
        }
        /** @var InventoryAccountService $inventoryService */
        $inventoryService = app('inventoryAccountService');
        $inventoryAccountMission = $inventoryService->跳过盘点记录($inventoryAccountMissionId, $inventoryAccountId);
        return ['success' => true, 'inventoryAccountMission' => $inventoryAccountMission];
    }

    public function 确认盘点差异(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return ['success' => false, 'data' => '没有权限'];
        }
        $inventoryAccountMissionId = $request->inventoryAccountMissionId;
        $inventoryAccountId = $request->input('inventoryAccountId');
        if (is_null($inventoryAccountMissionId)) {
            return ['success' => false, 'data' => '传入id为空'];
        }
        /** @var InventoryAccountService $inventoryService */
        $inventoryService = app('inventoryAccountService');
        $inventoryAccountMission = $inventoryService->确认盘点差异($inventoryAccountMissionId, $inventoryAccountId);
        return ['success' => true, 'inventoryAccountMission' => $inventoryAccountMission];
    }

    public function 批量跳过或确认差异(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return ['success' => false, 'data' => '没有权限'];
        }
        $checkData = $request->checkData;
        if (is_null($checkData)) {
            return ['success' => false, 'data' => '传入勾选盘点记录为空'];
        }
        $marks = [];
        foreach ($checkData as $inventoryMission) {
            if (isset($inventoryMission['mark']))array_push($marks,$inventoryMission['mark']);
        }
        if (in_array('确认差异', $marks) || in_array('跳过', $marks) || in_array('无差异', $marks) || in_array('已复盘无差异', $marks)) return ['success' => false, 'data' => '传入勾选盘点记录存在不可操作项!'];
        /** @var InventoryAccountService $inventoryService */
        $inventoryService = app('inventoryAccountService');
        $inventoryAccountMissions = $inventoryService->批量跳过或确认差异($checkData);
        return ['success' => true, 'inventoryAccountMissions' => $inventoryAccountMissions];
    }

    public function exportInventoryAccountMission(Request $request)
    {
        if (!Gate::allows("库存管理-盘点")) {
            return redirect(url('/'));
        }
        $post = Http::post(config('go.export.url'), ['type' => 'inventoryAccountMission', '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 searchCommodityByBarcode(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) {
            return ['success' => false, 'data' => '没有权限'];
        }
        $barcode = $request->input('barcode');
        $owner_code = $request->input('owner_code');
        /** @var InventoryAccountService $inventoryService */
        $inventoryService = app('inventoryAccountService');
        $commodity = $inventoryService->searchCommodityByBarcode($barcode, $owner_code);
        if ($commodity) {
            return ['success' => true, 'data' => $commodity];
        } else {
            return ['success' => false, 'data' => '输入的条码没有对应商品!'];
        }
    }
    //根据库位批量盘点该库位下盘点记录
    public function batchStockByLocation(Request $request)
    {
        if (!Gate::allows('库存管理-盘点')) return ['success' => false, 'msg' => '没有权限'];
        $missions=$request->mission;
        $inventoryId=$request->inventoryId;
        if (!$inventoryId||count($missions)<1) return ['success' => false, 'msg' => '参数错误'];
        /** @var InventoryAccountService $inventoryService */
        $inventoryService = app('inventoryAccountService');
        $inventoryMissions=$inventoryService->batchStockByLocation($missions,$inventoryId);
        $inventoryService = app('inventoryAccountService');
        $inventoryAccount = $inventoryService->updateInventory($inventoryId);
        $stockInventoryPersons = $inventoryMissions[0]->stockInventoryPersons;
        return ['success' => true, 'inventoryMission' => $inventoryMissions, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
    }
}
