<?php

namespace App\Http\Controllers\Api\WarehouseManage;

use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\WarehouseManage\VerifyStocktakeController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Api\WarehouseManage\Stocktake;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use App\Services\Business\WashOrderBasicService;

// 仓储系统 -- 盘库单
class StocktakeController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;
    protected $show_counts = 100;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->adm_shop_id;
        $page_size  = (int) $request->input('show_count', 10);
        $search_data = $request->all();
        $list_data = DB::table('stocktake as a')
            ->leftJoin('admin as b', 'b.adm_id', '=', 'a.stoc_adm_id')
            ->leftJoin('warehouse as c', 'c.ware_id', '=', 'a.stoc_ware_id')
            ->where('stoc_cid', $user_info->adm_cid)
            ->where('stoc_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_name'])) {
                    $query->where('b.adm_name', 'like', '%' . $search_data['adm_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['stoc_storage_number'])) {
                    $query->where('stoc_storage_number', 'like', '%' . $search_data['stoc_storage_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('stoc_make_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('stoc_make_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('stoc_make_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            }) //创建时间/派单时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['stoc_type'])) {
                    $query->where('stoc_type', $search_data['stoc_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['stoc_state'])) {
                    $query->where('stoc_state', $search_data['stoc_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['stoc_ware_id'])) {
                    $query->where('stoc_ware_id', $search_data['stoc_ware_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['stoc_waon_class'])) {
                    $query->where('stoc_waon_class', $search_data['stoc_waon_class']);
                }
            })
            ->select('stoc_id', 'stoc_storage_number', 'stoc_type', 'stoc_differ_number', 'stoc_state', 'stoc_remark', 'stoc_make_time', 'adm_name', 'ware_name', 'stoc_manner', 'stoc_waon_class')
            ->orderBy('stoc_id', 'desc')
            ->paginate($page_size);
        // 查询门店打印模板
        $shpt_data = DB::table('shop_print_template')
            ->where('shpt_shop_id', $user_info->adm_shop_id)
            ->whereIn('shpt_print_type', [12])
            ->where('shpt_delete', 1)
            ->select('shpt_id', 'shpt_print_type', 'shpt_isdefault')
            ->get()->toArray();
        if (empty($shpt_data)) {
            $shpt_data = [];
        }

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据
        $data_info['shpt_data'] = $shpt_data;                   //模板id

        //获取每一个单子的盘盈和盘亏
        $stoc_id_arr = [];
        foreach ($data_info['data'] as $key => $value){
            $stoc_id_arr[] = $value->stoc_id;
        }
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if(!empty($stoc_id_arr)){
            $detail_list_data = DB::table('stocktake_goods')
                ->whereIn('stgo_stoc_id', $stoc_id_arr)
                ->select('stgo_stoc_id', 'stgo_goo_id', 'stgo_stock_number', 'stgo_stocktake_number')
                ->get()->toArray();
            foreach ($detail_list_data as $k => $v){
                if(!isset($diff_arr[$v->stgo_stoc_id]['stoc_differ_profit'])){
                    $diff_arr[$v->stgo_stoc_id]['stoc_differ_profit'] = 0;//盘盈
                }
                if(!isset($diff_arr[$v->stgo_stoc_id]['stoc_differ_loss'])){
                    $diff_arr[$v->stgo_stoc_id]['stoc_differ_loss'] = 0;//盘亏
                }
                if($v->stgo_stocktake_number > 0){
                    $diff_arr[$v->stgo_stoc_id]['stoc_differ_profit'] += $v->stgo_stocktake_number;
                }else if($v->stgo_stocktake_number < 0){
                    $diff_arr[$v->stgo_stoc_id]['stoc_differ_loss'] += $v->stgo_stocktake_number;
                }
            }
            $data_info['data'] = json_decode(json_encode($data_info['data']), true);
            foreach ($data_info['data'] as $r_k => $r_v){
                $data_info['data'][$r_k]['stoc_differ_profit'] = $diff_arr[$r_v['stoc_id']]['stoc_differ_profit'];//盘盈
                $data_info['data'][$r_k]['stoc_differ_loss'] = str_replace("-",'',$diff_arr[$r_v['stoc_id']]['stoc_differ_loss']);//盘亏

                $buttonData = [];
                if($r_v['stoc_state'] == 1 || $r_v['stoc_state'] == 4){
                    $buttonData[] = 'edit';//编辑
                }
                if($r_v['stoc_state'] == 2){
                    $buttonData[] = 'pass';//通过
                }
                if($r_v['stoc_state'] == 2){
                    $buttonData[] = 'reject';//驳回
                }
                $buttonData[] = 'info';//详情
                $buttonData[] = 'print';//打印
                if($r_v['stoc_state'] != 3){
                    $buttonData[] = 'delete';//删除
                }
                $button = CommonService::getListButton($buttonData,$list_button);
                $data_info['data'][$r_k]['button_one'] = $button['button_one']??[];
                $data_info['data'][$r_k]['button_two'] = $button['button_two']??[];
                $data_info['data'][$r_k]['button_three'] = $button['button_three']??[];
            }
        }

        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info, 'list_button' => $list_button]);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '暂无数据']);
        }
    }

    // 详情
    public function info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->submitValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 盘库单数据
        $find_stoc = DB::table('stocktake as a')
            ->leftJoin('admin as b', 'b.adm_id', '=', 'a.stoc_adm_id')
            ->leftJoin('warehouse as c', 'c.ware_id', '=', 'a.stoc_ware_id')
            ->where('stoc_id', $request['stoc_id'])
            ->select('adm_name', 'ware_name', 'stoc_make_time', 'stoc_state', 'stoc_type', 'stoc_storage_number', 'stoc_differ_number', 'stoc_ware_id', 'stoc_waon_class', 'ware_type')
            ->first();
        // 获取盘库商品数据
        $find_goods = DB::table('stocktake_goods as a')
            ->leftJoin('goods as b', 'a.stgo_goo_id', '=', 'b.goo_id')
            ->where('stgo_stoc_id', $request['stoc_id'])
            ->select('stgo_stock_number', 'stgo_lock_number', 'stgo_stocktake_number', 'goo_class', 'goo_bra_name', 'goo_brse_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'stgo_priority_stock_number', 'stgo_priority_lock_number', 'stgo_unchecked_stock_number', 'stgo_priority_stocktake_number', 'stgo_unchecked_stocktake_number', 'goo_class', 'goo_id', 'stgo_wafr_id', 'stgo_goo_id', 'goo_unit', 'goo_unta_id')
            ->get();
        $data['stoc_data'] = $find_stoc;
        $find_goods = json_decode(json_encode($find_goods), true);
        // 查询系列数据
        $goo_brse_id = array_column($find_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        $goo_id = array_column($find_goods, 'goo_id');
        // 查询商品附属表信息
        $gosu_data = DB::table('goods_subsidiary')
            ->where('gosu_shop_id', $user_info->adm_shop_id)
            ->whereIn('gosu_goo_id', $goo_id)
            ->pluck('gosu_another_name', 'gosu_goo_id')
            ->toArray();
        // 查询仓位名称信息
        $stgo_wafr_id = array_column($find_goods, 'stgo_wafr_id');
        $find_wafr_data = DB::table('warehouse_freight')
            ->where('wafr_shop_id', $user_info->adm_shop_id)
            ->whereIn('wafr_id', $stgo_wafr_id)
            ->where('wafr_delete', 1)
            ->pluck('wafr_name', 'wafr_id')
            ->toArray();
        foreach ($find_goods as $k => $v) {
            if (isset($gosu_data[$v['goo_id']]) && !empty($gosu_data[$v['goo_id']])) { //商品别名
                $find_goods[$k]['goo_name'] = $gosu_data[$v['goo_id']];
            }
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP')) && isset($brse_data[$v['goo_brse_id']])) {
                if (!empty($v['goo_brse_id'])) {
                    if ($v['goo_class'] == 2) {
                        $find_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $find_goods[$k]['goo_name'];
                        unset($find_goods[$k]['goo_brse_id']);
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $find_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $find_goods[$k]['goo_name'];
                            unset($find_goods[$k]['goo_brse_id']);
                        }
                    }
                }
            }
            // 显示品牌名称
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                if ($v['goo_class'] == 2) {
                    $find_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $find_goods[$k]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $find_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $find_goods[$k]['goo_name'];
                    }
                }
            }
            // 盘前数量
            $find_goods[$k]['stgo_stock_number'] = $v['stgo_stock_number'] + $v['stgo_lock_number'];
            $find_goods[$k]['stgo_priority_stock_number'] = $v['stgo_priority_stock_number'] + $v['stgo_priority_lock_number'];
            $find_goods[$k]['stgo_unchecked_stock_number'] = $v['stgo_unchecked_stock_number'];
            // 盘后数量
            $find_goods[$k]['stgo_stocktake_number'] = $v['stgo_stock_number'] + $v['stgo_lock_number'] + $v['stgo_stocktake_number'];
            $find_goods[$k]['stgo_priority_stocktake_number'] = $v['stgo_priority_stocktake_number'] + $v['stgo_priority_stock_number'] + $v['stgo_priority_lock_number'];
            $find_goods[$k]['stgo_unchecked_stocktake_number'] = $v['stgo_unchecked_stocktake_number'] + $v['stgo_unchecked_stock_number'];
            //盘盈盘亏
            if($find_goods[$k]['stgo_stock_number'] == $find_goods[$k]['stgo_stocktake_number']){
                $find_goods[$k]['stoc_differ'] = '盘平';
                $find_goods[$k]['stoc_differ_number'] = '0';
            }else if($find_goods[$k]['stgo_stock_number'] > $find_goods[$k]['stgo_stocktake_number']){
                $find_goods[$k]['stoc_differ'] = '盘亏';
                $find_goods[$k]['stoc_differ_number'] = $find_goods[$k]['stgo_stock_number'] - $find_goods[$k]['stgo_stocktake_number'];
            }else if($find_goods[$k]['stgo_stock_number'] < $find_goods[$k]['stgo_stocktake_number']){
                $find_goods[$k]['stoc_differ'] = '盘盈';
                $find_goods[$k]['stoc_differ_number'] = $find_goods[$k]['stgo_stocktake_number'] - $find_goods[$k]['stgo_stock_number'];
            }
            // 仓位名称
            if (isset($find_wafr_data[$v['stgo_wafr_id']])) {
                $find_goods[$k]['wafr_name'] = $find_wafr_data[$v['stgo_wafr_id']];
            } else {
                $find_goods[$k]['wafr_name'] = '';
            }
            unset($find_goods[$k]['goo_class']);
        }
        $data['goods_data'] = $find_goods;
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    // 盘库方式: 通盘, 获取仓位所有的商品
    public function warehouseAllGoods(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->warehouseAllGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();

        // 查询仓库类型：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', $request['ware_id'])
            ->value('ware_type');

        // 系统版本：1门店版2运营中心版
        $shop_versions = 2;
        if ($shop_versions == 1 || $ware_type == 3) { //系统版本:1门店版或仓库类型为移动仓
            $list_data = DB::table('warehouse_goods as wg')
                ->leftjoin('goods as g', 'g.goo_id', '=', 'wg.wago_goo_id')
                ->where('wago_ware_id', $request['ware_id'])
                ->where('wago_class', $request['stoc_waon_class'])
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['bra_id'])) {
                        $query->where('goo_bra_id', $search_data['bra_id']);
                    }
                }) //品牌id
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['cate_id'])) {
                        $query->where('goo_cate_id', $search_data['cate_id']);
                    }
                }) //品类id
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_goods_encode'])) {
                        $query->where('goo_name', 'like', '%' . $search_data['goo_goods_encode'] . '%')
                            ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                    }
                }) //检索编码
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_brse_id'])) {
                        $query->where('goo_brse_id', $search_data['goo_brse_id']);
                    }
                }) //品牌系列id
                ->select('goo_name', 'goo_type', 'goo_goods_encode', 'wago_goo_id', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number', 'goo_bra_name', 'goo_brse_id', 'goo_class', 'goo_id', 'goo_unit');
            if (isset($request['page'])) {
                $list_data = $list_data->paginate($this->show_count);
                $find_wago['current_page'] = $list_data->currentPage();  //当前页面页码
                $find_wago['last_page'] = $list_data->lastPage();        //表示最后一页的页码
                $find_wago['total'] = $list_data->total();               //总数据个数
                $find_wago['current_number'] = $this->show_count;       //一页显示多少个
                $find_wago['data'] = $list_data->items();
            } else {
                $find_wago['data'] = $list_data->get()->toArray();
            }
        } else { //系统版本:2运营中心版
            $list_data = DB::table('warehouse_goods as wg')
                ->leftjoin('goods as g', 'g.goo_id', '=', 'wg.wago_goo_id')
                ->where('wago_ware_id', $request['ware_id'])
                ->where('wago_class', $request['stoc_waon_class'])
                ->where(function ($query) use ($search_data) { //品牌id
                    if (!empty($search_data['bra_id'])) {
                        $query->where('goo_bra_id', $search_data['bra_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //品类id
                    if (!empty($search_data['cate_id'])) {
                        $query->where('goo_cate_id', $search_data['cate_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //检索编码
                    if (!empty($search_data['goo_goods_encode'])) {
                        $query->where('goo_name', 'like', '%' . $search_data['goo_goods_encode'] . '%')
                            ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //品牌系列id
                    if (!empty($search_data['goo_brse_id'])) {
                        $query->where('goo_brse_id', $search_data['goo_brse_id']);
                    }
                })
                ->select('goo_name', 'goo_type', 'goo_goods_encode', 'wago_goo_id', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number', 'goo_bra_name', 'goo_brse_id', 'goo_class', 'goo_id', 'goo_unit');
            if (isset($request['page'])) {
                $list_data = $list_data->paginate($this->show_counts);
                $find_wago['current_page'] = $list_data->currentPage();  //当前页面页码
                $find_wago['last_page'] = $list_data->lastPage();        //表示最后一页的页码
                $find_wago['total'] = $list_data->total();               //总数据个数
                $find_wago['current_number'] = $this->show_counts;       //一页显示多少个
                $find_wago['data'] = $list_data->items();
            } else {
                $find_wago['data'] = $list_data->get()->toArray();
            }
        }

        $find_wago['data'] = json_decode(json_encode($find_wago['data']), true);
        // 查询系列数据
        $goo_brse_id = array_column($find_wago['data'], 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        $goo_id = array_column($find_wago['data'], 'goo_id');
        // 查询商品附属表信息
        $gosu_data = DB::table('goods_subsidiary')
            ->where('gosu_shop_id', $user_info->adm_shop_id)
            ->whereIn('gosu_goo_id', $goo_id)
            ->pluck('gosu_another_name', 'gosu_goo_id')
            ->toArray();
        foreach ($find_wago['data'] as $key => $value) {
            // 系列名称
            if (!empty($value['goo_brse_id']) && isset($brse_data[$value['goo_brse_id']])) {
                $find_wago['data'][$key]['brse_name'] = $brse_data[$value['goo_brse_id']];
            }
            if (isset($gosu_data[$value['goo_id']]) && !empty($gosu_data[$value['goo_id']])) { //商品别名
                $find_wago['data'][$key]['goo_name'] = $gosu_data[$value['goo_id']];
            }
            // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP')) && isset($brse_data[$value['goo_brse_id']])) {
                if (!empty($value['goo_brse_id'])) {
                    if ($value['goo_class'] == 2) {
                        $find_wago['data'][$key]['goo_name'] = $brse_data[$value['goo_brse_id']] . ' ' . $find_wago['data'][$key]['goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $find_wago['data'][$key]['goo_name'] = $brse_data[$value['goo_brse_id']] . ' ' . $find_wago['data'][$key]['goo_name'];
                        }
                    }
                }
            }
            // 显示品牌名称
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                if ($value['goo_class'] == 2) {
                    $find_wago['data'][$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $find_wago['data'][$key]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $find_wago['data'][$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $find_wago['data'][$key]['goo_name'];
                    }
                }
            }
            $find_wago['data'][$key]['goo_name'] = $value['goo_name'].'('.$value['goo_unit'].')';
            unset($find_wago['data'][$key]['goo_brse_id']);
            unset($find_wago['data'][$key]['goo_class']);
        }
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $find_wago]);
    }

    // 查询当前仓位商品库存数量【新增21.12.17】
    public function selectGoodsWarehouse(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();

        $list_data = DB::table('warehouse_freight_goods as wg')
            ->leftjoin('goods as g', 'g.goo_id', '=', 'wg.wafg_goo_id')
            ->leftjoin('warehouse_freight as wafr', 'wafr.wafr_id', '=', 'wg.wafg_wafr_id')
            ->where('wafg_ware_id', $request['ware_id'])
            ->where('wafg_class', $request['stoc_waon_class'])
            ->whereIn('wafg_goo_id', $request['goo_id'])

            ->select('goo_name', 'goo_goods_encode', 'wafg_goo_id as wago_goo_id', 'wafg_stock_number as wago_stock_number', 'wafg_lock_quantity as wago_lock_quantity', 'wafg_priority_lock_quantity as wago_priority_lock_quantity', 'wafg_priority_stock_number as wago_priority_stock_number', 'wafg_unchecked_stock_number as wago_unchecked_stock_number', 'goo_id', 'wafg_wafr_id', 'wafr_name', 'goo_unit');
        if (isset($request['page'])) {
            $list_data = $list_data->paginate($this->show_count);
            $find_wago['current_page'] = $list_data->currentPage();  //当前页面页码
            $find_wago['last_page'] = $list_data->lastPage();        //表示最后一页的页码
            $find_wago['total'] = $list_data->total();               //总数据个数
            $find_wago['current_number'] = $this->show_count;       //一页显示多少个
            $find_wago['data'] = $list_data->items();return 2;
        } else {
            $find_wago['data'] = $list_data->get()->toArray();
        }
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $find_wago]);
    }

    // 搜索商品
    public function searchGoods(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->searchGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        if (!empty($request['ware_id'])) {
            $search_data['goo_id'] = DB::table('warehouse_goods')
                ->where('wago_ware_id', $request['ware_id'])
                ->pluck('wago_goo_id')->toArray();
        }

        $search_data = $request->all();
        $list_data = DB::table('goods')
            ->where('goo_cid', $user_info->adm_cid)
            ->where('goo_superior_shop_id', $shop_id)
            ->where('goo_type', $request['goo_type'])
            ->where('goo_delete', 1)
            ->where('goo_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_id'])) {
                    $query->where('goo_id', $search_data['goo_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            })
            ->select('goo_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_price', 'goo_wholesale_price', 'goo_purchase_price', 'goo_class')
            ->orderBy('goo_goods_encode', 'asc')
            ->paginate($this->show_count);

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据
        $goo_id = array_column($data_info['data'], 'goo_id');
        // 查询商品附属表信息
        $gosu_data = DB::table('goods_subsidiary')
            ->where('gosu_shop_id', $user_info->adm_shop_id)
            ->whereIn('gosu_goo_id', $goo_id)
            ->pluck('gosu_another_name', 'gosu_goo_id')
            ->toArray();
        foreach ($data_info['data'] as $key => $value) {
            if (isset($gosu_data[$value->goo_id]) && !empty($gosu_data[$value->goo_id])) { //商品别名
                $data_info['data'][$key]->goaf_another_name = $gosu_data[$value->goo_id];
            }
            unset($data_info['data'][$key]->goo_class);
        }
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info]);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '暂无数据']);
        }
    }

    public function searchGoods2(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->searchGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $adm_cid = $user_info->adm_cid;
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        if (!empty($request['ware_id'])) {
            $search_data['goo_id'] = DB::table('warehouse_goods')
                ->where('wago_ware_id', $request['ware_id'])
                ->where(function ($query) use ($request) {
                    if (!empty($request['waon_class'])) {
                        $query->where('wago_class', $request['waon_class']);
                    }
                })
                ->pluck('wago_goo_id')->toArray();
        }
        $search_data = $request->all();
        if (!empty($request['waon_class'])) {
            if ($request['waon_class'] == 1) {
                $goo_type = 1;
            } elseif ($request['waon_class'] == 2) {
                $goo_type = 2;
            } elseif ($request['waon_class'] == 3) {
                $goo_type = 4;
            } else {
                $goo_type = 1;
            }
        } else {
            $goo_type = isset($request['goo_type']) ? $request['goo_type'] : 1;
        }
        $shop_state = true;
        if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
            $shop_state = false;
        }
        $list_data = DB::table('goods')
            ->where(function ($query) use ($adm_cid, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_cid', 0)
                        ->orwhere('goo_cid', $adm_cid);
                } else {
                    $query->where('goo_cid', $adm_cid);
                }
            })
            ->where(function ($query) use ($shop_id, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_shop_id', 0)
                        ->orwhere('goo_shop_id', $shop_id);
                } else {
                    $query->where('goo_shop_id', $shop_id);
                }
            })
            ->where('goo_type', $goo_type)
            ->where('goo_delete', 1)
            ->where('goo_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_id'])) {
                    $query->where('goo_id', $search_data['goo_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_class'])) {
                    $query->where('goo_class', $search_data['goo_class']);
                }
            }) //类型：1自营商品2系统商品
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            }) //品牌系列id
            ->select('goo_class', 'goo_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_price', 'goo_wholesale_price', 'goo_purchase_price', 'goo_unit', 'goo_brse_id', 'goo_bra_name')
            ->orderBy('goo_goods_encode', 'desc')
            ->paginate($this->show_count);

        $data = $list_data->items();
        $data = json_decode(json_encode($data), true);
        $goo_id = array_column($data, 'goo_id');
        // 查询商品附属表信息
        $gosu_data = DB::table('goods_subsidiary')
            ->where('gosu_shop_id', $shop_id)
            ->whereIn('gosu_goo_id', $goo_id)
            ->select('gosu_another_name', 'gosu_goo_id', 'gosu_wholesale_price')
            ->toArray();
        $gosu_data = array_column($gosu_data, null, 'gosu_goo_id');
        // 查询入库仓库的商品的预警值
        $wago_data = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['in_ware_id'])
            ->where('wago_class', $request['waon_class'])
            ->whereIn('wago_goo_id', $goo_id)
            ->pluck('wago_min_warn', 'wago_goo_id')
            ->toArray();
        foreach ($data as $key => $value) {
            if (isset($gosu_data[$value['goo_id']]) && !empty($gosu_data[$value['goo_id']])) { //商品别名
                if ($value['goo_class'] == 2) {
                    $data[$key]['goo_purchase_price'] = $gosu_data[$value['goo_id']]['gosu_wholesale_price'];
                }
                $data[$key]['goo_name'] = $gosu_data[$value['goo_id']]['gosu_another_name'];
            }
            if (isset($wago_data[$value['goo_id']])) { //仓库商品预警值
                $data[$key]['wago_min_warn'] = $wago_data[$value['goo_id']];
            } else {
                $data[$key]['wago_min_warn'] = 0;
            }
            unset($data[$key]['goo_class']);
        }
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $data;                //返回数据
        $data_info['brse_data'] = []; //品牌系列数据
        if ($data_info['data']) {
            // 查询品牌系列数据
            $goo_brse_id = array_filter(array_unique(array_column($data_info['data'], 'goo_brse_id')));
            if ($goo_brse_id) {
                $data_info['brse_data'] = DB::table('brand_serie')
                    ->whereIn('brse_id', $goo_brse_id)
                    ->select('brse_id', 'brse_name')
                    ->get();
            }
        }
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info]);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '暂无数据']);
        }
    }

    // 盘库方式: 部分盘库, 获取商品库存数量
    public function goodsStock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->goodsStockValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 系统版本：1门店版2运营中心版
        $shop_versions = 2;
        // 查询仓库类型：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', $request['ware_id'])
            ->value('ware_type');
        if ($shop_versions == 1 || $ware_type == 3) { //系统版本:1门店版
            $list_data = DB::table('warehouse_goods')
                ->where('wago_ware_id', $request['ware_id'])
                ->where('wago_goo_id', $request['goo_id'])
                ->where('wago_class', $request['waon_class'])
                ->select('wago_stock_amount as wago_stock_number', 'wago_lock_amount as wago_lock_quantity', 'wago_priority_stock_amount as wago_priority_stock_number', 'wago_priority_lock_amount as wago_priority_lock_quantity', 'wago_unchecked_stock_amount as wago_unchecked_stock_number')
                ->first();
        } else {
            $list_data = DB::table('warehouse_freight_goods')
                ->where('wafg_wafr_id', $request['wafr_id'])
                ->where('wafg_ware_id', $request['ware_id'])
                ->where('wafg_goo_id', $request['goo_id'])
                ->where('wafg_class', $request['waon_class'])
                ->select('wafg_stock_number as wago_stock_number', 'wafg_lock_quantity as wago_lock_quantity', 'wafg_priority_stock_number as wago_priority_stock_number', 'wafg_priority_lock_quantity as wago_priority_lock_quantity', 'wafg_unchecked_stock_number as wago_unchecked_stock_number')
                ->first();
        }
        $data['wago_stock_number'] = $list_data ? $list_data->wago_stock_number : 0;    //良品库存数量
        $data['wago_lock_quantity'] = $list_data ? $list_data->wago_lock_quantity : 0;    //良品锁定数量
        $data['wago_priority_stock_number'] = $list_data ? $list_data->wago_priority_stock_number : 0;  //优先库存数量
        $data['wago_priority_lock_quantity'] = $list_data ? $list_data->wago_priority_lock_quantity : 0;    //优先锁定数量
        $data['wago_unchecked_stock_number'] = $list_data ? $list_data->wago_unchecked_stock_number : 0;    //待检测数量
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    // 获取盘点仓库信息
    public function warehouseInfo(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $list_data = DB::table('warehouse')
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_superior_shop_id', $shop_id)
            ->where('ware_type', 1)
            ->where('ware_state', 1)
            ->select('ware_id', 'ware_name')
            ->get();
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $list_data]);
    }

    // 新增保存
    public function save(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->saveValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 系统版本：1门店版2运营中心版
        $shop_versions = 2;

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

        DB::beginTransaction();
        if ($shop_versions == 1) { //系统版本：1门店版
            $stoc_return = $this->saveShopSubmitData($request->all(), $goods_data, $user_info, 1);
        } else { //系统版本：2运营中心版
            $stoc_return = $this->saveSubmitData($request->all(), $goods_data, $user_info, 1);
        }

        if ($stoc_return['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '盘库单', '新增', '新增盘库单：' . $stoc_return['return_data']['stoc_storage_number'] . '成功');
            return response()->json($stoc_return);
        } else {
            DB::rollBack();
            return response()->json($stoc_return);
        }
    }

    // 新增提交
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->saveValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);


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

        // 记录日志
        $log_data['user_info'] = $user_info;
        $log_data['request'] = $request->all();
        Common::write_record_log($log_data, 'pc/kucun/StocktakeController.txt', 'add');

        DB::beginTransaction();

        $stoc_return = $this->saveSubmitData($request->all(), $goods_data, $user_info, 2);

        if ($stoc_return['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '盘库单', '新增', '新增盘库单：' . $stoc_return['return_data']['stoc_storage_number'] . '成功');
            return response()->json($stoc_return);
        } 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]
     */
    private 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) {
            // 只有旧货仓用到待检测
            if ($request['stoc_waon_class'] != '3') {
                $unchecked_stocktake_numbergoo = 0;
            } else {
                $unchecked_stocktake_numbergoo = $value['unchecked_stocktake_number'];
            }
            // 根据仓库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 ($ware_type == 1 && $user_info->shop_versions == 2) {
                // 固定仓，查询仓位商品库存数量
                // 固定仓判断是否选择仓位，固定仓必须选择仓位
                if (empty($value['wafr_id'])) {
                    return ['code' => 400, 'msg' => 'error', 'data' => '请选择仓位！', 'return_data' => $goods_data];
                }

                $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();
            } elseif ($ware_type == 3 || $user_info->shop_versions == 1) {
                // 移动仓，查询仓库库存数量
                $warehouse_goods = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $request['ware_id'])
                    ->where('wago_goo_id', $value['goo_id'])
                    ->where('wago_class', $request['stoc_waon_class'])
                    ->select('wago_goo_id', 'wago_freight_stock_number', 'wago_freight_lock_quantity', 'wago_freight_priority_stock_number', 'wago_freight_priority_lock_quantity', 'wago_freight_unchecked_stock_number', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_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 {
                if ($ware_type == 1 && $user_info->shop_versions == 2) {
                    $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'];
                } elseif ($ware_type == 3 || $user_info->shop_versions == 1) { //门店基础版或者移动仓
                    $wago_freight_stock_number = $warehouse_goods['wago_stock_number'];
                    $wago_freight_lock_quantity = $warehouse_goods['wago_lock_quantity'];
                    $wago_freight_priority_stock_number = $warehouse_goods['wago_priority_stock_number'];
                    $wago_freight_priority_lock_quantity = $warehouse_goods['wago_priority_lock_quantity'];
                    $wago_freight_unchecked_stock_number = $warehouse_goods['wago_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' => 'error', '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' => 'error', 'data' => '盘亏不能低于锁定数量', 'return_data' => $goods_data];
                }
            }
            // 盘库单编辑调用
            if ($call_type == 2) {
                $stgo_data[$num]['stgo_stoc_id'] = $request['stoc_id']; //盘库单id
            }
            $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']; //良品盘点数量
            $stgo_data[$num]['stgo_priority_stocktake_number'] = $value['priority_stocktake_number']; //优先盘点数量
            $stgo_data[$num]['stgo_unchecked_stocktake_number'] = $unchecked_stocktake_numbergoo; //待检测盘点数量
            $num++;

            $stocktake_number += $value['stocktake_number']; //良品盘点数量
            $priority_stocktake_number += $value['priority_stocktake_number']; //优先盘点数量
            $unchecked_stocktake_number += $value['unchecked_stocktake_number']; //待检测盘点数量
        }
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $stoc_differ_number = $stocktake_number + $priority_stocktake_number + $unchecked_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'] = $request['stoc_remark'] ? $request['stoc_remark'] : '';
        $stoc_data['stoc_ware_id'] = $request['ware_id'];
        $stoc_data['stoc_make_time'] = $request['stoc_make_time'];
        $stoc_data['stoc_waon_class'] = $request['stoc_waon_class'];
        $stoc_data['stoc_manner'] = $request['stoc_manner'];

        if ($call_type == 1) {
            // 新增盘库单
            $stoc_res =  DB::table('stocktake')->insertGetId($stoc_data);
            // 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 = '新增';
        } else {
            // 编辑盘库单
            $stoc_data['stoc_update_time'] = date('Y-m-d H:i:s');
            $stoc_res = DB::table('stocktake')
                ->where('stoc_id', $request['stoc_id'])
                ->update($stoc_data);
            // 2. 更改盘点商品表的数据
            // 2.1 删除原来盘点id对应的盘点商品数据
            $stgo_del_res = DB::table('stocktake_goods')
                ->where('stgo_stoc_id', $request['stoc_id'])
                ->delete();
            // 2.2 重新添加提交的盘点商品数据
            $stgo_res =  DB::table('stocktake_goods')->insert($stgo_data);
            $hint = '编辑';
        }

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

    /**
     * [saveSubmitData 门店版保存提交的数据]
     * @param  [type] $request      [提交的数据]
     * @param  [type] $goods_data   [提交的商品数据]
     * @param  [type] $user_info    [用户信息]
     * @param  [type] $type         [类型：1保存2提交]
     * @return [type]               [description]
     */
    private function saveShopSubmitData(
        $request,
        $goods_data,
        $user_info,
        $type
    ) {
        $stocktake_number = 0;  //良品盘点数量
        $priority_stocktake_number = 0;  //优先盘点数量
        $unchecked_stocktake_number = 0;  //待检测盘点数量
        foreach ($goods_data as $key => $value) {
            // 只有旧货仓用到待检测
            if ($request['stoc_waon_class'] != '3') {
                $unchecked_stocktake_numbergoo = 0;
            } else {
                $unchecked_stocktake_numbergoo = $value['unchecked_stocktake_number'];
            }
            // 查询仓库的仓位库存数量
            $warehouse_goods = DB::table('warehouse_goods')
                ->where('wago_ware_id', $request['ware_id'])
                ->where('wago_goo_id', $value['goo_id'])
                ->where('wago_class', $request['stoc_waon_class'])
                ->select('wago_goo_id', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                ->first();
            $warehouse_goods = json_decode(json_encode($warehouse_goods), true);
            if (!$warehouse_goods) {
                $wago_stock_number = 0;
                $wago_lock_quantity = 0;
                $wago_priority_stock_number = 0;
                $wago_priority_lock_quantity = 0;
                $wago_unchecked_stock_number = 0;
            } else {
                $wago_stock_number = $warehouse_goods['wago_stock_number'];
                $wago_lock_quantity = $warehouse_goods['wago_lock_quantity'];
                $wago_priority_stock_number = $warehouse_goods['wago_priority_stock_number'];
                $wago_priority_lock_quantity = $warehouse_goods['wago_priority_lock_quantity'];
                $wago_unchecked_stock_number = $warehouse_goods['wago_unchecked_stock_number'];
            }
            if ($value['stocktake_number'] < 0) {
                $stocktake_numbers = abs($value['stocktake_number']);
                if ($stocktake_numbers > $wago_stock_number) {
                    return ['code' => 400, 'msg' => 'error', 'data' => '盘亏不能低于锁定数量', 'return_data' => $goods_data];
                }
            }
            if ($value['priority_stocktake_number'] < 0) {
                $priority_stocktake_numbers = abs($value['priority_stocktake_number']);
                if ($priority_stocktake_numbers > $wago_priority_stock_number) {
                    return ['code' => 400, 'msg' => 'error', 'data' => '盘亏不能低于锁定数量', 'return_data' => $goods_data];
                }
            }
            $stgo_data[$key]['stgo_goo_id'] = $value['goo_id']; //商品id
            $stgo_data[$key]['stgo_stock_number'] = $wago_stock_number; //良品库存数量
            $stgo_data[$key]['stgo_priority_stock_number'] = $wago_priority_stock_number; //优先库存数量
            $stgo_data[$key]['stgo_unchecked_stock_number'] = $wago_unchecked_stock_number; //待检测数量
            $stgo_data[$key]['stgo_lock_number'] = $wago_lock_quantity; //良品锁定数量
            $stgo_data[$key]['stgo_priority_lock_number'] = $wago_priority_lock_quantity; //优先锁定数量
            $stgo_data[$key]['stgo_stocktake_number'] = $value['stocktake_number']; //良品盘点数量
            $stgo_data[$key]['stgo_priority_stocktake_number'] = $value['priority_stocktake_number']; //优先盘点数量
            $stgo_data[$key]['stgo_unchecked_stocktake_number'] = $unchecked_stocktake_numbergoo; //待检测盘点数量
            $stocktake_number += $value['stocktake_number']; //良品盘点数量
            $priority_stocktake_number += $value['priority_stocktake_number']; //优先盘点数量
            $unchecked_stocktake_number += $value['unchecked_stocktake_number']; //待检测盘点数量
        }

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $stoc_differ_number = $stocktake_number + $priority_stocktake_number + $unchecked_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'] = $shop_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'] = $request['stoc_remark'] ? $request['stoc_remark'] : '';
        $stoc_data['stoc_ware_id'] = $request['ware_id'];
        $stoc_data['stoc_make_time'] = $request['stoc_make_time'];
        $stoc_data['stoc_waon_class'] = $request['stoc_waon_class'];
        $stoc_data['stoc_manner'] = $request['stoc_manner'];

        // 新增盘库单
        $stoc_res =  DB::table('stocktake')->insertGetId($stoc_data);

        // 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]);
        }

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

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 盘库单数据
        $find_stoc = DB::table('stocktake')
            ->where('stoc_id', $request['stoc_id'])
            ->select('stoc_ware_id', 'stoc_make_time', 'stoc_manner', 'stoc_waon_class', 'stoc_remark', 'stoc_state', 'stoc_storage_number')
            ->first();
        if (empty($find_stoc->stoc_state) || !in_array($find_stoc->stoc_state, [1, 4])) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前盘库单不是待提交状态无法编辑！']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $stoc_state = 1; //编辑保存提交状态，默然是保存
        if ($request['type'] == 1) { //获取页面数据
            $find_goods = DB::table('stocktake_goods as stgo')
                ->leftJoin('goods as goo', 'stgo.stgo_goo_id', '=', 'goo.goo_id')
                ->where('stgo_stoc_id', $request['stoc_id'])
                ->select('stgo_goo_id', 'stgo_stock_number', 'stgo_lock_number', 'stgo_priority_lock_number', 'stgo_stocktake_number', 'goo_name', 'goo_type', 'goo_goods_encode', 'stgo_priority_stock_number', 'stgo_unchecked_stock_number', 'stgo_priority_stocktake_number', 'stgo_unchecked_stocktake_number', 'goo_brse_id', 'goo_class', 'goo_bra_name', 'goo_id', 'stgo_wafr_id', 'goo_unit')
                ->get()->toArray();
            // 返回仓库名称
            $find_stoc->stoc_ware_name = DB::table('warehouse')
                ->where('ware_id', $find_stoc->stoc_ware_id)
                ->value('ware_name');
            // 查询仓库类型：1固定仓2技师库3移动仓
            $find_stoc->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');
            $find_stoc->stoc_ware_name = DB::table('warehouse')
                ->where('ware_id', $find_stoc->stoc_ware_id)
                ->value('ware_name');
            // 查询系列数据
            $goo_brse_id = array_column($find_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            $goo_id = array_column($find_goods, 'goo_id');
            // 查询商品附属表信息
            $gosu_data = DB::table('goods_subsidiary')
                ->where('gosu_shop_id', $user_info->adm_shop_id)
                ->whereIn('gosu_goo_id', $goo_id)
                ->pluck('gosu_another_name', 'gosu_goo_id')
                ->toArray();
            $wafr_id = array_column($find_goods, 'stgo_wafr_id'); //仓位id
            // 查询仓位表数据
            $find_wafr_data = DB::table('warehouse_freight')
                ->where('wafr_shop_id', $user_info->adm_shop_id)
                ->whereIn('wafr_id', $wafr_id)
                ->where('wafr_delete', 1)
                ->pluck('wafr_name', 'wafr_id')
                ->toArray();
            foreach ($find_goods as $key => $value) {
                if (isset($gosu_data[$value->goo_id]) && !empty($gosu_data[$value->goo_id])) { //商品别名
                    $find_goods[$key]->goo_name = $gosu_data[$value->goo_id];
                }
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP')) && isset($brse_data[$value->goo_brse_id])) {
                    if (!empty($value->goo_brse_id)) {
                        if ($value->goo_class == 2) {
                            $find_goods[$key]->goo_name = $brse_data[$value->goo_brse_id] . ' ' . $find_goods[$key]->goo_name;
                            unset($find_goods[$key]->goo_brse_id);
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $find_goods[$key]->goo_name = $brse_data[$value->goo_brse_id] . ' ' . $find_goods[$key]->goo_name;
                                unset($find_goods[$key]->goo_brse_id);
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $find_goods[$key]->goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $find_goods[$key]->goo_name;
                        }
                    }
                }
                if (isset($find_wafr_data[$value->stgo_wafr_id])) {
                    $find_goods[$key]->wafr_name = $find_wafr_data[$value->stgo_wafr_id];
                } else {
                    $find_goods[$key]->wafr_name = '';
                }
                // 查询根据仓库id、仓库类别和商品id查询对应的库存数量
                $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_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                    ->first();
                $find_goods[$key]->stgo_wago_stock_number = $find_wago_data->wago_stock_number;
                $find_goods[$key]->stgo_wago_lock_number = $find_wago_data->wago_lock_quantity;
                $find_goods[$key]->stgo_wago_priority_stock_number = $find_wago_data->wago_priority_stock_number;
                $find_goods[$key]->stgo_wago_priority_lock_number = $find_wago_data->wago_priority_lock_quantity;
                $find_goods[$key]->stgo_wago_unchecked_stock_number = $find_wago_data->wago_unchecked_stock_number;
                $find_goods[$key]->goo_name = $find_goods[$key]->goo_name.'('.$value->goo_unit.')';
                unset($find_goods[$key]->goo_class);
            }
            $data['stoc_data'] = $find_stoc;
            $data['goods_data'] = $find_goods;
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } elseif ($request['type'] == 3) {
            $stoc_data['stoc_state'] = '2'; //状态1保存/待提交 2提交/待审核 3通过4驳回
            $stoc_state = 2; //提交
        }

        // 编辑提交数据
        // 验证数据
        $error_message = $verify_data->saveValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', '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' => '请选择商品']);
        }

        // 记录日志
        $log_data['stoc_storage_number'] = $find_stoc->stoc_storage_number;
        $log_data['user_info'] = $user_info;
        $log_data['request'] = $request->all();
        Common::write_record_log($log_data, 'pc/kucun/StocktakeController.txt', 'edit');

        DB::beginTransaction();
        $stoc_return = $this->saveSubmitData(
            $request->all(), //提交的数据
            $goods_data, //提交的商品数据
            $user_info, //用户信息
            $stoc_state, //类型：1保存2提交
            2 //调用类型：1新增调用2编辑调用
        );
        if ($stoc_return['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '盘库单', '编辑', '编辑盘库单：' . $find_stoc->stoc_storage_number . '成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '编辑盘库单：成功']);
        } else {
            DB::rollBack();
            return response()->json($stoc_return);
        }
    }

    // 提交
    public function submit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->submitValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 查询信息
        $find_stoc = DB::table('stocktake')
            ->where('stoc_id', $request['stoc_id'])
            ->select('stoc_storage_number', 'stoc_state')
            ->first();
        if ($find_stoc->stoc_state == 2) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前盘库单已提交']);
        }
        if ($find_stoc->stoc_state == 3) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前盘库单已通过审核']);
        }

        // 提交
        $update_data['stoc_state'] = 2; //状态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);
        if ($stoc_res) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '盘库单', '提交', '盘库单：' . $find_stoc->stoc_storage_number . ' 提交成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '提交成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '提交失败']);
        }
    }

    // 通过
    public function pass(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->submitValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 查询信息
        $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 response()->json(['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();

        DB::beginTransaction();

        // 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();
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        if ($find_stoc->stoc_is_import == 1) { //期初导入调用该方法
            $return_pass = $this->openingPass($user_info, $request->all()); //通过导入期初
            // $return_pass = $this->passOldStock($user_info, $request->all());//厦门旧仓库库存盘点
            if ($return_pass['code'] == 200) {
                Common::addLog($user_info, getRealIp($request), '盘库单', '通过', '盘库单：' . $find_stoc->stoc_storage_number . ' 通过成功');
                DB::commit();
            } else {
                DB::rollBack();
            }
            return response()->json($return_pass);
        }
        $shop_versions = 2; //系统版本信息1门店版2运营中心版
        if ($shop_versions == 1) {
            $return_pass = $this->shopPass($user_info, $request->all());
            if ($return_pass['code'] == 200) {
                Common::addLog($user_info, getRealIp($request), '盘库单', '通过', '盘库单：' . $find_stoc->stoc_storage_number . ' 通过成功');
                DB::commit();
            } else {
                DB::rollBack();
            }
            return response()->json($return_pass);
        }
        $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');
                DB::rollBack();
                return response()->json(['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) {
                            DB::rollBack();
                            return response()->json(['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) {
                            DB::rollBack();
                            return response()->json(['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)) {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => 'error', '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) {
                                DB::rollBack();
                                return response()->json(['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) {
                                DB::rollBack();
                                return response()->json(['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) {
            DB::rollBack();
            return response()->json(['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) {
                    DB::rollBack();
                    return response()->json(['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) {
                    DB::rollBack();
                    return response()->json(['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) {
                    DB::rollBack();
                    return response()->json(['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) {
                    DB::rollBack();
                    return response()->json(['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'] = $shop_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) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            // 查询品牌公司表，与门店存在补货关系的品牌
            $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) {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => $request_return->msg, 'data' => $request_return->msg]);
                    }
                }
            }
            //盘库单入库修改商品单价和总价
            $amount_ret = $this->updateWagoAmountStocktake($request['stoc_id']);
            if($amount_ret['code'] != 200){
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'盘库单通过失败011']);
            }
            foreach ($stocktake_goods as $key => $value) {
                $new_goods_data[$key]['goo_id'] = $value['stgo_goo_id'];
            }
            $post_data['ware_id'] = $find_stoc->stoc_ware_id;
            $post_data['new_goods_data'] = $new_goods_data;
            $res = WashOrderBasicService::addGoodPlan($user_info, $post_data);
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '盘库单', '通过', '盘库单：' . $find_stoc->stoc_storage_number . ' 通过成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '通过成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '通过失败']);
        }
    }

    /* 商品库存有变化的时候，修改仓库商品得总价 20230518
     * $id 盘库单id
     */
    public function updateWagoAmountStocktake($id)
    {
        //盘库单信息
        $transferring_res = DB::table('stocktake_goods as tg')
            ->leftJoin('stocktake as t', 't.stoc_id', '=', 'tg.stgo_stoc_id')
            ->where('stgo_stoc_id', $id)
            ->select('stgo_goo_id', 'stoc_ware_id')
            ->get()->toArray();
        if(empty($transferring_res)){
            return ['code'=>500, 'msg'=>'success', 'data'=>'盘库单不存在'];
        }
        $good_ids = array_column($transferring_res,'stgo_goo_id');//盘库单里的商品id
        $ware_id = array_unique(array_column($transferring_res,'stoc_ware_id'));//盘点仓库的id
        // 查询仓库商品信息
        $find_tror = DB::table('warehouse_goods')
            ->whereIn('wago_goo_id', $good_ids)
            ->where('wago_class', 1)
            ->where('wago_ware_id', $ware_id)
            ->select('wago_id', 'wago_goo_price', 'wago_goo_amount', 'wago_stock_number', 'wago_lock_quantity', 'wago_ware_id', 'wago_goo_id')
            ->get()->toArray();
        if(empty($find_tror)){
            return ['code'=>500, 'msg'=>'success', 'data'=>'仓库商品不存在'];
        }
        foreach ($find_tror as $k => $v){
            $trod_data = [];
            //仓库商品得总价 = 商品单价 * （商品库存 + 商品锁定数量）
            $amount = $v->wago_goo_price * ($v->wago_stock_number + $v->wago_lock_quantity);
            $trod_data['wago_goo_amount'] = $amount;
            $trod_data['wago_update_time'] =  date('Y-m-d H:i:s'); //更新时间
            //修改仓库商品的总价
            $ware_goo_ret = DB::table('warehouse_goods')
                ->where('wago_ware_id', $v->wago_ware_id)
                ->where('wago_goo_id', $v->wago_goo_id)
                ->where('wago_class', 1)
                ->update($trod_data);
        }
        //查找仓库所有商品总价
        $find_tror_all = DB::table('warehouse_goods')
            ->where('wago_ware_id', $ware_id)
            ->where('wago_class', 1)
            ->select('wago_id', 'wago_goo_amount', 'wago_ware_id')
            ->get()->toArray();
        if(empty($find_tror_all)){
            return ['code'=>500, 'msg'=>'success', 'data'=>'仓库不存在'];
        }
        $ware_all_data = [];
        foreach ($find_tror_all as $a_k => $a_v){
            if(isset($ware_all_data[$a_v->wago_ware_id])){
                $ware_all_data[$a_v->wago_ware_id] += $a_v->wago_goo_amount;
            }else{
                $ware_all_data[$a_v->wago_ware_id] = $a_v->wago_goo_amount;
            }
        }
        if(empty($ware_all_data)){
            return ['code'=>500, 'msg'=>'success', 'data'=>'仓库不存在'];
        }
        foreach ($ware_all_data as $k => $v){
            //修改仓库商品的总金额
            $ware_ret = DB::table('warehouse')
                ->where('ware_id', $k)
                ->where('ware_type', 1)
                ->update(['ware_goo_amount'=>$v]);
        }
        return ['code'=>200, 'msg'=>'success', 'data'=>'修改总价成功'];
    }

    // 门店基础版通过
    public function shopPass($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')
            ->first();
        $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')
            ->first();
        // 2. 查询要盘点的商品数量
        $stocktake_goods = DB::table('stocktake_goods')
            ->where('stgo_stoc_id', $find_stoc->stoc_id)
            ->select('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')
            ->get();
        // 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();
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 4. 盘库单商品盘点数量，与仓库商品数量比较
        $diff_ware_all_stock = 0; //良品库存盘点盈亏数量
        $diff_ware_priority_all_stock = 0; //优先库存盘点盈亏数量
        $diff_ware_unchecked_all_stock = 0; //待检测库存盘点盈亏数量
        $diff_ware_amount = 0; //仓库总的损益数量
        $goodsamout['stock_goodsuamout'] = 0; //良品盘盈总数
        $goodsamout['stock_goodsdamout'] = 0; //良品盘亏总数
        $goodsamout['priority_goodsuamout'] = 0; //优先盘盈总数
        $goodsamout['priority_goodsdamout'] = 0; //优先盘亏总数
        $goodsamout['unchecked_goodsuamout'] = 0; //待检测盘盈总数
        $goodsamout['unchecked_goodsdamout'] = 0; //待检测盘亏总数
        foreach ($stocktake_goods as $key => $value) {
            $goo_id[] = $value->stgo_goo_id; //盘点商品id
            // 商品良品盘点数量
            $diff_stock_number = $value->stgo_stocktake_number;
            $goo_stock_number[$value->stgo_goo_id] = $diff_stock_number;
            $diff_ware_all_stock += $diff_stock_number;
            $diff_ware_amount += $diff_stock_number;
            // 商品流水
            if ($value->stgo_stocktake_number > 0) {
                $goodsout['stock_goodsuid'][] = $value->stgo_goo_id; //良品盘盈id
                $goodsout['stock_goodsunum'][] = $diff_stock_number; //良品盘盈数量
                $goodsout['stock_goodsuinv'][] = 1; //良品盘盈
                $goodsamout['stock_goodsuamout'] += $diff_stock_number;
            } elseif ($value->stgo_stocktake_number < 0) {
                $goodsout['stock_goodsdid'][] = $value->stgo_goo_id; //良品盘亏id
                $goodsout['stock_goodsdnum'][] = abs($diff_stock_number); //良品盘亏数量
                $goodsout['stock_goodsdinv'][] = 1; //良品盘亏
                $goodsamout['stock_goodsdamout'] += abs($diff_stock_number);
            }
            // 商品优先盘点数量
            $diff_priority_number = $value->stgo_priority_stocktake_number;
            $goo_priority_number[$value->stgo_goo_id] = $diff_priority_number;
            $diff_ware_priority_all_stock += $diff_priority_number;
            $diff_ware_amount += $diff_priority_number;
            // 商品流水
            if ($value->stgo_priority_stocktake_number > 0) {
                $goodsout['priority_goodsuid'][] = $value->stgo_goo_id; //优先盘盈id
                $goodsout['priority_goodsunum'][] = $diff_priority_number; //优先盘盈数量
                $goodsout['priority_goodsuinv'][] = 2; //优先盘盈
                $goodsamout['priority_goodsuamout'] += $diff_priority_number;
            } elseif ($value->stgo_priority_stocktake_number < 0) {
                $goodsout['priority_goodsdid'][] = $value->stgo_goo_id; //优先盘亏id
                $goodsout['priority_goodsdnum'][] = abs($diff_priority_number); //优先盘亏数量
                $goodsout['priority_goodsdinv'][] = 2; //优先盘亏
                $goodsamout['priority_goodsdamout'] += abs($diff_priority_number);
            }
            // 商品待检测盘点数量
            $diff_unchecked_number = $value->stgo_unchecked_stocktake_number;
            $goo_unchecked_number[$value->stgo_goo_id] = $diff_unchecked_number;
            $diff_ware_unchecked_all_stock += $diff_unchecked_number;
            $diff_ware_amount += $diff_unchecked_number;
            // 商品流水
            if ($value->stgo_unchecked_stocktake_number > 0) {
                $goodsout['unchecked_goodsuid'][] = $value->stgo_goo_id; //待检测盘盈id
                $goodsout['unchecked_goodsunum'][] = $diff_unchecked_number; //待检测盘盈数量
                $goodsout['unchecked_goodsuinv'][] = 3; //待检测盘盈
                $goodsamout['unchecked_goodsuamout'] += $diff_unchecked_number;
            } elseif ($value->stgo_unchecked_stocktake_number < 0) {
                $goodsout['unchecked_goodsdid'][] = $value->stgo_goo_id; //待检测盘亏id
                $goodsout['unchecked_goodsdnum'][] = abs($diff_unchecked_number); //待检测盘亏数量
                $goodsout['unchecked_goodsdinv'][] = 3; //待检测盘亏
                $goodsamout['unchecked_goodsdamout'] += abs($diff_unchecked_number);
            }
        }
        foreach ($goodsamout as $k => $v) {
            if ($v > 0) { //良品盘盈
                if ($k == 'stock_goodsuamout') {
                    $outware = 0;
                    $inware = $find_stoc->stoc_ware_id;
                    $outtype = 3;
                    $intype = 2;
                    $surplus->ware_all_stock = $surplus->ware_all_stock + $v;
                    $goo_idarr = $goodsout['stock_goodsuid']; //数组，商品id
                    $goo_number = $goodsout['stock_goodsunum']; //数组，商品数量
                    $inventory = $goodsout['stock_goodsuinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'priority_goodsuamout') { //优先盘盈
                    $outware = 0;
                    $inware = $find_stoc->stoc_ware_id;
                    $outtype = 3;
                    $intype = 2;
                    $surplus->ware_priority_all_stock = $surplus->ware_priority_all_stock + $v;
                    $goo_idarr = $goodsout['priority_goodsuid']; //数组，商品id
                    $goo_number = $goodsout['priority_goodsunum']; //数组，商品数量
                    $inventory = $goodsout['priority_goodsuinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'unchecked_goodsuamout') { //待检测盘盈
                    $outware = 0;
                    $inware = $find_stoc->stoc_ware_id;
                    $outtype = 3;
                    $intype = 2;
                    $surplus->ware_unchecked_all_stock = $surplus->ware_unchecked_all_stock + $v;
                    $goo_idarr = $goodsout['unchecked_goodsuid']; //数组，商品id
                    $goo_number = $goodsout['unchecked_goodsunum']; //数组，商品数量
                    $inventory = $goodsout['unchecked_goodsuinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'stock_goodsdamout') { //良品盘亏
                    $inware = 0;
                    $outware = $find_stoc->stoc_ware_id;
                    $outtype = 2;
                    $intype = 1;
                    $surplus->ware_all_stock = $surplus->ware_all_stock - $v;
                    $goo_idarr = $goodsout['stock_goodsdid']; //数组，商品id
                    $goo_number = $goodsout['stock_goodsdnum']; //数组，商品数量
                    $inventory = $goodsout['stock_goodsdinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'priority_goodsdamout') { //优先盘亏
                    $inware = 0;
                    $outware = $find_stoc->stoc_ware_id;
                    $outtype = 2;
                    $intype = 1;
                    $surplus->ware_priority_all_stock = $surplus->ware_priority_all_stock - $v;
                    $goo_idarr = $goodsout['priority_goodsdid']; //数组，商品id
                    $goo_number = $goodsout['priority_goodsdnum']; //数组，商品数量
                    $inventory = $goodsout['priority_goodsdinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'unchecked_goodsdamout') { //待检测盘亏
                    $inware = 0;
                    $outware = $find_stoc->stoc_ware_id;
                    $outtype = 2;
                    $intype = 1;
                    $surplus->ware_unchecked_all_stock = $surplus->ware_unchecked_all_stock - $v;
                    $goo_idarr = $goodsout['unchecked_goodsdid']; //数组，商品id
                    $goo_number = $goodsout['unchecked_goodsdnum']; //数组，商品数量
                    $inventory = $goodsout['unchecked_goodsdinv']; //数组，出库类型1良品2优先3待检测
                }
                // 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
                    $v, //出库的商品总量
                    15, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单15盘库单
                    $outtype, //操作类型：1锁定库存2出库3入库4调货5发货
                    $surplus->ware_all_stock, //良品总库存
                    $surplus->ware_lock_quantity, //良品锁定数量
                    $surplus->ware_priority_all_stock, //优先总库存
                    $surplus->ware_priority_lock_quantity, //优先锁定数量
                    $surplus->ware_unchecked_all_stock, //待检测总库存
                    $intype, //出入库类型：1出库，2入库
                    $find_stoc->stoc_waon_class, //[仓库类别]
                    $goo_idarr, //数组，商品id
                    $goo_number, //数组，商品数量
                    $inventory //数组，出库类型1良品2优先3待检测
                );
            }
        }
        // 4.2 查询商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $find_stoc->stoc_ware_id)
            ->where('wago_class', $find_stoc->stoc_waon_class)
            ->whereIn('wago_goo_id', $goo_id)
            ->select('wago_id', 'wago_stock_number', 'wago_goo_id', 'wago_priority_stock_number', 'wago_unchecked_stock_number', 'wago_stock_amount', 'wago_priority_stock_amount', 'wago_unchecked_stock_amount')
            ->get();
        $warehouse_goods = json_decode(json_encode($warehouse_goods), true);
        // 4.3 处理要盘点的商品库存数量
        if (empty($warehouse_goods)) {
            $ware_edit_res = true;
        } else {
            // 4.4 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
            $sql = 'UPDATE `faster_warehouse_goods` SET ';
            $stock_number_sql = '';
            $priority_stock_number_sql = '';
            $unchecked_stock_number_sql = '';
            $wago_stock_amount_sql = '';
            $wago_priority_stock_amount_sql = '';
            $wago_unchecked_stock_amount_sql = '';
            $update_time_sql = '';
            $ids = '';
            foreach ($warehouse_goods as $key => $value) {
                // 要更改的商品库存数量
                $stock_number = $value['wago_stock_number'] + $goo_stock_number[$value['wago_goo_id']];
                $priority_stock_number = $value['wago_priority_stock_number'] + $goo_priority_number[$value['wago_goo_id']];
                $unchecked_stock_number = $value['wago_unchecked_stock_number'] + $goo_unchecked_number[$value['wago_goo_id']];

                $wago_stock_amount = $value['wago_stock_amount'] + $goo_stock_number[$value['wago_goo_id']];
                $wago_priority_stock_amount = $value['wago_priority_stock_amount'] + $goo_priority_number[$value['wago_goo_id']];
                $wago_unchecked_stock_amount = $value['wago_unchecked_stock_amount'] + $goo_unchecked_number[$value['wago_goo_id']];
                // if ($stock_number < 0 || $priority_stock_number < 0 || $unchecked_stock_number < 0) {

                //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品盘亏数量超出库存数量']);
                // }
                if ($stock_number < 0) {
                    $stock_number = 0;
                }
                if ($priority_stock_number < 0) {
                    $priority_stock_number = 0;
                }
                if ($unchecked_stock_number < 0) {
                    $unchecked_stock_number = 0;
                }
                if ($wago_stock_amount < 0) {
                    $wago_stock_amount = 0;
                }
                if ($wago_priority_stock_amount < 0) {
                    $wago_priority_stock_amount = 0;
                }
                if ($wago_unchecked_stock_amount < 0) {
                    $wago_unchecked_stock_amount = 0;
                }
                // 更改商品库存数量(仓库+仓位)
                $stock_number_sql = $stock_number_sql . ' WHEN ' . $value['wago_id'];
                $stock_number_sql = $stock_number_sql . ' THEN ' . $stock_number;
                // 更改商品库存数量(仓库)
                $wago_stock_amount_sql = $wago_stock_amount_sql . ' WHEN ' . $value['wago_id'];
                $wago_stock_amount_sql = $wago_stock_amount_sql . ' THEN ' . $wago_stock_amount;
                // 更改优先库存数量(仓库+仓位)
                $priority_stock_number_sql = $priority_stock_number_sql . ' WHEN ' . $value['wago_id'];
                $priority_stock_number_sql = $priority_stock_number_sql . ' THEN ' . $priority_stock_number;
                // 更改优先库存数量(仓库)
                $wago_priority_stock_amount_sql = $wago_priority_stock_amount_sql . ' WHEN ' . $value['wago_id'];
                $wago_priority_stock_amount_sql = $wago_priority_stock_amount_sql . ' THEN ' . $wago_stock_amount;
                // 更改待检测库存数量(仓库+仓位)
                $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' WHEN ' . $value['wago_id'];
                $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' THEN ' . $unchecked_stock_number;
                // 更改待检测库存数量(仓库)
                $wago_unchecked_stock_amount_sql = $wago_unchecked_stock_amount_sql . ' WHEN ' . $value['wago_id'];
                $wago_unchecked_stock_amount_sql = $wago_unchecked_stock_amount_sql . ' THEN ' .  $wago_unchecked_stock_amount;
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value['wago_id'];
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $value['wago_id'] . ',';
                // 删除已更改的商品数据
                unset($goo_stock_number[$value['wago_goo_id']]);
            }
            $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $stock_number_sql . ' END,';
            $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $priority_stock_number_sql . ' END,';
            $sql = $sql . ' `wago_unchecked_stock_number`=  CASE `wago_id` ' . $unchecked_stock_number_sql . ' END,';

            $sql = $sql . ' `wago_stock_amount`=  CASE `wago_id` ' . $wago_stock_amount_sql . ' END,';
            $sql = $sql . ' `wago_priority_stock_amount`=  CASE `wago_id` ' . $wago_priority_stock_amount_sql . ' END,';
            $sql = $sql . ' `wago_unchecked_stock_amount`=  CASE `wago_id` ' . $wago_unchecked_stock_amount_sql . ' END,';
            $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
            $ware_edit_res = DB::update($sql);
        }

        if (empty($goo_stock_number)) {
            $ware_add_res = true;
        } else {
            return ["code" => 500, 'msg' => 'error', 'data' => '仓库商品不存在，通过失败'];
        }

        // 仓库类别表总库存数量加上 差值数量
        $warehouse_onhand_sql = 'UPDATE `faster_warehouse_onhand` SET  `waon_all_amount`= `waon_all_amount`+' . $diff_ware_amount . ', `waon_stock_fine_amount`= `waon_stock_fine_amount`+' . $diff_ware_all_stock . ' , `waon_stock_priority_amount`= `waon_stock_priority_amount` + ' . $diff_ware_priority_all_stock . ', `waon_stock_unchecked_amount`= `waon_stock_unchecked_amount` + ' . $diff_ware_unchecked_all_stock . ', `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);

        $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'] = $shop_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;
        }
        // 记录日志
        $log_data['user_info'] = $user_info;
        $log_data['stoc_storage_number'] = $find_stoc->stoc_storage_number;
        $log_data['request'] = $request;
        Common::write_record_log($log_data, 'pc/StocktakeController.txt', 'shopPass');
        if ($waon_res && $ware_edit_res && $ware_add_res && $vore_id && $volo_id) {
            // 获取当前操作账号信息
            return ["code" => 200, 'msg' => 'success', 'data' => '通过成功'];
        } else {
            return ["code" => 500, 'msg' => 'error', 'data' => '通过失败'];
        }
    }

    // 通过导入期初
    public function passImport($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')
            ->first();
        // if ($find_stoc->stoc_state != 2) {
        //     return response()->json(['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')
            ->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_goo_id', 'stgo_stock_number', 'stgo_stocktake_number', 'stgo_priority_stock_number', 'stgo_unchecked_stock_number', 'stgo_priority_stocktake_number', 'stgo_unchecked_stocktake_number')
            ->get();
        // 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_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 4. 盘库单商品盘点数量，与仓库商品数量比较
        $diff_ware_all_stock = 0; //良品库存盘点盈亏数量
        $diff_ware_priority_all_stock = 0; //优先库存盘点盈亏数量
        $diff_ware_unchecked_all_stock = 0; //待检测库存盘点盈亏数量
        $diff_ware_amount = 0; //仓库总的损益数量
        $goodsamout['stock_goodsuamout'] = 0; //良品盘盈总数
        $goodsamout['stock_goodsdamout'] = 0; //良品盘亏总数
        $goodsamout['priority_goodsuamout'] = 0; //优先盘盈总数
        $goodsamout['priority_goodsdamout'] = 0; //优先盘亏总数
        $goodsamout['unchecked_goodsuamout'] = 0; //待检测盘盈总数
        $goodsamout['unchecked_goodsdamout'] = 0; //待检测盘亏总数
        foreach ($stocktake_goods as $key => $value) {
            $goo_id[] = $value->stgo_goo_id; //盘点商品id
            // 商品良品盘点数量
            $diff_stock_number = $value->stgo_stocktake_number;
            $goo_stock_number[$value->stgo_goo_id] = $diff_stock_number;
            $diff_ware_all_stock += $diff_stock_number;
            $diff_ware_amount += $diff_stock_number;
            // 商品流水
            if ($value->stgo_stocktake_number > 0) {
                $goodsout['stock_goodsuid'][] = $value->stgo_goo_id; //良品盘盈id
                $goodsout['stock_goodsunum'][] = $diff_stock_number; //良品盘盈数量
                $goodsout['stock_goodsuinv'][] = 1; //良品盘盈
                $goodsamout['stock_goodsuamout'] += $diff_stock_number;
            } elseif ($value->stgo_stocktake_number < 0) {
                $goodsout['stock_goodsdid'][] = $value->stgo_goo_id; //良品盘亏id
                $goodsout['stock_goodsdnum'][] = abs($diff_stock_number); //良品盘亏数量
                $goodsout['stock_goodsdinv'][] = 1; //良品盘亏
                $goodsamout['stock_goodsdamout'] += abs($diff_stock_number);
            }
            // 商品优先盘点数量
            $diff_priority_number = $value->stgo_priority_stocktake_number;
            $goo_priority_number[$value->stgo_goo_id] = $diff_priority_number;
            $diff_ware_priority_all_stock += $diff_priority_number;
            $diff_ware_amount += $diff_priority_number;
            // 商品流水
            if ($value->stgo_priority_stocktake_number > 0) {
                $goodsout['priority_goodsuid'][] = $value->stgo_goo_id; //优先盘盈id
                $goodsout['priority_goodsunum'][] = $diff_priority_number; //优先盘盈数量
                $goodsout['priority_goodsuinv'][] = 2; //优先盘盈
                $goodsamout['priority_goodsuamout'] += $diff_priority_number;
            } elseif ($value->stgo_priority_stocktake_number < 0) {
                $goodsout['priority_goodsdid'][] = $value->stgo_goo_id; //优先盘亏id
                $goodsout['priority_goodsdnum'][] = abs($diff_priority_number); //优先盘亏数量
                $goodsout['priority_goodsdinv'][] = 2; //优先盘亏
                $goodsamout['priority_goodsdamout'] += abs($diff_priority_number);
            }
            // 商品待检测盘点数量
            $diff_unchecked_number = $value->stgo_unchecked_stocktake_number;
            $goo_unchecked_number[$value->stgo_goo_id] = $diff_unchecked_number;
            $diff_ware_unchecked_all_stock += $diff_unchecked_number;
            $diff_ware_amount += $diff_unchecked_number;
            // 商品流水
            if ($value->stgo_unchecked_stocktake_number > 0) {
                $goodsout['unchecked_goodsuid'][] = $value->stgo_goo_id; //待检测盘盈id
                $goodsout['unchecked_goodsunum'][] = $diff_unchecked_number; //待检测盘盈数量
                $goodsout['unchecked_goodsuinv'][] = 3; //待检测盘盈
                $goodsamout['unchecked_goodsuamout'] += $diff_unchecked_number;
            } elseif ($value->stgo_unchecked_stocktake_number < 0) {
                $goodsout['unchecked_goodsdid'][] = $value->stgo_goo_id; //待检测盘亏id
                $goodsout['unchecked_goodsdnum'][] = abs($diff_unchecked_number); //待检测盘亏数量
                $goodsout['unchecked_goodsdinv'][] = 3; //待检测盘亏
                $goodsamout['unchecked_goodsdamout'] += abs($diff_unchecked_number);
            }
        }
        foreach ($goodsamout as $k => $v) {
            if ($v > 0) {
                // 良品盘盈
                if ($k == 'stock_goodsuamout') {
                    $outware = 0;
                    $inware = $find_stoc->stoc_ware_id;
                    $outtype = 3;
                    $intype = 2;
                    $surplus->ware_all_stock = $surplus->ware_all_stock + $v;
                    $goo_idarr = $goodsout['stock_goodsuid']; //数组，商品id
                    $goo_number = $goodsout['stock_goodsunum']; //数组，商品数量
                    $inventory = $goodsout['stock_goodsuinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'priority_goodsuamout') { //优先盘盈
                    $outware = 0;
                    $inware = $find_stoc->stoc_ware_id;
                    $outtype = 3;
                    $intype = 2;
                    $surplus->ware_priority_all_stock = $surplus->ware_priority_all_stock + $v;
                    $goo_idarr = $goodsout['priority_goodsuid']; //数组，商品id
                    $goo_number = $goodsout['priority_goodsunum']; //数组，商品数量
                    $inventory = $goodsout['priority_goodsuinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'unchecked_goodsuamout') { //待检测盘盈
                    $outware = 0;
                    $inware = $find_stoc->stoc_ware_id;
                    $outtype = 3;
                    $intype = 2;
                    $surplus->ware_unchecked_all_stock = $surplus->ware_unchecked_all_stock + $v;
                    $goo_idarr = $goodsout['unchecked_goodsuid']; //数组，商品id
                    $goo_number = $goodsout['unchecked_goodsunum']; //数组，商品数量
                    $inventory = $goodsout['unchecked_goodsuinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'stock_goodsdamout') { //良品盘亏
                    $inware = 0;
                    $outware = $find_stoc->stoc_ware_id;
                    $outtype = 2;
                    $intype = 1;
                    $surplus->ware_all_stock = $surplus->ware_all_stock - $v;
                    $goo_idarr = $goodsout['stock_goodsdid']; //数组，商品id
                    $goo_number = $goodsout['stock_goodsdnum']; //数组，商品数量
                    $inventory = $goodsout['stock_goodsdinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'priority_goodsdamout') { //优先盘亏
                    $inware = 0;
                    $outware = $find_stoc->stoc_ware_id;
                    $outtype = 2;
                    $intype = 1;
                    $surplus->ware_priority_all_stock = $surplus->ware_priority_all_stock - $v;
                    $goo_idarr = $goodsout['priority_goodsdid']; //数组，商品id
                    $goo_number = $goodsout['priority_goodsdnum']; //数组，商品数量
                    $inventory = $goodsout['priority_goodsdinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'unchecked_goodsdamout') { //待检测盘亏
                    $inware = 0;
                    $outware = $find_stoc->stoc_ware_id;
                    $outtype = 2;
                    $intype = 1;
                    $surplus->ware_unchecked_all_stock = $surplus->ware_unchecked_all_stock - $v;
                    $goo_idarr = $goodsout['unchecked_goodsdid']; //数组，商品id
                    $goo_number = $goodsout['unchecked_goodsdnum']; //数组，商品数量
                    $inventory = $goodsout['unchecked_goodsdinv']; //数组，出库类型1良品2优先3待检测
                }
                // 3.生成出出库记录
                $oure_data = OutinRecord::additionImport(
                    $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
                    $v, //出库的商品总量
                    15, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单15盘库单
                    $outtype, //操作类型：1锁定库存2出库3入库4调货5发货
                    $surplus->ware_all_stock, //良品总库存
                    $surplus->ware_lock_quantity, //良品锁定数量
                    $surplus->ware_priority_all_stock, //优先总库存
                    $surplus->ware_priority_lock_quantity, //优先锁定数量
                    $surplus->ware_unchecked_all_stock, //待检测总库存
                    $intype, //出入库类型：1出库，2入库
                    $find_stoc->stoc_waon_class, //[仓库类别]
                    $goo_idarr, //数组，商品id
                    $goo_number, //数组，商品数量
                    $inventory //数组，出库类型1良品2优先3待检测
                );
            }
        }
        // 4.2 查询商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $find_stoc->stoc_ware_id)
            ->where('wago_class', $find_stoc->stoc_waon_class)
            ->whereIn('wago_goo_id', $goo_id)
            ->select('wago_id', 'wago_stock_number', 'wago_goo_id', 'wago_priority_stock_number', 'wago_unchecked_stock_number')
            ->get();
        $warehouse_goods = json_decode(json_encode($warehouse_goods), true);
        // 4.3 处理要盘点的商品库存数量
        if (empty($warehouse_goods)) {
            $ware_edit_res = true;
        } else {
            // 4.4 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
            $sql = 'UPDATE `faster_warehouse_goods` SET ';
            $stock_number_sql = '';
            $priority_stock_number_sql = '';
            $unchecked_stock_number_sql = '';
            $update_time_sql = '';
            $ids = '';

            foreach ($warehouse_goods as $key => $value) {
                // 要更改的商品库存数量
                $stock_number = $value['wago_stock_number'] + $goo_stock_number[$value['wago_goo_id']];
                $priority_stock_number = $value['wago_priority_stock_number'] + $goo_priority_number[$value['wago_goo_id']];
                $unchecked_stock_number = $value['wago_unchecked_stock_number'] + $goo_unchecked_number[$value['wago_goo_id']];
                if ($stock_number < 0 || $priority_stock_number < 0 || $unchecked_stock_number < 0) {
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '商品盘亏数量超出库存数量']);
                }
                // 更改商品库存数量
                $stock_number_sql = $stock_number_sql . ' WHEN ' . $value['wago_id'];
                $stock_number_sql = $stock_number_sql . ' THEN ' . $stock_number;
                // 更改优先库存数量
                $priority_stock_number_sql = $priority_stock_number_sql . ' WHEN ' . $value['wago_id'];
                $priority_stock_number_sql = $priority_stock_number_sql . ' THEN ' . $priority_stock_number;
                // 更改待检测库存数量
                $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' WHEN ' . $value['wago_id'];
                $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' THEN ' . $unchecked_stock_number;
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value['wago_id'];
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $value['wago_id'] . ',';
                // 删除已更改的商品数据
                unset($goo_stock_number[$value['wago_goo_id']]);
            }
            $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $stock_number_sql . ' END,';
            $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $priority_stock_number_sql . ' END,';
            $sql = $sql . ' `wago_unchecked_stock_number`=  CASE `wago_id` ' . $unchecked_stock_number_sql . ' END,';
            $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
            $ware_edit_res = DB::update($sql);
        }

        if (empty($goo_stock_number)) {
            $ware_add_res = true;
        } else {
            // 4.5 仓库商品表中没有的商品，新增仓库商品
            $num = 0;
            foreach ($goo_stock_number as $key => $value) {
                if ($value < 0) {
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '商品盘亏数量超出库存数量']);
                }
                $ware_add_data[$num]['wago_ware_id'] = $find_stoc->stoc_ware_id;
                $ware_add_data[$num]['wago_class'] = $find_stoc->stoc_waon_class;
                $ware_add_data[$num]['wago_goo_id'] = $key;
                $ware_add_data[$num]['wago_stock_number'] = $value;
                $ware_add_data[$num]['wago_priority_stock_number'] = $goo_priority_number[$key];
                $ware_add_data[$num]['wago_unchecked_stock_number'] = $goo_unchecked_number[$key];
                $num++;
            }
            $ware_add_res = DB::table('warehouse_goods')->insert($ware_add_data);
        }

        // 仓库类别表总库存数量加上 差值数量
        $warehouse_onhand_sql = 'UPDATE `faster_warehouse_onhand` SET  `waon_all_amount`= `waon_all_amount`+' . $diff_ware_amount . ', `waon_stock_fine_amount`= `waon_stock_fine_amount`+' . $diff_ware_all_stock . ' , `waon_stock_priority_amount`= `waon_stock_priority_amount` + ' . $diff_ware_priority_all_stock . ', `waon_stock_unchecked_amount`= `waon_stock_unchecked_amount` + ' . $diff_ware_unchecked_all_stock . ', `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);

        $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'] = $shop_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 ($waon_res && $ware_edit_res && $ware_add_res && $vore_id && $volo_id) {
            return ['code' => 200, 'msg' => 'success', 'data' => '通过成功'];
        } else {
            return ['code' => 500, 'msg' => 'error', 'data' => '通过失败'];
        }
    }

    // 厦门旧仓库库存盘点
    public function passOldStock($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')
            ->first();
        $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')
            ->first();

        // 2. 查询要盘点的商品数量
        $stocktake_goods = DB::table('stocktake_goods')
            ->where('stgo_stoc_id', $find_stoc->stoc_id)
            ->select('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')
            ->get();
        // 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_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 4. 盘库单商品盘点数量，与仓库商品数量比较
        $diff_ware_all_stock = 0; //良品库存盘点盈亏数量
        $diff_ware_priority_all_stock = 0; //优先库存盘点盈亏数量
        $diff_ware_unchecked_all_stock = 0; //待检测库存盘点盈亏数量
        $diff_ware_amount = 0; //仓库总的损益数量
        $goodsamout['stock_goodsuamout'] = 0; //良品盘盈总数
        $goodsamout['stock_goodsdamout'] = 0; //良品盘亏总数
        $goodsamout['priority_goodsuamout'] = 0; //优先盘盈总数
        $goodsamout['priority_goodsdamout'] = 0; //优先盘亏总数
        $goodsamout['unchecked_goodsuamout'] = 0; //待检测盘盈总数
        $goodsamout['unchecked_goodsdamout'] = 0; //待检测盘亏总数
        foreach ($stocktake_goods as $key => $value) {
            $goo_id[] = $value->stgo_goo_id; //盘点商品id
            // 商品良品盘点数量
            $diff_stock_number = $value->stgo_stocktake_number;
            $goo_stock_number[$value->stgo_goo_id] = $diff_stock_number;
            $diff_ware_all_stock += $diff_stock_number;
            $diff_ware_amount += $diff_stock_number;
            // 商品流水
            if ($value->stgo_stocktake_number > 0) {
                $goodsout['stock_goodsuid'][] = $value->stgo_goo_id; //良品盘盈id
                $goodsout['stock_goodsunum'][] = $diff_stock_number; //良品盘盈数量
                $goodsout['stock_goodsuinv'][] = 1; //良品盘盈
                $goodsamout['stock_goodsuamout'] += $diff_stock_number;
            } elseif ($value->stgo_stocktake_number < 0) {
                $goodsout['stock_goodsdid'][] = $value->stgo_goo_id; //良品盘亏id
                $goodsout['stock_goodsdnum'][] = abs($diff_stock_number); //良品盘亏数量
                $goodsout['stock_goodsdinv'][] = 1; //良品盘亏
                $goodsamout['stock_goodsdamout'] += abs($diff_stock_number);
            }
            // 商品优先盘点数量
            $diff_priority_number = $value->stgo_priority_stocktake_number;
            $goo_priority_number[$value->stgo_goo_id] = $diff_priority_number;
            $diff_ware_priority_all_stock += $diff_priority_number;
            $diff_ware_amount += $diff_priority_number;
            // 商品流水
            if ($value->stgo_priority_stocktake_number > 0) {
                $goodsout['priority_goodsuid'][] = $value->stgo_goo_id; //优先盘盈id
                $goodsout['priority_goodsunum'][] = $diff_priority_number; //优先盘盈数量
                $goodsout['priority_goodsuinv'][] = 2; //优先盘盈
                $goodsamout['priority_goodsuamout'] += $diff_priority_number;
            } elseif ($value->stgo_priority_stocktake_number < 0) {
                $goodsout['priority_goodsdid'][] = $value->stgo_goo_id; //优先盘亏id
                $goodsout['priority_goodsdnum'][] = abs($diff_priority_number); //优先盘亏数量
                $goodsout['priority_goodsdinv'][] = 2; //优先盘亏
                $goodsamout['priority_goodsdamout'] += abs($diff_priority_number);
            }
            // 商品待检测盘点数量
            $diff_unchecked_number = $value->stgo_unchecked_stocktake_number;
            $goo_unchecked_number[$value->stgo_goo_id] = $diff_unchecked_number;
            $diff_ware_unchecked_all_stock += $diff_unchecked_number;
            $diff_ware_amount += $diff_unchecked_number;
            // 商品流水
            if ($value->stgo_unchecked_stocktake_number > 0) {
                $goodsout['unchecked_goodsuid'][] = $value->stgo_goo_id; //待检测盘盈id
                $goodsout['unchecked_goodsunum'][] = $diff_unchecked_number; //待检测盘盈数量
                $goodsout['unchecked_goodsuinv'][] = 3; //待检测盘盈
                $goodsamout['unchecked_goodsuamout'] += $diff_unchecked_number;
            } elseif ($value->stgo_unchecked_stocktake_number < 0) {
                $goodsout['unchecked_goodsdid'][] = $value->stgo_goo_id; //待检测盘亏id
                $goodsout['unchecked_goodsdnum'][] = abs($diff_unchecked_number); //待检测盘亏数量
                $goodsout['unchecked_goodsdinv'][] = 3; //待检测盘亏
                $goodsamout['unchecked_goodsdamout'] += abs($diff_unchecked_number);
            }
        }
        foreach ($goodsamout as $k => $v) {
            if ($v > 0) {
                if ($k == 'stock_goodsuamout') { //良品盘盈
                    $outware = 0;
                    $inware = $find_stoc->stoc_ware_id;
                    $outtype = 3;
                    $intype = 2;
                    $surplus->ware_all_stock = $surplus->ware_all_stock + $v;
                    $goo_idarr = $goodsout['stock_goodsuid']; //数组，商品id
                    $goo_number = $goodsout['stock_goodsunum']; //数组，商品数量
                    $inventory = $goodsout['stock_goodsuinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'priority_goodsuamout') { //优先盘盈
                    $outware = 0;
                    $inware = $find_stoc->stoc_ware_id;
                    $outtype = 3;
                    $intype = 2;
                    $surplus->ware_priority_all_stock = $surplus->ware_priority_all_stock + $v;
                    $goo_idarr = $goodsout['priority_goodsuid']; //数组，商品id
                    $goo_number = $goodsout['priority_goodsunum']; //数组，商品数量
                    $inventory = $goodsout['priority_goodsuinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'unchecked_goodsuamout') { //待检测盘盈
                    $outware = 0;
                    $inware = $find_stoc->stoc_ware_id;
                    $outtype = 3;
                    $intype = 2;
                    $surplus->ware_unchecked_all_stock = $surplus->ware_unchecked_all_stock + $v;
                    $goo_idarr = $goodsout['unchecked_goodsuid']; //数组，商品id
                    $goo_number = $goodsout['unchecked_goodsunum']; //数组，商品数量
                    $inventory = $goodsout['unchecked_goodsuinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'stock_goodsdamout') { //良品盘亏
                    $inware = 0;
                    $outware = $find_stoc->stoc_ware_id;
                    $outtype = 2;
                    $intype = 1;
                    $surplus->ware_all_stock = $surplus->ware_all_stock - $v;
                    $goo_idarr = $goodsout['stock_goodsdid']; //数组，商品id
                    $goo_number = $goodsout['stock_goodsdnum']; //数组，商品数量
                    $inventory = $goodsout['stock_goodsdinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'priority_goodsdamout') { //优先盘亏
                    $inware = 0;
                    $outware = $find_stoc->stoc_ware_id;
                    $outtype = 2;
                    $intype = 1;
                    $surplus->ware_priority_all_stock = $surplus->ware_priority_all_stock - $v;
                    $goo_idarr = $goodsout['priority_goodsdid']; //数组，商品id
                    $goo_number = $goodsout['priority_goodsdnum']; //数组，商品数量
                    $inventory = $goodsout['priority_goodsdinv']; //数组，出库类型1良品2优先3待检测
                } elseif ($k == 'unchecked_goodsdamout') { //待检测盘亏
                    $inware = 0;
                    $outware = $find_stoc->stoc_ware_id;
                    $outtype = 2;
                    $intype = 1;
                    $surplus->ware_unchecked_all_stock = $surplus->ware_unchecked_all_stock - $v;
                    $goo_idarr = $goodsout['unchecked_goodsdid']; //数组，商品id
                    $goo_number = $goodsout['unchecked_goodsdnum']; //数组，商品数量
                    $inventory = $goodsout['unchecked_goodsdinv']; //数组，出库类型1良品2优先3待检测
                }
                // 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
                    $v, //出库的商品总量
                    15, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单15盘库单
                    $outtype, //操作类型：1锁定库存2出库3入库4调货5发货
                    $surplus->ware_all_stock, //良品总库存
                    $surplus->ware_lock_quantity, //良品锁定数量
                    $surplus->ware_priority_all_stock, //优先总库存
                    $surplus->ware_priority_lock_quantity, //优先锁定数量
                    $surplus->ware_unchecked_all_stock, //待检测总库存
                    $intype, //出入库类型：1出库，2入库
                    $find_stoc->stoc_waon_class, //[仓库类别]
                    $goo_idarr, //数组，商品id
                    $goo_number, //数组，商品数量
                    $inventory //数组，出库类型1良品2优先3待检测
                );
            }
        }
        // 4.2 查询商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $find_stoc->stoc_ware_id)
            ->where('wago_class', $find_stoc->stoc_waon_class)
            ->whereIn('wago_goo_id', $goo_id)
            ->select('wago_id', 'wago_goo_id', 'wago_stock_number', 'wago_priority_stock_number', 'wago_unchecked_stock_number', 'wago_stock_amount', 'wago_priority_stock_amount', 'wago_unchecked_stock_amount')
            ->get();
        $warehouse_goods = json_decode(json_encode($warehouse_goods), true);
        // 4.3 处理要盘点的商品库存数量
        if (empty($warehouse_goods)) {
            $ware_edit_res = true;
        } else {
            // 4.4 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
            $sql = 'UPDATE `faster_warehouse_goods` SET ';
            $stock_number_sql = ''; //良品库存数量（仓库+仓位）
            $priority_stock_number_sql = ''; //优先库存数量（仓库+仓位）
            $unchecked_stock_number_sql = ''; //待检测数量（仓库+仓位）

            $stock_amount_sql = ''; //仓库良品库存数量
            $priority_stock_amount_sql = ''; //仓库优先库存数量
            $unchecked_stock_amount_sql = ''; //仓库待检测库存数量

            $update_time_sql = '';
            $ids = '';

            foreach ($warehouse_goods as $key => $value) {
                // 要更改的商品库存数量
                $stock_number = $value['wago_stock_number'] + $goo_stock_number[$value['wago_goo_id']];
                $priority_stock_number = $value['wago_priority_stock_number'] + $goo_priority_number[$value['wago_goo_id']];
                $unchecked_stock_number = $value['wago_unchecked_stock_number'] + $goo_unchecked_number[$value['wago_goo_id']];
                if ($stock_number < 0 || $priority_stock_number < 0 || $unchecked_stock_number < 0) {
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '商品盘亏数量超出库存数量']);
                }

                // 更改良品库存数量（仓库+仓位）
                $stock_number_sql = $stock_number_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $stock_number;
                // 更改优先库存数量（仓库+仓位）
                $priority_stock_number_sql = $priority_stock_number_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $priority_stock_number;
                // 更改待检测数量（仓库+仓位）
                $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $unchecked_stock_number;

                // 更改仓库良品库存数量
                $stock_amount_sql = $stock_amount_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $stock_number;
                // 更改仓库优先库存数量
                $priority_stock_amount_sql = $priority_stock_amount_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $priority_stock_number;
                // 更改仓库待检测库存数量
                $unchecked_stock_amount_sql = $unchecked_stock_amount_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $unchecked_stock_number;

                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value['wago_id'] . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $value['wago_id'] . ',';
                // 删除已更改的商品数据
                unset($goo_stock_number[$value['wago_goo_id']]);
            }
            $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $stock_number_sql . ' END,';
            $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $priority_stock_number_sql . ' END,';
            $sql = $sql . ' `wago_unchecked_stock_number`=  CASE `wago_id` ' . $unchecked_stock_number_sql . ' END,';
            $sql = $sql . ' `wago_stock_amount`=  CASE `wago_id` ' . $stock_amount_sql . ' END,';
            $sql = $sql . ' `wago_priority_stock_amount`=  CASE `wago_id` ' . $priority_stock_amount_sql . ' END,';
            $sql = $sql . ' `wago_unchecked_stock_amount`=  CASE `wago_id` ' . $unchecked_stock_amount_sql . ' END,';
            $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
            $ware_edit_res = DB::update($sql);
        }

        // 仓库类别表总库存数量加上 差值数量
        $warehouse_onhand_sql = 'UPDATE `faster_warehouse_onhand` SET  `waon_all_amount`= `waon_all_amount`+' . $diff_ware_amount . ', `waon_stock_fine_amount`= `waon_stock_fine_amount`+' . $diff_ware_all_stock . ' , `waon_stock_priority_amount`= `waon_stock_priority_amount` + ' . $diff_ware_priority_all_stock . ', `waon_stock_unchecked_amount`= `waon_stock_unchecked_amount` + ' . $diff_ware_unchecked_all_stock . ', `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);

        $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'] = $shop_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 ($waon_res && $ware_edit_res && $vore_id && $volo_id) {
            return ['code' => 200, 'msg' => 'success', 'data' => '通过成功'];
        } else {
            return ['code' => 500, 'msg' => 'error', 'data' => '通过失败'];
        }
    }

    // 驳回
    public function reject(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->submitValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 查询信息
        $find_stoc = DB::table('stocktake')
            ->where('stoc_id', $request['stoc_id'])
            ->select('stoc_storage_number', 'stoc_state')
            ->first();
        if ($find_stoc->stoc_state != 2) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前盘库单不是待审核状态']);
        }

        // 驳回
        $update_data['stoc_state'] = 4; //状态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);
        if ($stoc_res) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '盘库单', '驳回', '盘库单：' . $find_stoc->stoc_storage_number . ' 驳回成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '驳回成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '驳回失败']);
        }
    }

    // 删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->submitValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 查询信息
        $find_stoc = DB::table('stocktake')
            ->where('stoc_id', $request['stoc_id'])
            ->select('stoc_storage_number', 'stoc_state')
            ->get();
        foreach ($find_stoc as $key => $value) {
            if ($value->stoc_state == 3) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前盘库单已通过审核']);
            }
            $stoc_storage_number[] = $value->stoc_storage_number;
        }

        DB::beginTransaction();
        $stoc_res = DB::table('stocktake')
            ->where('stoc_id', $request['stoc_id'])
            ->delete();

        $stgo_stoc_res = DB::table('stocktake_goods')
            ->where('stgo_stoc_id', $request['stoc_id'])
            ->delete();

        if ($stoc_res && $stgo_stoc_res) {
            DB::commit();
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '盘库单', '删除', '盘库单：（' . implode(',', $stoc_storage_number) . '）删除成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '删除成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '删除失败']);
        }
    }

    // 打印
    public function print(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStocktakeController;
        $error_message = $verify_data->printValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 盘库单数据
        $find_stoc = DB::table('stocktake as a')
            ->leftJoin('admin as b', 'b.adm_id', '=', 'a.stoc_adm_id')
            ->leftJoin('warehouse as c', 'c.ware_id', '=', 'a.stoc_ware_id')
            ->where('stoc_id', $request['stoc_id'])
            ->select('adm_name', 'ware_name', 'stoc_make_time', 'stoc_state', 'stoc_type', 'stoc_storage_number', 'stoc_differ_number', 'stoc_manner', 'stoc_ware_id', 'stoc_waon_class', 'ware_type')
            ->first();
        // 获取盘库商品数据
        $find_goods = DB::table('stocktake_goods as a')
            ->leftJoin('goods as b', 'a.stgo_goo_id', '=', 'b.goo_id')
            ->where('stgo_stoc_id', $request['stoc_id'])
            ->select('stgo_stock_number', 'stgo_lock_number', 'stgo_stocktake_number', 'goo_class', 'goo_bra_name', 'goo_brse_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'stgo_priority_stock_number', 'stgo_priority_lock_number', 'stgo_unchecked_stock_number', 'stgo_priority_stocktake_number', 'stgo_unchecked_stocktake_number', 'goo_id', 'stgo_wafr_id', 'stgo_goo_id', 'goo_unit')
            ->get()->toArray();
        $data['stoc_data'] = $find_stoc;
        $find_goods = json_decode(json_encode($find_goods), true);
        // 查询系列数据
        $goo_brse_id = array_column($find_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        $goo_id = array_column($find_goods, 'goo_id');
        // 查询商品附属表信息
        $gosu_data = DB::table('goods_subsidiary')
            ->where('gosu_shop_id', $user_info->adm_shop_id)
            ->whereIn('gosu_goo_id', $goo_id)
            ->pluck('gosu_another_name', 'gosu_goo_id')
            ->toArray();
        // 查询仓位名称信息
        $stgo_wafr_id = array_column($find_goods, 'stgo_wafr_id');
        $find_wafr_data = DB::table('warehouse_freight')
            ->where('wafr_shop_id', $user_info->adm_shop_id)
            ->whereIn('wafr_id', $stgo_wafr_id)
            ->where('wafr_delete', 1)
            ->pluck('wafr_name', 'wafr_id')
            ->toArray();
        foreach ($find_goods as $k => $v) {
            if (isset($gosu_data[$v['goo_id']]) && !empty($gosu_data[$v['goo_id']])) { //商品别名
                $find_goods[$k]['goo_name'] = $gosu_data[$v['goo_id']];
            }
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP')) && isset($brse_data[$v['goo_brse_id']])) {
                if (!empty($v['goo_brse_id'])) {
                    if ($v['goo_class'] == 2) {
                        $find_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $find_goods[$k]['goo_name'];
                        unset($find_goods[$k]['goo_brse_id']);
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $find_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $find_goods[$k]['goo_name'];
                            unset($find_goods[$k]['goo_brse_id']);
                        }
                    }
                }
            }
            // 显示品牌名称
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                if ($v['goo_class'] == 2) {
                    $find_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $find_goods[$k]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $find_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $find_goods[$k]['goo_name'];
                    }
                }
            }
            unset($find_goods[$k]['goo_class']);
            // 盘前数量
            $find_goods[$k]['stgo_stock_number'] = $v['stgo_stock_number'] + $v['stgo_lock_number'];
            $find_goods[$k]['stgo_priority_stock_number'] = $v['stgo_priority_stock_number'] + $v['stgo_priority_lock_number'];
            $find_goods[$k]['stgo_unchecked_stock_number'] = $v['stgo_unchecked_stock_number'];
            // 盘后数量
            $find_goods[$k]['stgo_stocktake_number'] = $v['stgo_stock_number'] + $v['stgo_lock_number'] + $v['stgo_stocktake_number'];
            $find_goods[$k]['stgo_priority_stocktake_number'] = $v['stgo_priority_stocktake_number'] + $v['stgo_priority_stock_number'] + $v['stgo_priority_lock_number'];
            $find_goods[$k]['stgo_unchecked_stocktake_number'] = $v['stgo_unchecked_stocktake_number'] + $v['stgo_unchecked_stock_number'];
            // 仓位名称
            if (isset($find_wafr_data[$v['stgo_wafr_id']])) {
                $find_goods[$k]['wafr_name'] = $find_wafr_data[$v['stgo_wafr_id']];
            } else {
                $find_goods[$k]['wafr_name'] = '';
            }
        }
        $data['goods_data'] = $find_goods;
        Common::addLog($user_info, getRealIp($request), '盘库单', '打印', $find_stoc->stoc_storage_number . '打印成功');
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    // 生成凭证
    public function workOrderVoucher(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id1
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        ignore_user_abort();
        set_time_limit(0);
        // 查询工单表,完成已通过的数据
        $find_wor_data = DB::table('stocktake')
            ->where('stoc_cid', $user_info->adm_cid)
            ->where('stoc_shop_id', $user_info->adm_shop_id)
            ->where('stoc_state', 3)
            ->where('stoc_type', '!=', 3)
            ->whereIn('stoc_id', [159, 165, 166])
            ->select('stoc_id', 'stoc_cid', 'stoc_superior_shop_id', 'stoc_shop_id', 'stoc_adm_id', 'stoc_storage_number', 'stoc_type', 'stoc_differ_number', 'stoc_ware_id', 'stoc_waon_class', 'stoc_create_time')
            ->get()->toArray();
        DB::beginTransaction();
        $cost_price = 0;
        foreach ($find_wor_data as $key => $value) {
            // 根据盘库单id,查询商品数据
            $find_stgo_data = DB::table('stocktake_goods')
                ->where('stgo_stoc_id', $value->stoc_id)
                ->select('stgo_goo_id', 'stgo_stock_number', 'stgo_stocktake_number', 'stgo_priority_stock_number', 'stgo_priority_stocktake_number', 'stgo_unchecked_stock_number', 'stgo_unchecked_stocktake_number', 'stgo_goo_id')
                ->get()->toArray();
            if ($find_stgo_data) {
                $stocktake_cost_price = 0;
                $priority_cost_price = 0;
                $unchecked_cost_price = 0;
                foreach ($find_stgo_data as $kkkk => $vvvv) {
                    // 获取当前月份的成本价
                    $find_ense_end_price = DB::table('enters_sells_saves')
                        ->where('ense_goo_id', $vvvv->stgo_goo_id)
                        ->where('ense_goo_warehouse', $value->stoc_ware_id)
                        ->where('ense_goo_waretype', $value->stoc_waon_class)
                        ->where('ense_order_number', $value->stoc_storage_number)
                        ->orderBy('ense_id', 'desc')
                        ->value('ense_end_price');
                    if ($find_ense_end_price) {
                        $find_ense_end_price = sprintf('%.2f', $find_ense_end_price);
                    } else {
                        $find_ense_end_price = 0;
                    }
                    $stocktake_cost_price += $find_ense_end_price * $vvvv->stgo_stocktake_number;
                    $priority_cost_price += $find_ense_end_price * $vvvv->stgo_priority_stocktake_number;
                    $unchecked_cost_price += $find_ense_end_price * $vvvv->stgo_unchecked_stocktake_number;
                    $cost_price = $stocktake_cost_price + $priority_cost_price + $unchecked_cost_price;
                }
                // 凭证单据报表
                // 判断凭证单据是否存在
                $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', $value->stoc_id)
                    ->where('vore_ord_number', $value->stoc_storage_number)
                    ->where('vore_order_type', 6)
                    ->where('vore_state', 1)
                    ->select('vore_id', 'vore_wor_id', 'vore_wor_number')
                    ->first();
                if (empty($vore_id)) {
                    $vore_data['vore_cid'] = $value->stoc_cid; //公司id
                    $vore_data['vore_superior_shop_id'] = $value->stoc_superior_shop_id; //总店id
                    $vore_data['vore_shop_id'] = $value->stoc_shop_id; //门店id
                    $vore_data['vore_create_id'] = $value->stoc_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'] = $value->stoc_id; //订单id
                    $vore_data['vore_ord_number'] = $value->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'] = $value->stoc_create_time;
                    $vore_id = DB::table('voucher_receipts')->insertGetId($vore_data);
                    // 凭证借贷表(结算金额)
                    if ($value->stoc_type == '1') { //盘盈
                        $volo_data[0]['volo_shop_id'] = $value->stoc_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); //贷方金额
                    } elseif ($value->stoc_type == '2') { //盘亏
                        $volo_data[0]['volo_shop_id'] = $value->stoc_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'] = $value->stoc_create_time; //更新时间
                    $volo_id = DB::table('voucher_loan')->insert($volo_data);
                } else {
                    $vore_id = true;
                    $volo_id = true;
                }
            } else {
                $vore_id = true;
                $volo_id = true;
            }
        }
        if ($vore_id && $volo_id) {
            DB::commit();
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '生成凭证成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '生成凭证失败']);
        }
    }

    // 盘库单期初导入
    public function openingImport(Request $request)
    {
        ignore_user_abort();
        set_time_limit(0);

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $file = $request->file('file');

        if ($file->isValid()) {
            // 获取表格的大小，限制上传表格的大小5M
            $file_size = $_FILES['file']['size'];
            if ($file_size > 5 * 1024 * 1024) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '文件大小不能超过5M']);
            }

            // 限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '仅允许上传以xlsx结尾的后缀文件']);
            }

            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');
            $filename = $_FILES['file']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            if ($highestRow < 2) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '未获取到商品数据']);
            }
            if ($highestRow > 482) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '一次最多导入480条数据']);
            }

            // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
            $usersExits = [];
            $encode_arr = []; //系统编码
            $encode = []; //已存在的编码

            DB::beginTransaction();

            $stocktake_number = 0;  //良品盘点数量
            $priority_stocktake_number = 0;  //优先盘点数量
            $num = 0;
            for ($j = 2; $j <= $highestRow; $j++) {
                // 仓库名称
                $request['ware_name'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                // 仓库类别
                $request['ware_class'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                // 商品品类
                $request['goo_cate_name'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
                if (empty($request['goo_cate_name'])) {
                    DB::rollBack();
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '商品品类必填']);
                }
                // 查询商品品类是否存在
                $request['goo_cate_id'] = DB::table('category')
                    ->where(function ($query) use ($user_info) {
                        $query->where('cate_cid', $user_info->adm_cid)
                            ->orWhere('cate_cid', 0);
                    })
                    ->where(function ($query) use ($shop_id) {
                        $query->where('cate_shop_id', $shop_id)
                            ->orWhere('cate_shop_id', 0);
                    })
                    ->where('cate_name', $request['goo_cate_name'])
                    ->where('cate_delete', 1)
                    ->where('cate_state', 1)
                    ->value('cate_id');
                if (empty($request['goo_cate_id'])) {
                    // 新增品类数据
                    $cate_add_data['cate_cid'] = $user_info->adm_cid; //所属企业id
                    $cate_add_data['cate_superior_shop_id'] = $shop_id; //所属总店id或加盟店id
                    $cate_add_data['cate_shop_id'] = $user_info->adm_shop_id; //所属门店id
                    $cate_add_data['cate_parent_id'] = 0; //隶属上级id
                    $cate_add_data['cate_name'] = $request['goo_cate_name']; //品类名称
                    // 判断隶属上级
                    if ($cate_add_data['cate_parent_id']) {
                        // 查找隶属品类是第几级
                        $cate_rank = DB::table('category')
                            ->where('cate_id', $cate_add_data['cate_parent_id'])
                            ->select('cate_rank')
                            ->first();

                        if ($cate_rank->cate_rank >= 3) {
                            return response()->json(["code" => 500, 'msg' => 'error', 'data' => '所属品类已超过三级']);
                        }
                        $cate_add_data['cate_rank'] = $cate_rank->cate_rank + 1;
                    } else {
                        $cate_add_data['cate_rank'] = 1;
                    }
                    // 新增品类
                    $request['goo_cate_id'] =  DB::table('category')->insertGetid($cate_add_data);
                    // 新增品类关联数据
                    $caco_data['caco_shop_id'] = $user_info->adm_shop_id;
                    $caco_data['caco_cate_id'] = $request['goo_cate_id'];
                    $caco_res = DB::table('category_correlation')->insert($caco_data);
                    if (!$request['goo_cate_id'] || !$caco_res) {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => 'error', 'data' => '新品牌添加失败']);
                    }
                    unset($cate_add_data);
                    unset($caco_data);
                }
                // 商品品牌
                $request['goo_bra_name'] = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());
                if (empty($request['goo_bra_name'])) {
                    $request['goo_bra_name'] = ''; //品牌名称
                    $request['goo_bra_id'] = 0; //品牌id
                    $request['goo_brse_id'] = 0; //品牌系列id
                } else {
                    // 查询商品品牌是否存在
                    $bra_id = DB::table('brand')
                        ->where(function ($query) use ($user_info) {
                            $query->where('bra_cid', $user_info->adm_cid)
                                ->orWhere('bra_cid', 0);
                        })
                        ->where(function ($query) use ($user_info) {
                            $query->where('bra_shop_id', $user_info->adm_shop_id)
                                ->orWhere('bra_shop_id', 0);
                        })
                        ->where('bra_name', $request['goo_bra_name'])
                        ->where('bra_delete', 1)
                        ->where('bra_state', 1)
                        ->value('bra_id');
                    if (empty($bra_id)) {
                        // 新增品牌数据
                        $bra_data['bra_cid'] = $user_info->adm_cid; //所属企业id
                        $bra_data['bra_superior_shop_id'] = $shop_id; //所属总店id
                        $bra_data['bra_shop_id'] = $user_info->adm_shop_id; //所属门店id
                        $bra_data['bra_name'] = $request['goo_bra_name']; //品牌名称
                        $bra_id = DB::table('brand')->insertGetId($bra_data);
                        // 新增品牌关联表数据
                        $brco_add['brco_bra_id'] = $bra_id;
                        $brco_add['brco_shop_id'] = $shop_id;
                        $brco_id = DB::table('brand_correlation')->insertGetId($brco_add);
                        if (!$bra_id || !$brco_id) {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '新品牌添加失败']);
                        }
                        unset($bra_data);
                        unset($brco_add);
                    }
                    $request['goo_bra_id'] = $bra_id;
                    if ($request['goo_bra_id']) {
                        // 品牌系列
                        $brse_name = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                        if (!empty($brse_name)) {
                            $brse_id = DB::table('brand_serie')
                                ->where(function ($query) use ($user_info) {
                                    $query->where('brse_cid', $user_info->adm_cid)
                                        ->orWhere('brse_cid', 0);
                                })
                                ->where(function ($query) use ($user_info) {
                                    $query->where('brse_shop_id', $user_info->adm_shop_id)
                                        ->orWhere('brse_shop_id', 0);
                                })
                                ->where('brse_bra_id', $request['goo_bra_id'])
                                ->where('brse_name', $brse_name)
                                ->where('brse_delete', 1)
                                ->where('brse_state', 1)
                                ->value('brse_id');
                            if (empty($brse_id)) {
                                // 新增品牌系列数据
                                $brse_data['brse_cid'] = $user_info->adm_cid; //所属企业id
                                $brse_data['brse_superior_shop_id'] = $shop_id; //所属总店id
                                $brse_data['brse_shop_id'] = $user_info->adm_shop_id; //所属门店id
                                $brse_data['brse_bra_id'] = $request['goo_bra_id']; //所属品牌id
                                $brse_data['brse_cate_id'] = $request['goo_cate_id']; //一级品类id
                                $brse_data['brse_name'] = $brse_name; //系列名称
                                $brse_id = DB::table('brand_serie')->insertGetId($brse_data);
                                // 新增品牌系列关联数据
                                $brsc_add['brsc_shop_id'] = $user_info->adm_shop_id;
                                $brsc_add['brsc_brse_id'] = $brse_id;
                                $brsc_id = DB::table('brand_serie_correlation')->insertGetId($brsc_add);
                                if (!$brse_id || !$brsc_id) {
                                    DB::rollBack();
                                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '系列添加失败']);
                                }
                                unset($brse_data);
                                unset($brsc_add);
                            }
                            $request['goo_brse_id'] = $brse_id;
                        } else {
                            $request['goo_brse_id'] = 0; //品牌系列id
                        }
                    } else {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => 'error', 'data' => '请选择所属品牌']);
                    }
                }
                // 商品名称
                $request['goo_name'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());
                if (empty($request['goo_name'])) {
                    DB::rollBack();
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '商品名称必填']);
                }
                // 检索编码
                $request['goo_goods_encode'] = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue());
                // 判断检索编码是否存在
                if (!empty($request['goo_goods_encode'])) {
                    $find_goo = DB::table('goods')
                        ->where('goo_delete', 1)
                        ->where(function ($query) use ($user_info) {
                            $query->where('goo_shop_id', 0)
                                ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                        })
                        ->where('goo_goods_encode', $request['goo_goods_encode'])
                        ->select('goo_id')
                        ->first();
                    if ($find_goo) {
                        $request['goods_ids'] = $find_goo->goo_id;
                    }
                } else {
                    // 1. 判断商品名称是否存在
                    $find_goo = DB::table('goods')
                        ->where('goo_delete', 1)
                        ->where(function ($query) use ($user_info) {
                            $query->where('goo_shop_id', 0)
                                ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                        })
                        ->where('goo_cate_id', $request['goo_cate_id'])
                        ->where('goo_bra_id', $request['goo_bra_id'])
                        ->where('goo_brse_id', $request['goo_brse_id'])
                        ->where('goo_name', $request['goo_name'])
                        ->select('goo_id')
                        ->first();
                    if ($find_goo) {
                        $request['goods_ids'] = $find_goo->goo_id;
                    }
                }
                if (empty($find_goo)) {
                    // 2 新增一个商品数据
                    $goo_add_data['goo_cid'] = $user_info->adm_cid;
                    $goo_add_data['goo_superior_shop_id'] = $user_info->adm_shop_id;
                    $goo_add_data['goo_shop_id'] = $user_info->adm_shop_id;
                    $goo_add_data['goo_name'] = $request['goo_name']; //商品名称
                    $goo_add_data['goo_type'] = 1;   //1正常商品2赠品商品3活动商品4旧货商品
                    $goo_add_data['goo_goods_encode'] = $request['goo_goods_encode'] ? $request['goo_goods_encode'] : '';   //检索编码
                    $goo_add_data['goo_cate_id'] = $request['goo_cate_id']; //所属品类id
                    $goo_add_data['goo_cate_name'] = $request['goo_cate_name']; //品类名称
                    $goo_add_data['goo_price'] = $request['goo_price'] * 100;   //商品零售价格
                    $goo_add_data['goo_system_code'] = str_pad($user_info->adm_cid, '4', '0', STR_PAD_RIGHT) . str_pad($user_info->adm_shop_id, '5', '0', STR_PAD_RIGHT) . rand(10, 99) . rand(100000000, 999999999); //系统编码
                    // 判断是否选择商品品牌
                    if ($request['goo_bra_id']) {
                        $goo_add_data['goo_bra_id'] = $request['goo_bra_id'];
                        $goo_add_data['goo_bra_name'] = $request['goo_bra_name'];
                    }
                    // 判断是否选择品牌系列
                    if ($request['goo_brse_id']) {
                        if (empty($request['goo_bra_id'])) {
                            return ['code' => 500, 'msg' => 'error', 'data' => '请选择所属品牌'];
                        }
                        $goo_add_data['goo_brse_id'] = $request['goo_brse_id'];
                    }
                    // 新增商品
                    $goo_id =  DB::table('goods')->insertGetId($goo_add_data);
                    $request['goods_ids'] = $goo_id;
                    // 添加旧货商品
                    $goo_add_data['goo_fid'] = $goo_id;
                    $goo_add_data['goo_type'] = 4; //1正常商品2赠品商品3活动商品4旧货商品
                    $goo_add_data['goo_system_code'] = str_pad($user_info->adm_cid, '4', '0', STR_PAD_RIGHT) . str_pad($user_info->adm_shop_id, '5', '0', STR_PAD_RIGHT) . rand(10, 99) . rand(100000000, 999999999); //系统编码
                    // 新增商品
                    $goo_id_three =  DB::table('goods')->insertGetId($goo_add_data);
                    // 查询正常商品在商品附属表是否存在
                    $gosu_id = DB::table('goods_subsidiary')
                        ->where('gosu_goo_id', $goo_id)
                        ->where('gosu_shop_id', $user_info->adm_shop_id)
                        ->value('gosu_id');
                    if ($gosu_id) {
                        $gosu_add_data['gosu_goo_id'] = $goo_id;
                        $gosu_add_data['gosu_update_time'] = date('Y-m-d H:i:s');
                        $goaf_res = DB::table('goods_subsidiary')
                            ->where('gosu_goo_id', $goo_id)
                            ->where('gosu_shop_id', $user_info->adm_shop_id)
                            ->update($gosu_add_data);
                    } else {
                        $gosu_add_data['gosu_shop_id'] = $user_info->adm_shop_id;
                        $gosu_add_data['gosu_goo_id'] = $goo_id;
                        $gosu_add_data['gosu_price'] = $goo_add_data['goo_price'];
                        $goaf_res = DB::table('goods_subsidiary')->insert($gosu_add_data);
                    }
                    // 查询旧货商品在商品附属表是否存在
                    $junk_gosu_id = DB::table('goods_subsidiary')
                        ->where('gosu_goo_id', $goo_id_three)
                        ->where('gosu_shop_id', $user_info->adm_shop_id)
                        ->value('gosu_id');
                    if ($junk_gosu_id) {
                        $gosu_add_data['gosu_goo_id'] = $goo_id_three;
                        $gosu_add_data['gosu_update_time'] = date('Y-m-d H:i:s');
                        $junk_goaf_res = DB::table('goods_subsidiary')
                            ->where('gosu_goo_id', $goo_id_three)
                            ->where('gosu_shop_id', $user_info->adm_shop_id)
                            ->update($gosu_add_data);
                    } else {
                        $gosu_add_data['gosu_shop_id'] = $user_info->adm_shop_id;
                        $gosu_add_data['gosu_goo_id'] = $goo_id_three;
                        $gosu_add_data['gosu_price'] = $goo_add_data['goo_price'];
                        $junk_goaf_res = DB::table('goods_subsidiary')->insert($gosu_add_data);
                    }
                    unset($goo_add_data);
                    unset($gosu_add_data);
                    // 4.商品所属品类数量更改
                    $find_caco_id = DB::table('category_correlation')
                        ->where('caco_cate_id', $request['goo_cate_id'])
                        ->where('caco_shop_id', $user_info->adm_shop_id)
                        ->value('caco_id');
                    if ($find_caco_id) {
                        $res_cate = DB::table('category_correlation')
                            ->where('caco_cate_id', $request['goo_cate_id'])
                            ->where('caco_shop_id', $user_info->adm_shop_id)
                            ->increment('caco_goods_number', 2);
                    } else {
                        // 没有数据，新增数据
                        $add_caco_data['caco_shop_id'] = $user_info->adm_shop_id;
                        $add_caco_data['caco_cate_id'] = $request['goo_cate_id'];
                        $add_caco_data['caco_goods_number'] = 2;
                        $add_caco_data['caco_update_time'] = date('Y-m-d H:i:s');
                        $res_cate = DB::table('category_correlation')->insert($add_caco_data);
                        unset($add_caco_data);
                        unset($res_cate);
                    }

                    // 5.商品所属品牌数量更改
                    if ($request['goo_bra_id']) {
                        // 查询关联表是否有数据
                        $find_brco_id = DB::table('brand_correlation')
                            ->where('brco_bra_id', $request['goo_bra_id'])
                            ->where('brco_shop_id', $user_info->adm_shop_id)
                            ->value('brco_id');
                        if ($find_brco_id) {
                            // 有数据增加数量
                            $res_brand = DB::table('brand_correlation')
                                ->where('brco_bra_id', $request['goo_bra_id'])
                                ->where('brco_shop_id', $user_info->adm_shop_id)
                                ->increment('brco_goods_number', 2);
                        } else {
                            // 没有数据，新增数据
                            $add_brco_data['brco_shop_id'] = $user_info->adm_shop_id;
                            $add_brco_data['brco_bra_id'] = $request['goo_bra_id'];
                            $add_brco_data['brco_goods_number'] = 2;
                            $add_brco_data['brco_update_time'] = date('Y-m-d H:i:s');
                            $res_brand = DB::table('brand_correlation')->insert($add_brco_data);
                            unset($add_brco_data);
                            unset($res_brand);
                        }
                    } else {
                        $res_brand = true;
                    }

                    // 商品所属品牌系列数量更改
                    if ($request['goo_brse_id']) {
                        // 查询系列关联表是否有数据
                        $find_brsc_id = DB::table('brand_serie_correlation')
                            ->where('brsc_brse_id', $request['goo_brse_id'])
                            ->where('brsc_shop_id', $user_info->adm_shop_id)
                            ->value('brsc_id');
                        if ($find_brsc_id) {
                            // 有数据增加数量
                            $res_brand_serie = DB::table('brand_serie_correlation')
                                ->where('brsc_brse_id', $request['goo_brse_id'])
                                ->where('brsc_shop_id', $user_info->adm_shop_id)
                                ->increment('brsc_goods_number', 2);
                        } else {
                            // 没有数据，新增数据
                            $add_brsc_data['brsc_shop_id'] = $user_info->adm_shop_id;
                            $add_brsc_data['brsc_brse_id'] = $request['goo_brse_id'];
                            $add_brsc_data['brsc_goods_number'] = 2;
                            $add_brsc_data['brsc_update_time'] = date('Y-m-d H:i:s');
                            $res_brand_serie = DB::table('brand_serie_correlation')->insert($add_brsc_data);
                            unset($add_brsc_data);
                            unset($res_brand_serie);
                        }
                    } else {
                        $res_brand_serie = true;
                    }
                }

                // 期初价格
                $request['goo_price'] = trim($objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue());
                if (empty($request['goo_price'])) {
                    $request['goo_price'] = 0;
                }
                // 良品库存
                $request['stock_number'] = trim($objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue());
                if (empty($request['stock_number'])) {
                    $request['stock_number'] = 0;
                }
                // 优先库存
                $request['priority_stock_number'] = trim($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue());
                if (empty($request['priority_stock_number'])) {
                    $request['priority_stock_number'] = 0;
                }
                // 添加期初金额
                $add_ense_data['ense_shop_id'] = $user_info->adm_shop_id;
                $add_ense_data['ense_goo_id'] = $request['goods_ids'];
                $add_ense_data['ense_new_amount'] = $request['goo_goods_encode'];
                $add_ense_data['ense_goo_number'] = $request['goo_goods_encode'];
                $add_ense_data['ense_new_price'] = $request['goo_price'];
                $find_enses_datas = DB::table('enters_sells_saves_price_total')
                    ->where('ense_shop_id', $user_info->adm_shop_id)
                    ->where('ense_goo_id', $request['goods_ids'])
                    ->value('ense_goo_id');
                if (empty($find_enses_datas)) {
                    $add_data_res = DB::table('enters_sells_saves_price_total')->insert($add_ense_data);
                } else {
                    $add_data_res = DB::table('enters_sells_saves_price_total')
                        ->where('ense_shop_id', $user_info->adm_shop_id)
                        ->where('ense_goo_id', $request['goods_ids'])
                        ->update($add_ense_data);
                }
                unset($add_ense_data);
                unset($add_data_res);
                // 根据仓库名称查询对应的仓库id
                $find_ware_id = DB::table('warehouse')
                    ->where('ware_cid', $user_info->adm_cid)
                    ->where('ware_shop_id', $user_info->adm_shop_id)
                    ->where('ware_name', $request['ware_name'])
                    ->value('ware_id');
                // 根据仓库列表名称查询仓库类别序号
                $find_waon_class = DB::table('warehouse_class')
                    ->where('wacl_cid', $user_info->adm_cid)
                    ->where('wacl_shop_id', $user_info->adm_shop_id)
                    ->where('wacl_class_name', $request['ware_class'])
                    ->value('wacl_class_numerical');
                // 查询仓库商品数量
                $find_wago_data = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $find_ware_id)
                    ->where('wago_class', $find_waon_class)
                    ->where('wago_goo_id', $request['goods_ids'])
                    ->select('wago_id', 'wago_class', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                    ->first();
                if (empty($find_wago_data)) {
                    $add_data['wago_ware_id'] = $find_ware_id;
                    $add_data['wago_class'] = $find_waon_class;
                    $add_data['wago_goo_id'] = $request['goods_ids'];
                    $wago_id = DB::table('warehouse_goods')->insert($add_data);
                    unset($add_data);
                    unset($wago_id);
                    $find_wago_data = DB::table('warehouse_goods')
                        ->where('wago_ware_id', $find_ware_id)
                        ->where('wago_class', $find_waon_class)
                        ->where('wago_goo_id', $request['goods_ids'])
                        ->select('wago_id', 'wago_class', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                        ->first();
                }
                // 查询仓库对应的仓位商品数据
                $wafr_data = DB::table('warehouse_freight_goods')
                    ->where('wafg_ware_id', $find_ware_id)
                    ->where('wafg_wago_id', $find_wago_data->wago_id)
                    ->where('wafg_class', $find_waon_class)
                    ->get()->toArray();
                // 仓位商品表中没有仓库对应的商品
                $find_wafr_id = DB::table('warehouse_freight')
                    ->where('wafr_ware_id', $find_ware_id)
                    ->where('wafr_shop_id', $shop_id)
                    ->select('wafr_id')
                    ->first();
                if (empty($wafr_data)) {
                    $wafg_add_data['wafg_wafr_id'] = $find_wafr_id->wafr_id; //仓位id
                    $wafg_add_data['wafg_wago_id'] = $find_wago_data->wago_id; //仓库商品id
                    $wafg_add_data['wafg_ware_id'] = $find_ware_id; //仓库id
                    $wafg_add_data['wafg_class'] = $find_wago_data->wago_class; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                    $wafg_add_data['wafg_goo_id'] = $request['goods_ids']; //商品id
                    // 仓位商品表中新增商品数据
                    $res = DB::table('warehouse_freight_goods')->insert($wafg_add_data);
                    unset($wafg_add_data);
                    unset($res);
                }
                unset($wafr_data);
                // 新增盘库商品表
                $stgo_data[$num]['stgo_goo_id'] = $request['goods_ids']; //商品id
                $stgo_data[$num]['stgo_wafr_id'] = $find_wafr_id->wafr_id; //仓位id
                $stgo_data[$num]['stgo_stock_number'] = $find_wago_data->wago_stock_number;
                $stgo_data[$num]['stgo_lock_number'] = $find_wago_data->wago_lock_quantity;
                $stgo_data[$num]['stgo_priority_stock_number'] = $find_wago_data->wago_priority_stock_number;
                $stgo_data[$num]['stgo_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity;
                $stgo_data[$num]['stgo_unchecked_stock_number'] = $find_wago_data->wago_unchecked_stock_number;
                $stgo_data[$num]['stgo_stocktake_number'] = intval($request['stock_number']); //良品盘点数量
                $stgo_data[$num]['stgo_priority_stocktake_number'] = intval($request['priority_stock_number']); //优先盘点数量
                $stgo_data[$num]['stgo_update_time'] = date('Y-m-d H:i:s'); //更新时间
                if (!empty($request['stock_number'])) {
                    $stocktake_number = $stocktake_number + intval($request['stock_number']);
                }
                if (!empty($request['priority_stock_number'])) {
                    $priority_stocktake_number = $stocktake_number + intval($request['priority_stock_number']);
                }
                $num++;
            }
            $stoc_differ_number = $stocktake_number + $priority_stocktake_number; //损益数量
            $stoc_add_data['stoc_cid'] = $user_info->adm_cid; //所属企业id
            $stoc_add_data['stoc_superior_shop_id'] = $shop_id; //所属总店id
            $stoc_add_data['stoc_shop_id'] = $user_info->adm_shop_id; //所属门店id
            $stoc_add_data['stoc_adm_id'] = $user_info->adm_id; //盘库人id
            $stoc_add_data['stoc_storage_number'] = 'P' . truncateFill($user_info->adm_shop_id, 2) . date('mdHis') . truncateFill($user_info->adm_id, 2) . rand(10000, 99999); //盘库单号
            $stoc_add_data['stoc_type'] = 1; //类型：1盘盈2盘亏3盘平
            $stoc_add_data['stoc_manner'] = 2; //盘库方式：1部分盘2通盘
            $stoc_add_data['stoc_differ_number'] = $stoc_differ_number; //损益数量
            $stoc_add_data['stoc_state'] = 2; //状态1保存/待提交 2提交/待审核 3通过4驳回
            $stoc_add_data['stoc_ware_id'] = $find_ware_id; //盘点仓库id
            $stoc_add_data['stoc_waon_class'] = 1; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
            $stoc_add_data['stoc_is_import'] = 1; //是否导入1是2否
            $stoc_add_data['stoc_make_time'] = date('Y-m-d H:i:s'); //盘库时间
            // 新增盘库单
            $stoc_res =  DB::table('stocktake')->insertGetId($stoc_add_data);
            foreach ($stgo_data as $key => $value) {
                $stgo_data[$key]['stgo_stoc_id'] = $stoc_res;
            }
            $stgo_res =  DB::table('stocktake_goods')->insert($stgo_data);
            unset($stgo_data);
            unset($stoc_add_data);
            if (!$stgo_res) {
                DB::rollBack();
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '上传有误，请重新上传001！']);
            }
            Common::addLog($user_info, getRealIp($request), '商品列表', '导入', '导入商品成功');
            DB::commit();
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '上传成功', 'num' => $highestRow - 2, 'encode' => $encode]);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '上传有误，请重新上传002！']);
        }
    }

    // 盘库单期初导入通过
    public function openingPass($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();

        // 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);
        // 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_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $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' => 'error', '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::additionImport(
                    $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::additionImport(
                    $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::additionImport(
                    $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::additionImport(
                    $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'] = $shop_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 ($waon_res && $vore_id && $volo_id) {
            return ['code' => 200, 'msg' => 'success', 'data' => '通过成功'];
        } else {
            return ['code' => 500, 'msg' => 'error', 'data' => '通过失败'];
        }
    }

}
