<?php
namespace App\Http\Controllers\WeChatApplet\Technician;

use App\Http\Models\Api\Common;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Export;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use App\Models\OperationLog;
use App\Services\CommonService;
use App\Http\Controllers\Api\Verify\WarehouseManage\VerifyStocktakeController;
use App\Http\Controllers\Api\WarehouseManage\StocktakeController;
use App\Http\Models\Api\WarehouseManage\Stocktake;
use App\Http\Models\Api\OutinRecord;
use App\Services\Business\WashOrderBasicService;

// 技师小程序-仓库盘货
class WashStockakeController extends Controller
{
    /**
     * 新增盘库单
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-04-07
     * @param  Request          $request [description]
     */
    public function add(Request $request)
    {
        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'add';
        logFileRecord($log_record, 'wash/WashStockake', 2);
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->saveValidator($request->all());
        if ($error_message) {
            $message = $error_message->all();
            return response()->json(['code' => 500, 'msg' => $message[0], 'data' => '参数错误', 'error_message' => $error_message]);
        }

        $goods_data = json_decode($request['goods_data'], true);
        if (empty($goods_data)) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '请选择商品']);
        }

        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();

        DB::beginTransaction();
        $stoc_return = $this->saveSubmitData($request->all(), $goods_data, $user_info, 2);
        if ($stoc_return['code'] == 500) {
            DB::rollBack();
            return response()->json($stoc_return);
        }
        $post_data['stoc_id'] = $stoc_return['return_data']['stoc_id'];
        $stoc_res = $this->pass($user_info, $post_data);
        
        $post_data['ware_id'] = $request['ware_id'];
        $post_data['new_goods_data'] = $goods_data;
        $res = WashOrderBasicService::addGoodPlan($user_info, $post_data);
        if ($stoc_return['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '盘库单', '新增', '新增盘库单：' . $stoc_return['return_data']['stoc_storage_number'] . '成功');
        } else {
            DB::rollBack();
        }
        return response()->json($stoc_return);
    }

    /**
     * [saveSubmitData 运营中心版保存提交的数据]
     * @param  [type] $request      [提交的数据]
     * @param  [type] $goods_data   [提交的商品数据]
     * @param  [type] $user_info    [用户信息]
     * @param  [type] $type         [类型：1保存2提交]
     * @param  [type] $call_type    [调用类型：1新增调用2编辑调用]
     * @return [type]               [description]
     */
    public function saveSubmitData(
        $request,
        $goods_data,
        $user_info,
        $type,
        $call_type = 1
    ) {
        $stocktake_number = 0;  //良品盘点数量
        $priority_stocktake_number = 0;  //优先盘点数量
        $unchecked_stocktake_number = 0;  //待检测盘点数量
        $request['stoc_waon_class'] = 1;  //只有货物仓可以提交 20230517
        $num = 0;
        foreach ($goods_data as $key => $value) {
            // 根据仓库id查询仓库类型：1固定仓2技师库3移动仓
            $ware_type = DB::table('warehouse')
                ->where('ware_id', $request['ware_id'])
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->value('ware_type');
            // shop_versions 系统版本：1门店版2运营中心版
            // 固定仓有仓位 固定仓，查询仓位商品库存数量
                // 固定仓判断是否选择仓位，固定仓必须选择仓位
            if (!isset($value['wafr_id']) || empty($value['wafr_id'])) {
                $value['wafr_id'] = DB::table('warehouse_freight')
                    ->where('wafr_ware_id', $request['ware_id'])
                    ->value('wafr_id');
            }

            $warehouse_goods = DB::table('warehouse_freight_goods')
                ->where('wafg_wafr_id', $value['wafr_id'])
                ->where('wafg_ware_id', $request['ware_id'])
                ->where('wafg_class', $request['stoc_waon_class'])
                ->where('wafg_goo_id', $value['goo_id'])
                ->select('wafg_goo_id', 'wafg_stock_number as wago_freight_stock_number', 'wafg_lock_quantity as wago_freight_lock_quantity', 'wafg_priority_stock_number as wago_freight_priority_stock_number', 'wafg_priority_lock_quantity as wago_freight_priority_lock_quantity', 'wafg_unchecked_stock_number as wago_freight_unchecked_stock_number')
                ->first();
            
            $warehouse_goods = json_decode(json_encode($warehouse_goods), true);
            if (!$warehouse_goods) {
                $wago_freight_stock_number = 0;
                $wago_freight_lock_quantity = 0;
                $wago_freight_priority_stock_number = 0;
                $wago_freight_priority_lock_quantity = 0;
                $wago_freight_unchecked_stock_number = 0;
            } else {
                $wago_freight_stock_number = $warehouse_goods['wago_freight_stock_number'];//仓位良品数量
                $wago_freight_lock_quantity = $warehouse_goods['wago_freight_lock_quantity'];//锁定良品数量
                $wago_freight_priority_stock_number = $warehouse_goods['wago_freight_priority_stock_number'];
                $wago_freight_priority_lock_quantity = $warehouse_goods['wago_freight_priority_lock_quantity'];
                $wago_freight_unchecked_stock_number = $warehouse_goods['wago_freight_unchecked_stock_number'];
            }
            // if ($value['stocktake_number'] < 0) {
            //     $stocktake_numbers = abs($value['stocktake_number']);//盘点数量
            //     if ($stocktake_numbers > $wago_freight_stock_number) {
            //         return ['code' => 400, 'msg' => '盘亏数量大于仓位数量', 'data' => '盘亏数量大于仓位数量', 'return_data' => $goods_data];
            //     }
            // }
            // if ($value['priority_stocktake_number'] < '0') {
            //     $priority_stocktake_numbers = abs($value['priority_stocktake_number']);
            //     if ($priority_stocktake_numbers > $wago_freight_priority_stock_number) {
            //         return ['code' => 400, 'msg' => '优先盘亏数量大于仓位数量', 'data' => '优先盘亏数量大于仓位数量', 'return_data' => $goods_data];
            //     }
            // }
            $stgo_data[$num]['stgo_goo_id'] = $value['goo_id']; //商品id
            $stgo_data[$num]['stgo_wafr_id'] = isset($value['wafr_id']) ? $value['wafr_id'] : 0; //仓位id
            $stgo_data[$num]['stgo_stock_number'] = $wago_freight_stock_number; //良品库存数量
            $stgo_data[$num]['stgo_priority_stock_number'] = $wago_freight_priority_stock_number; //优先库存数量
            $stgo_data[$num]['stgo_unchecked_stock_number'] = $wago_freight_unchecked_stock_number; //待检测数量
            $stgo_data[$num]['stgo_lock_number'] = $wago_freight_lock_quantity; //良品锁定数量
            $stgo_data[$num]['stgo_priority_lock_number'] = $wago_freight_priority_lock_quantity; //优先锁定数量
            $stgo_data[$num]['stgo_stocktake_number'] = $value['stocktake_number'] - $wago_freight_stock_number; //良品盘点数量
            $num++;

            $stocktake_number += ($value['stocktake_number'] - $wago_freight_stock_number); //良品盘点数量
        }

        $stoc_differ_number = $stocktake_number; //损益数量
        if ($stoc_differ_number > 0) {
            // 类型：1盘盈2盘亏3盘平
            $stoc_type = 1;
        } elseif ($stoc_differ_number < 0) {
            $stoc_type = 2;
        } else {
            $stoc_type = 3;
        }

        // 1 新增一个盘库单数据
        $stoc_data['stoc_cid'] = $user_info->adm_cid;
        $stoc_data['stoc_shop_id'] = $user_info->adm_shop_id;
        $stoc_data['stoc_superior_shop_id'] = $user_info->shop_superior_id;
        $stoc_data['stoc_adm_id'] = $user_info->adm_id;
        $stoc_data['stoc_storage_number'] = 'P' . truncateFill($user_info->adm_shop_id, 2) . date('mdHis') . truncateFill($user_info->adm_id, 2) . rand(10000, 99999);
        $stoc_data['stoc_type'] = $stoc_type;
        $stoc_data['stoc_differ_number'] = abs($stoc_differ_number);
        if ($type == 1) {
            $stoc_data['stoc_state'] = 1; //状态1保存/待提交2提交/待审核3通过4驳回
        } else {
            $stoc_data['stoc_state'] = 2; //状态1保存/待提交2提交/待审核3通过4驳回
        }
        $stoc_data['stoc_remark'] = isset($request['stoc_remark']) ? $request['stoc_remark'] : '';
        $stoc_data['stoc_ware_id'] = $request['ware_id'];
        $stoc_data['stoc_make_time'] = date('Y-m-d H:i:s');
        $stoc_data['stoc_waon_class'] = $request['stoc_waon_class'];
        $stoc_data['stoc_manner'] = $request['stoc_manner'];

        // 新增盘库单
        $stoc_res =  DB::table('stocktake')->insertGetId($stoc_data);
        $request['stoc_id'] = $stoc_res;
        // 2. 新增盘点商品数据
        foreach ($stgo_data as $key => $value) {
            $stgo_data[$key]['stgo_stoc_id'] = $stoc_res;
            $stgo_res =  DB::table('stocktake_goods')->insert($stgo_data[$key]);
        }
        $hint = '新增';

        if ($stoc_res && $stgo_res) {
            $return_data['stoc_storage_number'] = $stoc_data['stoc_storage_number'];
            $return_data['stoc_id'] = $stoc_res;
            return ['code' => 200, 'msg' => 'success', 'data' => $hint . '盘库单：成功', 'return_data' => $return_data];
        } else {
            return ['code' => 500, 'msg' => 'error', 'data' => $hint . '盘库单：失败'];
        }
    }


    /**
     * 通过
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-04-07
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function pass($user_info,$request)
    {
        // 查询信息
        $find_stoc = DB::table('stocktake')
            ->where('stoc_id', $request['stoc_id'])
            ->select('stoc_id', 'stoc_storage_number', 'stoc_state', 'stoc_ware_id', 'stoc_waon_class', 'stoc_type', 'stoc_adm_id', 'stoc_create_time', 'stoc_differ_number', 'stoc_is_import')
            ->first();
        if ($find_stoc->stoc_state != 2) {
            return ['code' => 500, 'msg' => 'error', 'data' => '当前盘库单不是待审核状态'];
        }
        $surplus = DB::table('warehouse')
            ->where('ware_id', $find_stoc->stoc_ware_id)
            ->select('ware_all_stock', 'ware_lock_quantity', 'ware_priority_all_stock', 'ware_priority_lock_quantity', 'ware_unchecked_all_stock', 'ware_type')
            ->first();


        // 1. 将盘点单状态改为通过
        $update_data['stoc_state'] = 3; //状态1保存/待提交2提交/待审核3通过4驳回
        $update_data['stoc_update_time'] = date('Y-m-d H:i:s');
        $stoc_res = DB::table('stocktake')
            ->where('stoc_id', $request['stoc_id'])
            ->update($update_data);

        // 2. 查询要盘点的商品数量
        $stocktake_goods = DB::table('stocktake_goods')
            ->where('stgo_stoc_id', $find_stoc->stoc_id)
            ->select('stgo_id', 'stgo_goo_id', 'stgo_stock_number', 'stgo_stocktake_number', 'stgo_priority_stock_number', 'stgo_unchecked_stock_number', 'stgo_priority_stocktake_number', 'stgo_unchecked_stocktake_number', 'stgo_wafr_id')
            ->get()->toArray();
        $stocktake_goods = json_decode(json_encode($stocktake_goods), true);
        $goods_id = array_column($stocktake_goods, 'stgo_goo_id'); //商品id
        // 3. 查询盘点仓库表的库存总数
        $find_waon_data = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $find_stoc->stoc_ware_id)
            ->where('waon_class', $find_stoc->stoc_waon_class)
            ->select('waon_id', 'waon_stock_fine_amount', 'waon_stock_priority_amount', 'waon_stock_unchecked_amount')
            ->first();

        $shop_versions = 2; //系统版本信息1门店版2运营中心版
        $diff_ware_amount = 0; //盘库差异数量

        $diff_stock_amount = 0; //盘库良品差异数量
        $diff_priority_amount = 0; //盘库优先差异数量

        $diff_stock_goo_number = []; //盘库单的商品良品差异数量
        $diff_priority_goo_number = []; //盘库单的商品优先差异数量
        // 查询仓库类型：1固定仓2技师库3移动仓
        $ware_type = DB::table('warehouse')
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_shop_id', $user_info->adm_shop_id)
            ->where('ware_id', $find_stoc->stoc_ware_id)
            ->value('ware_type');
        foreach ($stocktake_goods as $key => $value) { //入库数据
            if ($ware_type == 3) {
                $value['stgo_wafr_id'] = 0;
            }
            $find_wago_data = DB::table('warehouse_goods')
                ->where('wago_ware_id', $find_stoc->stoc_ware_id)
                ->where('wago_class', $find_stoc->stoc_waon_class)
                ->where('wago_goo_id', $value['stgo_goo_id'])
                ->select('wago_id', 'wago_ware_id', 'wago_class', 'wago_goo_id', 'wago_stock_number', 'wago_priority_stock_number', 'wago_stock_amount', 'wago_priority_stock_amount', 'wago_stock_amount', 'wago_lock_amount', 'wago_priority_stock_amount', 'wago_priority_lock_amount', 'wago_freight_stock_number', 'wago_freight_priority_stock_number')
                ->first();
            if (empty($find_wago_data)) {
                $find_goods_encode = DB::table('goods')
                    ->where('goo_id', $value['stgo_goo_id'])
                    ->where('goo_delete', 1)
                    ->value('goo_goods_encode');
                return ['code' => 500, 'msg' => 'error', 'data' => '检索编码：（' . $find_goods_encode . '）不在我的仓库--库存列表，请进行采购或调拨！！！'];
            } else {
                if ($value['stgo_wafr_id'] == 0) { //从仓库入
                    // 判断移动仓库内是否有入库商品id，有商品id就更改库存数量
                    if ($value['stgo_stocktake_number'] != 0) { //商品锁定类型：1良品
                        // 更改仓库商品表库存数量
                        $wago_edit_data['wago_stock_number'] = $find_wago_data->wago_stock_number + $value['stgo_stocktake_number'];
                        $wago_edit_data['wago_stock_amount'] = $find_wago_data->wago_stock_amount + $value['stgo_stocktake_number'];
                        $wago_edit_data['wago_update_time'] = date('Y-m-d H:i:s');
                        // 仓库商品表优先数量增加
                        $wago_stock_number = DB::table('warehouse_goods')
                            ->where('wago_ware_id', $find_stoc->stoc_ware_id)
                            ->where('wago_class', $find_stoc->stoc_waon_class)
                            ->where('wago_id', $find_wago_data->wago_id)
                            ->update($wago_edit_data);
                        unset($wago_edit_data);
                        if (!$wago_stock_number) {
                            return ['code' => 500, 'msg' => 'error', 'data' => '仓库数量盘库失败！1'];
                        }
                    }

                    if ($value['stgo_priority_stocktake_number'] != 0) { //商品锁定类型：1良品
                        // 更改仓库商品表库存数量
                        $wago_edit_data['wago_priority_stock_number'] = $find_wago_data->wago_priority_stock_number + $value['stgo_priority_stocktake_number'];
                        $wago_edit_data['wago_priority_stock_amount'] = $find_wago_data->wago_priority_stock_amount + $value['stgo_priority_stocktake_number'];
                        $wago_edit_data['wago_update_time'] = date('Y-m-d H:i:s');
                        // 仓库商品表优先数量增加
                        $wago_stock_amount = DB::table('warehouse_goods')
                            ->where('wago_ware_id', $find_stoc->stoc_ware_id)
                            ->where('wago_class', $find_stoc->stoc_waon_class)
                            ->where('wago_id', $find_wago_data->wago_id)
                            ->update($wago_edit_data);
                        unset($wago_edit_data);
                        if (!$wago_stock_amount) {
                            return ['code' => 500, 'msg' => 'error', 'data' => '仓库数量盘库失败！2'];
                        }
                    }
                } else { //从仓位入
                    $find_wafg_data = DB::table('warehouse_freight_goods')
                        ->where('wafg_ware_id', $find_stoc->stoc_ware_id)
                        ->where('wafg_class', $find_stoc->stoc_waon_class)
                        ->where('wafg_wago_id', $find_wago_data->wago_id)
                        ->where('wafg_wafr_id', $value['stgo_wafr_id'])
                        ->value('wafg_id');
                    if (empty($find_wafg_data)) {
                        return ['code' => 500, 'msg' => '当前仓位商品不存在', 'data' => '当前仓位不存在'];
                        $wafg_stock_number = true;
                    } else {
                        if ($value['stgo_stocktake_number'] != 0) { //商品锁定类型：1良品
                            // 仓位商品表增加库存
                            $wafg_stock_number = DB::table('warehouse_freight_goods')
                                ->where('wafg_ware_id', $find_stoc->stoc_ware_id)
                                ->where('wafg_class', $find_stoc->stoc_waon_class)
                                ->where('wafg_wago_id', $find_wago_data->wago_id)
                                ->where('wafg_wafr_id', $value['stgo_wafr_id'])
                                ->increment('wafg_stock_number', $value['stgo_stocktake_number']);

                            // 更改仓库商品表库存数量
                            $wago_edit_data['wago_stock_number'] = $find_wago_data->wago_stock_number + $value['stgo_stocktake_number'];
                            $wago_edit_data['wago_freight_stock_number'] = $find_wago_data->wago_freight_stock_number + $value['stgo_stocktake_number'];
                            $wago_edit_data['wago_update_time'] = date('Y-m-d H:i:s');
                            // 仓库商品表优先数量增加
                            $wago_stock_number = DB::table('warehouse_goods')
                                ->where('wago_ware_id', $find_stoc->stoc_ware_id)
                                ->where('wago_class', $find_stoc->stoc_waon_class)
                                ->where('wago_id', $find_wago_data->wago_id)
                                ->update($wago_edit_data);
                            unset($wago_edit_data);

                            // 仓位表良品数量增加
                            $wafr_lock_quantity_res = DB::table('warehouse_freight')
                                ->where('wafr_id', $value['stgo_wafr_id'])
                                ->where('wafr_ware_id', $find_stoc->stoc_ware_id)
                                ->increment('wafr_all_stock', $value['stgo_stocktake_number']);
                            if (!$wago_stock_number || !$wafg_stock_number || !$wafr_lock_quantity_res) {
                                return ['code' => 500, 'msg' => 'error', 'data' => '仓位数量盘库失败1'];
                            }
                        }

                        if ($value['stgo_priority_stocktake_number'] != 0) {
                            // 商品锁定类型：2优先
                            // 仓位商品表优先数量增加
                            $wafg_stock_number = DB::table('warehouse_freight_goods')
                                ->where('wafg_ware_id', $find_stoc->stoc_ware_id)
                                ->where('wafg_class', $find_stoc->stoc_waon_class)
                                ->where('wafg_wago_id', $find_wago_data->wago_id)
                                ->where('wafg_wafr_id', $value['stgo_wafr_id'])
                                ->increment('wafg_priority_stock_number', $value['stgo_priority_stocktake_number']);

                            // 更改仓库商品表库存数量
                            $wago_edit_data['wago_priority_stock_number'] = $find_wago_data->wago_priority_stock_number + $value['stgo_priority_stocktake_number'];
                            $wago_edit_data['wago_freight_priority_stock_number'] = $find_wago_data->wago_freight_priority_stock_number + $value['stgo_priority_stocktake_number'];
                            $wago_edit_data['wago_update_time'] = date('Y-m-d H:i:s');
                            // 仓库商品表优先数量增加
                            $wago_stock_number = DB::table('warehouse_goods')
                                ->where('wago_ware_id', $find_stoc->stoc_ware_id)
                                ->where('wago_class', $find_stoc->stoc_waon_class)
                                ->where('wago_id', $find_wago_data->wago_id)
                                ->update($wago_edit_data);
                            unset($wago_edit_data);

                            // 仓位表优先库存增加
                            $wafr_lock_quantity_res = DB::table('warehouse_freight')
                                ->where('wafr_id', $value['stgo_wafr_id'])
                                ->where('wafr_ware_id', $find_stoc->stoc_ware_id)
                                ->increment('wafr_priority_all_stock', $value['stgo_priority_stocktake_number']);

                            if (!$wago_stock_number || !$wafg_stock_number || !$wafr_lock_quantity_res) {
                                return ['code' => 500, 'msg' => 'error', 'data' => '仓位数量盘库失败2'];
                            }
                        }
                    }
                }
            }

            // 固定仓库增加仓位商品流水记录
            if ($ware_type == 1) {
                // 良品库存盘点
                if ($value['stgo_stocktake_number'] != 0) {
                    if ($value['stgo_stocktake_number'] > 0) {
                        $intype = 2; //出入库类型：1出库2入库
                    } else {
                        $intype = 1;
                    }
                    // 仓位入库记录
                    $outin_recore_res = Stocktake::junkaddition(
                        $user_info,
                        $find_stoc->stoc_ware_id, //仓库id
                        $find_stoc->stoc_waon_class, //仓库类型
                        $value['stgo_wafr_id'], //仓位id
                        7, //盘库
                        $request['stoc_id'], //原始单id
                        $find_stoc->stoc_storage_number, //原始单单号
                        $value['stgo_id'], //关联商品表主键id-盘库单商品表主键id
                        $value['stgo_goo_id'], //商品id
                        $intype, //出入库类型：1出库2入库
                        $value['stgo_stocktake_number'], //商品数量
                        1 //出库类型1良品2优先3待检测
                    );
                }

                // 优先库存盘点
                if ($value['stgo_priority_stocktake_number'] != 0) {
                    if ($value['stgo_priority_stocktake_number'] > 0) {
                        $intype = 2; //出入库类型：1出库2入库
                    } else {
                        $intype = 1;
                    }
                    // 仓位入库记录
                    $outin_recore_res = Stocktake::junkaddition(
                        $user_info,
                        $find_stoc->stoc_ware_id, //仓库id
                        $find_stoc->stoc_waon_class, //仓库类型
                        $value['stgo_wafr_id'], //仓位id
                        7, //盘库
                        $request['stoc_id'], //原始单id
                        $find_stoc->stoc_storage_number, //原始单单号
                        $value['stgo_id'], //关联商品表主键id-盘库单商品表主键id
                        $value['stgo_goo_id'], //商品id
                        $intype, //出入库类型：1出库2入库
                        $value['stgo_priority_stocktake_number'], //商品数量
                        2 //出库类型1良品2优先3待检测
                    );
                }
            }

            // 良品库存盘点
            if ($value['stgo_stocktake_number'] != 0) {
                $diff_stock_amount = $diff_stock_amount + $value['stgo_stocktake_number'];

                // 仓库流水记录使用数组
                if (isset($diff_stock_goo_number[$value['stgo_goo_id']])) {
                    $diff_stock_goo_number[$value['stgo_goo_id']] += $value['stgo_stocktake_number'];
                } else {
                    $diff_stock_goo_number[$value['stgo_goo_id']] = $value['stgo_stocktake_number'];
                }
            }

            // 优先库存盘点
            if ($value['stgo_priority_stocktake_number'] != 0) {
                $diff_priority_amount = $diff_priority_amount + $value['stgo_priority_stocktake_number'];

                // 仓库流水记录使用数组
                if (isset($diff_priority_goo_number[$value['stgo_goo_id']])) {
                    $diff_priority_goo_number[$value['stgo_goo_id']] += $value['stgo_priority_stocktake_number'];
                } else {
                    $diff_priority_goo_number[$value['stgo_goo_id']] = $value['stgo_priority_stocktake_number'];
                }
            }

            $diff_ware_amount = $diff_ware_amount + $value['stgo_stocktake_number'] + $value['stgo_priority_stocktake_number'];
        }

        // 仓库良品、优先总库存盘库
        $waon_edit_data['waon_stock_fine_amount'] = $find_waon_data->waon_stock_fine_amount + $diff_stock_amount;
        $waon_edit_data['waon_stock_priority_amount'] = $find_waon_data->waon_stock_priority_amount + $diff_priority_amount;
        $waon_edit_data['waon_update_time'] = date('Y-m-d H:i:s');
        $waon_edit_res = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $find_stoc->stoc_ware_id)
            ->where('waon_class', $find_stoc->stoc_waon_class)
            ->update($waon_edit_data);
        unset($waon_edit_data);
        if (!$waon_edit_res) {
            return ['code' => 500, 'msg' => 'error', 'data' => '仓库总数量盘库失败'];
        }

        if ($diff_ware_amount) {
            // 仓库类别表总库存数量加上 差值数量
            $warehouse_onhand_sql = 'UPDATE `faster_warehouse_onhand` SET  `waon_all_amount`= `waon_all_amount`+' . $diff_ware_amount . ',  `waon_update_time`= "' . date('Y-m-d H:i:s') . '"  WHERE  `waon_id` = ' . $find_waon_data->waon_id;
            $waon_res = DB::update($warehouse_onhand_sql);
        } else {
            $waon_res = true;
        }

        $find_waon_data = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $find_stoc->stoc_ware_id)
            ->where('waon_class', $find_stoc->stoc_waon_class)
            ->select('waon_id', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount')
            ->first();

        // 良品库存盘点
        if (!empty($diff_stock_goo_number)) {
            $out_goo_id = []; //出库
            $out_goo_number = []; //出库
            $out_goo_inventory = []; //出库

            $diff_stock_amount_out = 0; //盘库良品差异数量
            $diff_stock_amount_in = 0; //盘库良品差异数量

            $in_goo_id = []; //入库
            $in_goo_number = []; //入库
            $in_goo_inventory = []; //入库
            foreach ($diff_stock_goo_number as $key => $value) {
                if ($value > 0) {
                    $diff_stock_amount_in += abs($value);
                    $in_goo_number[$key] = abs($value);
                    $in_goo_id[$key] = $key;
                    $in_goo_inventory[$key] = 1;
                } else if ($value < 0) {
                    $diff_stock_amount_out += abs($value);
                    $out_goo_number[$key] = abs($value);
                    $out_goo_id[$key] = $key;
                    $out_goo_inventory[$key] = 1;
                }
            }
            if (!empty($out_goo_number)) {
                $outware = $find_stoc->stoc_ware_id; //仓库id
                $inware = 0; //入库仓库id
                $intype = 1; //出入库类型：1出库2入库
                $outtype = 2; //操作类型：1锁定库存2出库3入库4调货5发货

                // 3.生成出出库记录
                $oure_data = OutinRecord::addition(
                    $user_info, //用户信息
                    $find_stoc->stoc_id, //原始单的关联id
                    $find_stoc->stoc_storage_number, //原始单的关联单号
                    8, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后8盘库单
                    5, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单5盘库单
                    0, //选择的客户id,会员id/单位id
                    $find_stoc->stoc_storage_number, //原始单号
                    $inware, //入库仓库id
                    $outware, //出库仓库id
                    $diff_stock_amount_out, //出库的商品总量
                    15, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单15盘库单
                    $outtype, //操作类型：1锁定库存2出库3入库4调货5发货
                    $find_waon_data->waon_stock_fine_amount, //良品总库存
                    $find_waon_data->waon_lock_fine_amount, //良品锁定数量
                    $find_waon_data->waon_stock_priority_amount, //优先总库存
                    $find_waon_data->waon_lock_priority_amount, //优先锁定数量
                    $find_waon_data->waon_stock_unchecked_amount, //待检测总库存
                    $intype, //出入库类型：1出库，2入库
                    $find_stoc->stoc_waon_class, //[仓库类别]
                    $out_goo_id, //数组，商品id
                    $out_goo_number, //数组，商品数量
                    $out_goo_inventory //数组，出库类型1良品2优先3待检测
                );
                if (!$oure_data) {
                    return ['code' => 500, 'msg' => 'error', 'data' => '出入库记录保存失败！1'];
                }
            }

            if (!empty($in_goo_number)) {
                $intype = 2; //出入库类型：1出库2入库
                $outtype = 3; //操作类型：1锁定库存2出库3入库4调货5发货
                $outware = 0; //出库仓库id
                $inware = $find_stoc->stoc_ware_id; //仓库id
                // 3.生成出出库记录
                $oure_data = OutinRecord::addition(
                    $user_info, //用户信息
                    $find_stoc->stoc_id, //原始单的关联id
                    $find_stoc->stoc_storage_number, //原始单的关联单号
                    8, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后8盘库单
                    5, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单5盘库单
                    0, //选择的客户id,会员id/单位id
                    $find_stoc->stoc_storage_number, //原始单号
                    $inware, //入库仓库id
                    $outware, //出库仓库id
                    $diff_stock_amount_in, //出库的商品总量
                    15, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单15盘库单
                    $outtype, //操作类型：1锁定库存2出库3入库4调货5发货
                    $find_waon_data->waon_stock_fine_amount, //良品总库存
                    $find_waon_data->waon_lock_fine_amount, //良品锁定数量
                    $find_waon_data->waon_stock_priority_amount, //优先总库存
                    $find_waon_data->waon_lock_priority_amount, //优先锁定数量
                    $find_waon_data->waon_stock_unchecked_amount, //待检测总库存
                    $intype, //出入库类型：1出库，2入库
                    $find_stoc->stoc_waon_class, //[仓库类别]
                    $in_goo_id, //数组，商品id
                    $in_goo_number, //数组，商品数量
                    $in_goo_inventory //数组，出库类型1良品2优先3待检测
                );
                if (!$oure_data) {
                    return ['code' => 500, 'msg' => 'error', 'data' => '出入库记录保存失败！2'];
                }
            }

            unset($out_goo_id);
            unset($out_goo_number);
            unset($out_goo_inventory);
            unset($in_goo_id);
            unset($in_goo_number);
            unset($in_goo_inventory);
        }

        // 优先库存盘点
        if (!empty($diff_priority_goo_number)) {
            $out_goo_id = []; //出库
            $out_goo_number = []; //出库
            $out_goo_inventory = []; //出库

            $in_goo_id = []; //入库
            $in_goo_number = []; //入库
            $in_goo_inventory = []; //入库


            $diff_priority_amount_out = 0; //盘库良品差异数量
            $diff_priority_amount_in = 0; //盘库良品差异数量

            foreach ($diff_priority_goo_number as $key => $value) {
                if ($value > 0) {
                    $diff_priority_amount_in += abs($value);
                    $in_goo_number[$key] = abs($value);
                    $in_goo_id[$key] = $key;
                    $in_goo_inventory[$key] = 2;
                } else if ($value < 0) {
                    $diff_priority_amount_out += abs($value);
                    $out_goo_number[$key] = abs($value);
                    $out_goo_id[$key] = $key;
                    $out_goo_inventory[$key] = 2;
                }
            }

            if (!empty($out_goo_number)) {
                $inware = 0; //入库仓库id
                $intype = 1; //出入库类型：1出库2入库
                $outtype = 2; //操作类型：1锁定库存2出库3入库4调货5发货
                $outware = $find_stoc->stoc_ware_id; //仓库id

                // 3.生成出出库记录
                $oure_data = OutinRecord::addition(
                    $user_info, //用户信息
                    $find_stoc->stoc_id, //原始单的关联id
                    $find_stoc->stoc_storage_number, //原始单的关联单号
                    8, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后8盘库单
                    5, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单5盘库单
                    0, //选择的客户id,会员id/单位id
                    $find_stoc->stoc_storage_number, //原始单号
                    $inware, //入库仓库id
                    $outware, //出库仓库id
                    $diff_priority_amount_out, //出库的商品总量
                    15, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单15盘库单
                    $outtype, //操作类型：1锁定库存2出库3入库4调货5发货
                    $find_waon_data->waon_stock_fine_amount, //良品总库存
                    $find_waon_data->waon_lock_fine_amount, //良品锁定数量
                    $find_waon_data->waon_stock_priority_amount, //优先总库存
                    $find_waon_data->waon_lock_priority_amount, //优先锁定数量
                    $find_waon_data->waon_stock_unchecked_amount, //待检测总库存
                    $intype, //出入库类型：1出库，2入库
                    $find_stoc->stoc_waon_class, //[仓库类别]
                    $out_goo_id, //数组，商品id
                    $out_goo_number, //数组，商品数量
                    $out_goo_inventory //数组，出库类型1良品2优先3待检测
                );
                unset($out_goo_id);
                unset($out_goo_number);
                unset($out_goo_inventory);
                if (!$oure_data) {
                    return ['code' => 500, 'msg' => 'error', 'data' => '出入库记录保存失败！3'];
                }
            }

            if (!empty($in_goo_number)) {
                $intype = 2; //出入库类型：1出库2入库
                $outtype = 3; //操作类型：1锁定库存2出库3入库4调货5发货
                $outware = 0; //出库仓库id
                $inware = $find_stoc->stoc_ware_id; //仓库id

                // 3.生成出出库记录
                $oure_data = OutinRecord::addition(
                    $user_info, //用户信息
                    $find_stoc->stoc_id, //原始单的关联id
                    $find_stoc->stoc_storage_number, //原始单的关联单号
                    8, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后8盘库单
                    5, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单5盘库单
                    0, //选择的客户id,会员id/单位id
                    $find_stoc->stoc_storage_number, //原始单号
                    $inware, //入库仓库id
                    $outware, //出库仓库id
                    $diff_priority_amount_in, //出库的商品总量
                    15, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单15盘库单
                    $outtype, //操作类型：1锁定库存2出库3入库4调货5发货
                    $find_waon_data->waon_stock_fine_amount, //良品总库存
                    $find_waon_data->waon_lock_fine_amount, //良品锁定数量
                    $find_waon_data->waon_stock_priority_amount, //优先总库存
                    $find_waon_data->waon_lock_priority_amount, //优先锁定数量
                    $find_waon_data->waon_stock_unchecked_amount, //待检测总库存
                    $intype, //出入库类型：1出库，2入库
                    $find_stoc->stoc_waon_class, //[仓库类别]
                    $in_goo_id, //数组，商品id
                    $in_goo_number, //数组，商品数量
                    $in_goo_inventory //数组，出库类型1良品2优先3待检测
                );
                unset($in_goo_id);
                unset($in_goo_number);
                unset($in_goo_inventory);
                if (!$oure_data) {
                    return ['code' => 500, 'msg' => 'error', 'data' => '出入库记录保存失败！4'];
                }
            }
        }

        $cost_price = 0;
        $find_stgo_data = DB::table('stocktake_goods')
            ->where('stgo_stoc_id', $find_stoc->stoc_id)
            ->where(function ($query) use ($request) {
                $query->where('stgo_stocktake_number', '!=', 0)
                    ->orWhere('stgo_priority_stocktake_number', '!=', 0)
                    ->orWhere('stgo_unchecked_stocktake_number', '!=', 0);
            })
            ->select('stgo_id', 'stgo_goo_id', 'stgo_stock_number', 'stgo_stocktake_number', 'stgo_priority_stock_number', 'stgo_unchecked_stock_number', 'stgo_priority_stocktake_number', 'stgo_unchecked_stocktake_number', 'stgo_wafr_id')
            ->get()->toArray();
        $find_stgo_data = json_decode(json_encode($find_stgo_data), true);
        foreach ($find_stgo_data as $kkkk => $vvvv) {
            // 获取当前月份的成本价
            $find_ense_data = DB::table('enters_sells_saves')
                ->where('ense_goo_id', $vvvv['stgo_goo_id'])
                ->where('ense_goo_warehouse', $find_stoc->stoc_ware_id)
                ->where('ense_goo_waretype', $find_stoc->stoc_waon_class)
                ->where('ense_order_number', $find_stoc->stoc_storage_number)
                ->orderBy('ense_id', 'desc')
                ->select('ense_new_price', 'ense_out_in', 'ense_in_num', 'ense_out_num')
                ->get()->toArray();
            if (!empty($find_ense_data)) {
                foreach ($find_ense_data as $keys => $values) {
                    if ($values->ense_new_price) {
                        $find_ense_new_price = sprintf('%.2f', $values->ense_new_price);
                    } else {
                        $find_ense_new_price = 0;
                    }
                    if ($values->ense_out_in == 1) { //出库
                        $cost_price += $find_ense_new_price * $values->ense_out_num * (-1);
                    } elseif ($values->ense_out_in == 2) { //入库
                        $cost_price += $find_ense_new_price * $values->ense_in_num;
                    }
                }
            }
        }
        // 凭证单据报表
        // 判断凭证单据是否存在
        $vore_id = DB::table('voucher_receipts')
            ->where('vore_cid', $user_info->adm_cid)
            ->where('vore_shop_id', $user_info->adm_shop_id)
            ->where('vore_ord_id', $request['stoc_id'])
            ->where('vore_ord_number', $find_stoc->stoc_storage_number)
            ->where('vore_order_type', 6)
            ->where('vore_state', 1)
            ->select('vore_id', 'vore_wor_id', 'vore_wor_number')
            ->first();
        if ($find_stoc->stoc_waon_class != 4) {
            if ($cost_price != 0) {
                $vore_data['vore_cid'] = $user_info->adm_cid; //公司id
                $vore_data['vore_superior_shop_id'] = $user_info->shop_superior_id; //总店id
                $vore_data['vore_shop_id'] = $user_info->adm_shop_id; //门店id
                $vore_data['vore_create_id'] = $user_info->adm_id; //创建人
                $vore_data['vore_order_type'] = 6; //单号类型1.订单2.工单3.采购单4.销售单5.采购退货单6.盘库单
                $vore_data['vore_wor_id'] = ''; //工单id
                $vore_data['vore_wor_number'] = ''; //工单单号
                $vore_data['vore_ord_id'] = $find_stoc->stoc_id; //订单id
                $vore_data['vore_ord_number'] = $find_stoc->stoc_storage_number; //订单单号
                $vore_data['vore_plus_minus'] = 1; //金额正负1正值2负值
                $vore_data['vore_actual_price'] = abs($cost_price); //结算金额
                $vore_data['vore_collection_price'] = 0; //代收金额
                $vore_data['vore_recycle_price'] = 0; //回收金额
                $vore_data['vore_early_costing'] = 0; //成本
                $vore_data['vore_type'] = ''; //单位类型1会员零售2客户单位3速电派单
                $vore_data['vore_client_id'] = ''; //客户单位/客户id
                $vore_data['vore_channel_unit'] = '';
                $vore_data['vore_create_time'] = $find_stoc->stoc_create_time;
                $vore_id = DB::table('voucher_receipts')->insertGetId($vore_data);
            } else {
                $vore_id = true;
            }
            // 凭证借贷表(结算金额)
            if ($cost_price > 0) { //金额盘盈
                $volo_data[0]['volo_shop_id'] = $user_info->adm_shop_id;
                $volo_data[0]['volo_vore_id'] = $vore_id;
                $volo_data[0]['volo_type'] = 1; //类型1借方2贷方
                $volo_data[0]['volo_borrow_subject'] = '140501'; //借方科目
                $volo_data[0]['volo_borrow_subject_name'] = '库存商品'; //借方科目名称
                $volo_data[0]['volo_borrow_price'] = abs($cost_price); //借方金额
                $volo_data[0]['volo_loan_subject'] = '190101'; //贷方科目
                $volo_data[0]['volo_loan_subject_name'] = '待处理财产损溢'; //贷方科目名称
                $volo_data[0]['volo_loan_price'] = abs($cost_price); //贷方金额
                $volo_data[0]['volo_update_time'] = $find_stoc->stoc_create_time; //更新时间
                $volo_id = DB::table('voucher_loan')->insert($volo_data);
            } elseif ($cost_price < 0) { //金额盘亏
                $volo_data[0]['volo_shop_id'] = $user_info->adm_shop_id;
                $volo_data[0]['volo_vore_id'] = $vore_id;
                $volo_data[0]['volo_type'] = 1; //类型1借方2贷方
                $volo_data[0]['volo_borrow_subject'] = '190101'; //借方科目
                $volo_data[0]['volo_borrow_subject_name'] = '待处理财产损溢'; //借方科目名称
                $volo_data[0]['volo_borrow_price'] = abs($cost_price); //借方金额
                $volo_data[0]['volo_loan_subject'] = '140501'; //贷方科目
                $volo_data[0]['volo_loan_subject_name'] = '库存商品'; //贷方科目名称
                $volo_data[0]['volo_loan_price'] = abs($cost_price); //贷方金额
                $volo_data[0]['volo_update_time'] = $find_stoc->stoc_create_time; //更新时间
                $volo_id = DB::table('voucher_loan')->insert($volo_data);
            } elseif ($cost_price == 0) {
                $vore_id = true;
                $volo_id = true;
            }
        } else {
            $vore_id = true;
            $volo_id = true;
        }
        if ($stoc_res && $waon_res && $vore_id && $volo_id) {
            // 查询品牌公司表，与门店存在补货关系的品牌
            $find_brco_bra_id = DB::table('shop_relevance as b')
                ->leftJoin('branded_company as a', 'a.brco_company_ditc_id', '=', 'b.shre_company_ditc_id')
                ->where('brco_restock_state', 2) //品牌方补货状态1没有补货关系2有补货关系
                ->where('brco_delete', 1)
                ->where('shre_relevance_type', 2) //关联系统类型1速电系统2供应链系统
                ->where('shre_state', 2) //状态1已绑定未确定状态2已绑定已确定
                ->where('shre_delete', 1) //删除状态1正常2删除
                ->where('shre_shop_id', $user_info->adm_shop_id)
                ->value('brco_bra_id');
            // 根据门店id查询门店来源标识：1门店系统2半径小供应链3冠军供应链4中凯供应链
            $shop_source_identify = DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->value('shop_source_identify');
            if (config('apisystem.GYL_STATE') && $shop_source_identify == 3) {
                // 2. 查询要盘点的商品数量
                $stocktake_goods = DB::table('stocktake_goods as stgo')
                    ->leftjoin('goods as goo', 'goo.goo_id', '=', 'stgo.stgo_goo_id')
                    ->where('stgo_stoc_id', $find_stoc->stoc_id); //盘库单id
                if ($find_brco_bra_id) {
                    // 判断门店是否有品牌，有，就用自己设置的品牌
                    $stocktake_goods = $stocktake_goods->where('goo_bra_id', $find_brco_bra_id); //搜索品牌;
                } else {
                    // 判断门店是否有品牌，无，就用冠军的品牌
                    $stocktake_goods = $stocktake_goods->where('goo_bra_id', config('apisystem.champion_bra_id')); //搜索冠军品牌;
                }
                $stocktake_goods = $stocktake_goods
                    ->where('goo_class', 2) //类型：2系统商品
                    ->where(function ($query) use ($user_info) {
                        $query->where('stgo_stocktake_number', '!=', 0)
                            ->orWhere('stgo_priority_stocktake_number', '!=', 0)
                            ->orWhere('stgo_unchecked_stocktake_number', '!=', 0);
                    })
                    ->select('stgo_id', 'stgo_goo_id', 'stgo_stocktake_number', 'stgo_priority_stocktake_number', 'stgo_unchecked_stocktake_number', 'goo_goods_encode')
                    ->get()->toArray();
                $stocktake_goods = json_decode(json_encode($stocktake_goods), true);
                if (!empty($stocktake_goods)) {
                    foreach ($stocktake_goods as $key => $value) {
                        // 库存相关数据同步
                        $temp_goods_data['stgo_goods_encode'] = $value['goo_goods_encode']; //商品编码
                        $temp_goods_data['stgo_stock_quantity'] = $value['stgo_stocktake_number'] + $value['stgo_priority_stocktake_number'] + $value['stgo_unchecked_stocktake_number']; //当前结余库存
                        $return_goods_data[] = $temp_goods_data;
                        unset($temp_goods_data);
                    }
                    // 查询统计品牌方门店补货商品库存
                    // 查询品牌公司表，与门店存在补货关系的品牌
                    $find_company_shop = DB::table('shop_relevance as b')
                        ->leftJoin('branded_company as a', 'a.brco_company_ditc_id', '=', 'b.shre_company_ditc_id')
                        ->where('shre_shop_id', $user_info->adm_shop_id) //门店id
                        ->where('brco_restock_state', 2) //品牌方补货状态1没有补货关系2有补货关系
                        ->where('brco_delete', 1)
                        ->where('shre_relevance_type', 2) //关联系统类型1速电系统2供应链系统
                        ->where('shre_state', 2) //状态1已绑定未确定状态2已绑定已确定
                        ->where('shre_delete', 1) //删除状态1正常2删除
                        ->select('brco_company_ditc_id', 'shre_relevance_shop_id')
                        ->first();
                    // 同步库存到供应链
                    $url = config('urlsystem.GYL_URL_PREFIX') . '/v1/RestockList/syncOperateRestockStock';
                    $add_data['stock_type'] = 1; //类型：1入库2出库
                    $add_data['shop_ditc_id'] = $find_company_shop->shre_relevance_shop_id; //门店对应的渠道id
                    $add_data['brand_ditc_id'] = $find_company_shop->brco_company_ditc_id; //相关品牌渠道id
                    $add_data['stock_data'] = $return_goods_data; //商品库存数据
                    $add_data['time'] = date('Y-m-d H:i:s'); //收货时间
                    $request_return = Common::doPost($add_data, $url, 2);
                    $request_return = json_decode($request_return);
                    if ($request_return->code != 200) {
                        return ['code' => 500, 'msg' => $request_return->msg, 'data' => $request_return->msg];
                    }
                }
            }
            $stock = new StocktakeController;
            //盘库单入库修改商品单价和总价
            $amount_ret = $stock->updateWagoAmountStocktake($request['stoc_id']);
            if($amount_ret['code'] != 200){
                return ['code'=>500, 'msg'=>'盘库单通过失败011', 'data'=>'盘库单通过失败011'];
            }
            return ['code' => 200, 'msg' => '盘库成功', 'data' => ''];
        } else {
            return ['code' => 500, 'msg' => '盘库失败', 'data' => ''];
        }
    }

    /**
     * @name  列表页
     * @param action_name  控制器名
     * @param Request $request
     * @return mixed
     */
    public function allIndex (Request $request)
    {
        $input = $request->all();
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $data = DeliveryService::allIndex($user_info,$input);
        return response()->json($data);
    }

    //给发货单添加快递信息
    public function deliveryList(Request $request)
    {
        $input = $request->all();
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $data = DeliveryService::deliveryList($user_info,$input);
        return response()->json($data);
    }

    //给发货单添加快递信息
    public function deliveryEdit(Request $request)
    {
        $input = $request->all();
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $data = DeliveryService::editDelivery($user_info,$input);
        return response()->json($data);
    }
}
