<?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\VerifyMyWarehouseController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Api\StockSellStorageGoods;
use App\Http\Models\Api\Export;
use App\Http\Models\Services\PublicSearch;
use App\Http\Models\Api\WarehouseFreight;
use App\Http\Controllers\Api\WarehouseManage\StocktakeController;
// use App\Http\Models\Services\WarehouseManage\OutinStockLock;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use App\Http\Models\Api\WarehouseManage\Stocktake;
use App\Services\Business\WashMyWarehouseService;

// 我的仓库
class MyWarehouseController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $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->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $post['string'] = 'ware_';
        $post['user_info'] = $user_info;
        $type = 1;
        $where_data = whereFunction($post,$type);
        
        $search_data = $request->all();
        $page_size  = (int) $request->input('show_count', 10);
        // 获取有权限的仓库id
        $my_ware_id = DB::table('admin_set')
            ->where('adms_adm_id', $user_info->adm_id)
            ->where('adms_shop_id', $user_info->adm_shop_id)
            ->value('adms_myware_id');
        // $my_ware_id = json_decode(json_encode($my_ware_id, true), true);
        $my_ware_id =  explode(",", $my_ware_id);
        $list_data = DB::table('warehouse as a')
            ->where('ware_cid', $user_info->adm_cid)
            ->whereIn($where_data['string'], $where_data['shop_id'])
            ->whereIn('ware_id', $my_ware_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ware_name'])) {
                    $query->where('ware_name', 'like', '%' . $search_data['ware_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ware_type'])) {
                    $query->where('ware_type', $search_data['ware_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ware_state'])) {
                    $query->where('ware_state', $search_data['ware_state']);
                }
            })
            ->select('ware_id', 'ware_name', 'ware_freight_space', 'ware_type', 'ware_state', 'ware_default', 'ware_master', 'ware_address', 'ware_license', 'ware_leader_id', 'ware_goo_amount')
            ->orderBy('ware_id', 'desc')
            ->paginate($page_size);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $page_size;       //一页显示多少个

        $data = $list_data->items();
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($data) {
            // 获取出入库记录的仓库id
            $ware_id = array_column($data, 'ware_id');

            // 查询仓库信息
            $find_ware = DB::table('warehouse_onhand')
                ->whereIn('waon_ware_id', $ware_id)
                ->where('waon_class', 1)
                ->select('waon_ware_id', 'waon_all_amount', 'waon_class', 'waon_warn_state')
                ->get()->toArray();
            // 查询仓库类别对应的名称
            $wacl_class_numerical = array_unique(array_column($find_ware, 'waon_class'));
            $find_wacl = DB::table('warehouse_class')
                ->where('wacl_cid', $user_info->adm_cid)
                ->where('wacl_shop_id', $user_info->adm_shop_id)
                ->whereIn('wacl_class_numerical', $wacl_class_numerical)
                ->pluck('wacl_class_name', 'wacl_class_numerical')->toArray();

            foreach ($find_ware as $key => $value) {
                $find_ware[$key]->waon_class_name = $find_wacl[$value->waon_class];
            }
            $data_info['warehouse_onhand'] = $find_ware;
            //查询仓库的商品个数 20230525
            $warehouse_goo_num = DB::table('warehouse_goods')
                ->whereIn('wago_ware_id', $ware_id)
                ->where('wago_class', 1)
                ->where(function ($query) use ($ware_id) {
                    $query->where('wago_stock_number', '>', 0)
                        ->orWhere('wago_lock_quantity', '>', 0)
                        ->orWhere('wago_priority_stock_number', '>', 0)
                        ->orWhere('wago_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_stock_number', '>', 0)
                        ->orWhere('wago_freight_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_priority_stock_number', '>', 0)
                        ->orWhere('wago_freight_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_unchecked_stock_number', '>', 0);
                })
                ->groupBy('wago_ware_id')
                ->select('wago_ware_id', DB::raw('count(wago_ware_id) as num'))
                ->pluck(DB::raw('count(wago_ware_id) as num'), 'wago_ware_id')->toArray();
            $data = json_decode(json_encode($data), true);
            foreach ($data as $k => $v){
                $data[$k]['goods_num'] = 0;
                $data[$k]['ware_goo_amount'] = number_format($data[$k]['ware_goo_amount'],2) . ' 元';
                if(isset($warehouse_goo_num[$v['ware_id']])){
                    $data[$k]['goods_num'] = $warehouse_goo_num[$v['ware_id']];
                }
                $adm_id = explode(',',$v['ware_leader_id']);
                $adm_name = DB::table('admin')
                    ->whereIn('adm_id', $adm_id)
                    ->select('adm_name', 'adm_phone', 'adm_id')
                    ->get()->toArray();
                $new_adm_name = array_column($adm_name, 'adm_name');
                $adm_phone = array_column($adm_name, 'adm_phone');
                $new_adm_name =  implode(',', $new_adm_name);
                $adm_phone =  implode(',', $adm_phone);
                $data[$k]['adm_name'] = $new_adm_name;
                $data[$k]['adm_phone'] = $adm_phone;
                $data[$k]['adm_data'] = $adm_name;
                $buttonData = [];
                if($v['ware_type'] != 2){
                    $buttonData[] = 'edit';//编辑仓库
                }
                $buttonData[] = 'goodsList';//查看库存
                if($v['ware_type'] == 1){
                    $buttonData[] = 'addFreight';//仓位设置
                    $buttonData[] = 'freightGoodsList';//仓位商品
                }
                if($v['ware_state'] == 1 && $v['ware_type'] != 2){
                    $buttonData[] = 'stop';//停用仓库
                }
                if($v['ware_state'] == 2 && $v['ware_type'] != 2){
                    $buttonData[] = 'start';//启用仓库
                }
                if($v['ware_type'] == 1){
                    $buttonData[] = 'goodsWarning';//库存预警
                }
                $button = CommonService::getListButton($buttonData,$list_button);
                $data[$k]['button_one'] = $button['button_one']??[];
                $data[$k]['button_two'] = $button['button_two']??[];
                $data[$k]['button_three'] = $button['button_three']??[];
            }
        }

        $data_info['data'] = $data;
        // 查询是否设置主仓
        $set_master = DB::table('warehouse')
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_superior_shop_id', $shop_id)
            ->where('ware_master', 2)
            ->value('ware_id');
        $data_info['set_master'] = $set_master ? 1 : 2; //是否设置主仓：1已设置2未设置

        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' => '暂无数据', 'list_button' => $list_button]);
        }
    }

    // 查看仓库商品
    public function goodsList(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->goodsListValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        $search_data = $request->all();
        $waog_stock_type = true; //查询库存数量状态值：true查询有库存数量的，false查询所有的
        $wago_type = $request->input('wago_type', 1); //wago_type:1查询有库存数量的2查询所有的3查询库存数量为0的
        $list_data = DB::table('warehouse_goods as a')
            ->leftJoin('goods as b', 'b.goo_id', '=', 'a.wago_goo_id')
            ->where('wago_ware_id', $request['ware_id'])
            ->where('wago_class', $request['waon_class'])
            ->where(function ($query) use ($wago_type) {
                if ($wago_type == 1) {
                    $query->where('wago_stock_number', '>', 0)
                        ->orWhere('wago_lock_quantity', '>', 0)
                        ->orWhere('wago_priority_stock_number', '>', 0)
                        ->orWhere('wago_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_stock_number', '>', 0)
                        ->orWhere('wago_freight_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_priority_stock_number', '>', 0)
                        ->orWhere('wago_freight_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_unchecked_stock_number', '>', 0);
                } elseif ($wago_type == 3) {
                    $query->where('wago_stock_number', 0)
                        ->where('wago_lock_quantity', 0)
                        ->where('wago_priority_stock_number', 0)
                        ->where('wago_priority_lock_quantity', 0)
                        ->where('wago_freight_stock_number', 0)
                        ->where('wago_freight_lock_quantity', 0)
                        ->where('wago_freight_priority_stock_number', 0)
                        ->where('wago_freight_priority_lock_quantity', 0)
                        ->where('wago_unchecked_stock_number', 0);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('goo_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                }
            })
            ->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_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            }) //品牌系列id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            }) //品类id
            ->select('goo_name', 'goo_goods_encode', 'goo_bra_name', 'goo_cate_name', 'wago_stock_number', 'wago_max_warn', 'wago_min_warn', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number', 'wago_refuse_fine_stock', 'wago_refuse_fine_lock', 'wago_refuse_priority_stock', 'wago_refuse_priority_lock', 'wago_goo_id', 'wago_id', 'goo_type', 'goo_brse_id', 'wago_freight_stock_number', 'wago_freight_lock_quantity', 'wago_freight_priority_stock_number', 'wago_freight_priority_lock_quantity', 'wago_freight_unchecked_stock_number', 'goo_id', 'goo_class', 'wago_stock_amount', 'wago_lock_amount', 'wago_priority_stock_amount', 'wago_priority_lock_amount', 'wago_unchecked_stock_amount', 'goo_unit', 'goo_unta_id', 'wago_goo_price', 'wago_goo_amount', 'goo_level', 'goo_fid')
            ->orderBy('wago_id', 'desc')
            // ->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();                //返回数据
        //仓库库存总数量和总金额
        $data_info['onhand_data'] = DB::table('warehouse_onhand as o')
            ->leftJoin('warehouse as w', 'w.ware_id', '=', 'o.waon_ware_id')
            ->where('waon_ware_id', $request['ware_id'])
            ->where('waon_class', $request['waon_class'])
            ->select('waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount', 'ware_goo_amount', 'ware_all_stock', 'ware_lock_quantity')
            ->first();
        $data_info['onhand_data'] = json_decode(json_encode($data_info['onhand_data']),true);
        $data_info['onhand_data']['all_stock_amount'] = $data_info['onhand_data']['waon_stock_fine_amount'] + $data_info['onhand_data']['waon_lock_fine_amount'];//库存 + 锁定库存
        $data_info['onhand_data']['ware_goo_amount'] = number_format($data_info['onhand_data']['ware_goo_amount'],2) .' 元';

        $data_info['brse_data'] = []; //品牌系列数据
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        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();
            }
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            $goo_id = array_column($data_info['data'], 'goo_id');
            // 查询商品附属表信息
            $goaf_data = DB::table('goods_affiliate')
                ->where('goaf_shop_id', $user_info->adm_shop_id)
                ->whereIn('goaf_goo_id',  $goo_id)
                ->pluck('goaf_another_name', 'goaf_goo_id')
                ->toArray();
            // 查询系统商品属性表信息
            $gosa_data = DB::table('goods_system_affiliate')
                ->where('gosa_shop_id', $user_info->adm_shop_id)
                ->whereIn('gosa_goo_id',  $goo_id)
                ->pluck('gosa_another_name', 'gosa_goo_id')
                ->toArray();
            $buttonData = [];
            foreach ($data_info['data'] as $key => $value) {
                if ($value->goo_class == 2 && isset($gosa_data[$value->goo_id])) {
                    $data_info['data'][$key]->goaf_another_name = $gosa_data[$value->goo_id];
                } else {
                    $data_info['data'][$key]->goaf_another_name = '';
                }
                if (isset($goaf_data[$value->goo_id])) { // 商品别名
                    $data_info['data'][$key]->goaf_another_name = $goaf_data[$value->goo_id];
                } else {
                    $data_info['data'][$key]->goaf_another_name = '';
                }
                unset($data_info['data'][$key]->goo_id);
                unset($data_info['data'][$key]->goo_class);
                $data_info['data'][$key]->wago_goo_price = number_format($data_info['data'][$key]->wago_goo_price,2) . ' 元';
                $data_info['data'][$key]->wago_goo_amount = number_format($data_info['data'][$key]->wago_goo_amount,2) . ' 元';
                //按钮
                $buttonData = [];
                if ($value->goo_level == 1 || ($value->goo_level == 2 && $value->goo_fid)) {
                    $buttonData = ['unitConversion'];
                }
                $button = CommonService::getListButton($buttonData,$list_button);
                $data_info['data'][$key]->button_one = $button['button_one']??[];
                $data_info['data'][$key]->button_two = $button['button_two']??[];
                $data_info['data'][$key]->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 add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->addValidator($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;

        // 1. 判断仓库名称是否存在
        $find_ware = DB::table('warehouse')
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_superior_shop_id', $shop_id)
            ->where('ware_name', $request['ware_name'])
            ->value('ware_id');
        if ($find_ware) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '仓库名称已存在']);
        }
        if ($request['ware_type'] == 3) {
            $find_mobile_ware = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_superior_shop_id', $shop_id)
                ->where('ware_leader_id', $request['ware_leader_id'])
                ->where('ware_type', 3)
                ->select('ware_id')
                ->first();
            if ($find_mobile_ware) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前负责人已有移动仓！']);
            }
            // 判断账号是否是技师
            $find_adm = DB::table('admin_shop_role')
                ->where('adm_id', $request['ware_leader_id'])
                ->where('shop_id', $shop_id)
                ->select('admin_shop_role.adm_shop_leave as adm_leave')
                ->first();
            if (!in_array($find_adm->adm_leave, [3, 5])) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前负责人不是技师职位！']);
            }
        }
        // 2 新增一个仓库数据
        $ware_add_data = [
            'ware_cid' => $user_info->adm_cid,
            'ware_shop_id' => $user_info->adm_shop_id,
            'ware_superior_shop_id' => $shop_id,
            'ware_name' => $request['ware_name'],
            'ware_type' => $request['ware_type'],
            'ware_leader_id' => $request['ware_leader_id'],
            'ware_address' => $request['ware_address'] ? $request['ware_address'] : '',
            'ware_license' => $request['ware_license'] ? $request['ware_license'] : '',
        ];

        DB::beginTransaction();
        if ($request['ware_type'] == 1) { //固定仓
            // 2.1 查询是否已经添加了固定仓库
            $find_ware_type = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_superior_shop_id', $shop_id)
                ->where('ware_type', 1)
                ->value('ware_id');
            if ($find_ware_type) {
                // 2.2 已经添加固定仓库
                $ware_add_data['ware_default'] = $request['ware_default'];
                // 2.3 如果新增的仓库为默认仓库,将其他固定仓库都设为普通仓库
                if ($request['ware_default'] == 2) {
                    $update_data['ware_default'] = 1; //是否默认：1普通仓库2默认仓库
                    $update_data['ware_update_time'] = date('Y-m-d H:i:s');
                    $update_ware = DB::table('warehouse')
                        ->where('ware_cid', $user_info->adm_cid)
                        ->where('ware_superior_shop_id', $shop_id)
                        ->where('ware_type', 1)
                        ->update($update_data);
                } else {
                    $update_ware = true;
                }
            } else {
                // 2.4 第一次添加固定仓库
                $ware_add_data['ware_default'] = $request['ware_default'];
                $update_ware = true;
            }
            $ware_add_data['ware_freight_space'] = $request['ware_freight_space'] ? $request['ware_freight_space'] : '';
        } elseif ($request['ware_type'] == 3) { //移动仓
            $ware_add_data['ware_freight_space'] = $request['ware_freight_space'] ? $request['ware_freight_space'] : '';
            $update_ware = true;
        } else {
            //移动仓上级的固定仓id
            $update_ware = true;
        }

        // 新增仓库
        $ware_res =  DB::table('warehouse')->insertGetId($ware_add_data);
        // 判断admin_set表中是否有 该员工的设置
        $adm_set = DB::table('admin_set')
            ->where('adms_adm_id', $user_info->adm_id)
            ->where('adms_shop_id', $user_info->adm_shop_id)
            ->select('adms_id', 'adms_ware_id', 'adms_ware_ids', 'adms_myware_id')
            ->first();
        if ($adm_set) {
            $adms_data['adms_ware_id'] = $adm_set->adms_ware_id.','.$ware_res; //所绑定的仓库信息
            $adms_data['adms_ware_ids'] = $adm_set->adms_ware_ids.','.$ware_res; //仓库操作权限
            $adms_data['adms_myware_id'] = $adm_set->adms_myware_id.','.$ware_res; //我的仓库-仓库查看及相关操作权限
            $adms_data['adms_update_time'] = date('Y-m-d H:i:s'); //更新时间
            // 有该员工的设置编辑
            $adms_res = DB::table('admin_set')
                ->where('adms_id', $adm_set->adms_id)
                ->update($adms_data);
        } else {
            $adms_data['adms_ware_id'] = $ware_res; //所绑定的仓库信息
            $adms_data['adms_ware_ids'] = $ware_res; //仓库操作权限
            $adms_data['adms_myware_id'] = $ware_res; //我的仓库-仓库查看及相关操作权限
            $adms_data['adms_update_time'] = date('Y-m-d H:i:s'); //更新时间
            // 没有该员工的设置新增
            $adms_data['adms_adm_id'] = $user_info->adm_id; //员工id
            $adms_data['adms_shop_id'] = $user_info->adm_shop_id; //门店id
            $adms_res = DB::table('admin_set')->insert($adms_data);
        }
        // 新增仓库类别数据
        $waon_class = config('apisystem.WAREHOUSE_CLASS'); //  仓库类别：1货物仓2非货物仓3旧货仓4临时仓
        foreach ($waon_class as $key => $value) {
            $waon_data[$key]['waon_ware_id'] = $ware_res;
            $waon_data[$key]['waon_class'] = $value;
            $waon_data[$key]['waon_update_time'] = date('Y-m-d H:i:s');
        }
        $waon_res =  DB::table('warehouse_onhand')->insert($waon_data);

        if ($request['ware_type'] == 1) {
            // 新增默认仓位
            $data['wafr_shop_id'] = $user_info->adm_shop_id; //仓位隶属门店id
            $data['wafr_ware_id'] = $ware_res; //仓位隶属仓库id
            $data['wafr_parent_id'] = 0; //仓位隶属上级id
            $data['wafr_rank'] = 1; //仓位级别，第几级
            $data['wafr_name'] = '默认仓位'; //仓位名称
            $data['wafr_delete'] = 1; //是否删除1否2是
            $data['wafr_first_parent_id'] = 0; //仓位所属一级id
            $wafr_id = DB::table('warehouse_freight')->insertGetId($data);
        } else {
            $wafr_id = true;
        }

        if ($ware_res && $update_ware && $waon_res && $wafr_id) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '我的仓库', '新增', '新增仓库：' . $request['ware_name'] . '成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '新增仓库：成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '新增仓库：失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => '参数错误', '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;

        // 1. 判断仓库名称是否存在
        $find_ware = DB::table('warehouse')
            ->where('ware_id', '<>', $request['ware_id'])
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_superior_shop_id', $shop_id)
            ->where('ware_name', $request['ware_name'])
            ->select('ware_id')
            ->first();
        if ($find_ware) {
            return response()->json(['code' => 500, 'msg' => '仓库名称已存在', 'data' => '仓库名称已存在']);
        }

        // 查询仓库信息
        $find_ware = DB::table('warehouse')
            ->where('ware_id', $request['ware_id'])
            ->select('ware_id', 'ware_type')
            ->first();
        // 判断是否为移动仓 ware_type 类型：1固定仓2技师库3移动仓
        if ($find_ware->ware_type == 3) {
            // 移动仓类型，判断负责人是否已经有移动仓
            $find_mobile_ware = DB::table('warehouse')
                ->where('ware_id', '<>', $request['ware_id'])
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->where('ware_leader_id', $request['ware_leader_id'])
                ->where('ware_type', 3)
                ->select('ware_id')
                ->first();
            if ($find_mobile_ware) {
                return response()->json(['code' => 500, 'msg' => '当前负责人已有移动仓！', 'data' => '当前负责人已有移动仓！']);
            }
            // 判断账号是否是技师
            $find_adm = DB::table('admin_shop_role')
                ->where('adm_id', $request['ware_leader_id'])
                ->where('shop_id', $user_info->adm_shop_id)
                ->select('admin_shop_role.adm_shop_leave as adm_leave')
                ->first();
            if (!in_array($find_adm->adm_leave, [3, 5])) {
                return response()->json(['code' => 500, 'msg' => '当前负责人不是技师职位！', 'data' => '当前负责人不是技师职位！']);
            }
        }
        DB::beginTransaction();
        // 2 编辑仓库数据
        $ware_edit_data = [
            'ware_cid' => $user_info->adm_cid,
            'ware_shop_id' => $user_info->adm_shop_id,
            'ware_superior_shop_id' => $shop_id,
            'ware_name' => $request['ware_name'],
            'ware_address' => $request['ware_address'] ? $request['ware_address'] : '',
            'ware_leader_id' => $request['ware_leader_id'],
            'ware_license' => $request['ware_license'],
            'ware_update_time' => date('Y-m-d H:i:s'),
            'ware_freight_space' => $request['ware_freight_space'] ? $request['ware_freight_space'] : '',
        ];

        // 编辑仓库
        $ware_res =  DB::table('warehouse')
            ->where('ware_id', $request['ware_id'])
            ->update($ware_edit_data);
        if ($ware_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '仓库', '编辑', '编辑仓库：' . $request['ware_name'] . '成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '编辑仓库：成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => '编辑仓库：失败', 'data' => '编辑仓库：失败']);
        }
    }

    // 启用
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->startValidator($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_ware = DB::table('warehouse')
            ->whereIn('ware_id', $request['ware_id'])
            ->select('ware_name')
            ->get();
        foreach ($find_ware as $key => $value) {
            $ware_name[] = $value->ware_name;
        }

        // 启用
        $update_data['ware_state'] = 1; //状态1启用2停用
        $update_data['ware_update_time'] = date('Y-m-d H:i:s');
        $ware_res = DB::table('warehouse')
            ->whereIn('ware_id', $request['ware_id'])
            ->update($update_data);

        if ($ware_res) {
            Common::addLog($user_info, getRealIp($request), '仓库', '启用', '仓库：（' . implode(',', $ware_name) . '）启用成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '启用成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '启用失败']);
        }
    }

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

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

        // 查询信息
        $find_ware = DB::table('warehouse')
            ->whereIn('ware_id', $request['ware_id'])
            ->select('ware_name', 'ware_default')
            ->get();
        foreach ($find_ware as $key => $value) {
            $ware_name[] = $value->ware_name;
            if ($value->ware_default == 2) {
                return response()->json(['code' => 500, 'msg' => '默认仓库不允许停用', 'data' => '']);
            }
        }

        // 启用
        $update_data['ware_state'] = 2; //状态1启用2停用
        $update_data['ware_update_time'] = date('Y-m-d H:i:s');
        $ware_res = DB::table('warehouse')
            ->whereIn('ware_id', $request['ware_id'])
            ->update($update_data);

        if ($ware_res) {
            Common::addLog($user_info, getRealIp($request), '仓库', '停用', '仓库：（' . implode(',', $ware_name) . '）停用成功');
            return response()->json(['code' => 200, 'msg' => '停用成功', 'data' => '停用成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => '停用失败', 'data' => '停用失败']);
        }
    }

    // 撤仓
    public function repeal(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->startValidator($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_ware = DB::table('warehouse')
            ->whereIn('ware_id', $request['ware_id'])
            ->select('ware_name')
            ->get();
        foreach ($find_ware as $key => $value) {
            $ware_name[] = $value->ware_name;
        }

        // 删除
        $update_data['ware_delete'] = 2; //是否删除：1正常2已删除
        $update_data['ware_update_time'] = date('Y-m-d H:i:s');
        $ware_res = DB::table('warehouse')
            ->whereIn('ware_id', $request['ware_id'])
            ->update($update_data);

        if ($ware_res) {
            Common::addLog($user_info, getRealIp($request), '仓库', '删除', '仓库：（' . implode(',', $ware_name) . '）删除成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '删除成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '删除失败']);
        }
    }

    // 设为默认仓库
    public function setDefault(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->setDefaultValidator($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;

        // 查询信息
        $find_ware = DB::table('warehouse')
            ->where('ware_id', $request['ware_id'])
            ->select('ware_name', 'ware_type')
            ->first();
        if ($find_ware->ware_type != 1) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前仓库不是固定仓']);
        }

        DB::beginTransaction();
        // 1、将其他仓库设为普通仓库
        $update_data['ware_default'] = 1; //是否默认：1普通仓库2默认仓库
        $update_data['ware_update_time'] = date('Y-m-d H:i:s');
        $ware_res = DB::table('warehouse')
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_superior_shop_id', $shop_id)
            ->update($update_data);

        // 2、将选中仓库设为默认仓库
        $update_data['ware_default'] = 2; //是否默认：1普通仓库2默认仓库
        $update_data['ware_update_time'] = date('Y-m-d H:i:s');
        $ware_default_res = DB::table('warehouse')
            ->where('ware_id', $request['ware_id'])
            ->update($update_data);

        if ($ware_res && $ware_default_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '仓库', '设为默认仓库', $find_ware->ware_name . ' 设为默认仓库成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '设为默认仓库成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '设为默认仓库失败']);
        }
    }

    // 设置主仓
    public function setMaster(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->setDefaultValidator($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;

        // 查询是否设置主仓
        $master_ware_id = DB::table('warehouse')
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_superior_shop_id', $shop_id)
            ->where('ware_master', 2)
            ->value('ware_id');
        if ($master_ware_id) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前门店已经设置主仓']);
        }

        // 查询信息
        $find_ware = DB::table('warehouse')
            ->where('ware_id', $request['ware_id'])
            ->select('ware_name', 'ware_type')
            ->first();
        if ($find_ware->ware_type != 1) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '当前仓库不是固定仓']);
        }

        // 1、仓库设为主仓
        $update_data['ware_master'] = 2; //是否主仓：1普通仓库2主仓
        $update_data['ware_update_time'] = date('Y-m-d H:i:s');
        $ware_res = DB::table('warehouse')
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_superior_shop_id', $shop_id)
            ->where('ware_id', $request['ware_id'])
            ->update($update_data);

        if ($ware_res) {
            Common::addLog($user_info, getRealIp($request), '仓库', '设置主仓', $find_ware->ware_name . ' 设置主仓成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '设置主仓成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '设置主仓失败']);
        }
    }

    // 调货-提交【暂时用不到】
    public function allocating(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->allocatingValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }
        $goo_transfer = [];
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || !is_numeric($request['goo_num'][$key])) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数类型错误']);
            }
            $goo_transfer[$key]['goo_id'] = $value;
            $goo_transfer[$key]['goo_num'] = $request['goo_num'][$key];
            $goo_inventory[$key] = 1; //1.良品 2.优先(调货调的都是良品,用于出入库记录)
        }

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

        // 查询出出库仓库下 所有商品的数量 调货的入库商品数量不得大于出库商品数量
        $size = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['out_war_id'])
            ->get(['wago_goo_id', 'wago_stock_number']);
        foreach ($size as $key => $value) {
            foreach ($goo_transfer as $k => $v) {
                if ($v['goo_id'] == $value->wago_goo_id) {
                    if ($v['goo_num'] > $value->wago_stock_number) {
                        return response()->json(['code' => 500, 'msg' => 'error', 'data' => '入库商品数量不得大于出库商品数量']);
                    }
                }
            }
        }

        // 计算出总调货量/所有要调货的商品id
        $tuned_cargo = 0;
        foreach ($goo_transfer as $key => $value) {
            //所有要调货的商品数量
            $tuned_cargo = $tuned_cargo + $value['goo_num'];
            //所有要调货的商品id
            $spread_goo_id[$key] = $value['goo_id'];
        }

        // 验证不得出库 仓库中没有的商品
        $out_goo_id = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['out_war_id'])
            ->get(['wago_goo_id'])->toArray();
        $out_goo_id = array_column($out_goo_id, 'wago_goo_id');
        if (array_diff($spread_goo_id, $out_goo_id)) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '不得出库仓库中没有的商品']);
        }

        // 查询入库仓库下 所有的商品id(用于判断是否新增仓库内商品)
        $is_update_num = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['in_war_id'])
            ->get(['wago_goo_id'])->toArray();
        $is_update_num = array_column($is_update_num, 'wago_goo_id');


        DB::beginTransaction();
        // 1.更改左仓库表总库存量(总库存量-调货数量)
        $out_all_stock = DB::table('warehouse')
            ->where('ware_id', $request['out_war_id'])
            ->decrement('ware_all_stock', $tuned_cargo);
        // 2.更改右仓库表总库存量(总库存量+调货数量)
        $in_all_stock = DB::table('warehouse')
            ->where('ware_id', $request['in_war_id'])
            ->increment('ware_all_stock', $tuned_cargo);

        // 3.更改仓库商品表 出库仓库的商品库存数量(减)/入库仓库的商品库存数量(加)
        $sql = 'UPDATE `faster_warehouse_goods` SET ';
        $out_stock_num = '';

        $centre_time = ''; //调货时间
        $center_goo_id = ''; //调货的商品
        foreach ($goo_transfer as $key => $value) {
            // 更改出库商品库存数量(-)
            $out_stock_num = $out_stock_num . ' WHEN ' . $value['goo_id'];
            $out_stock_num = $out_stock_num . ' THEN wago_stock_number - ' . $value['goo_num'];
            // 更改时间(左右皆可用)
            $centre_time = $centre_time . ' WHEN ' . $value['goo_id'];
            $centre_time = $centre_time . ' THEN "' . date('Y-m-d H:i:s') . '"';
            //要更改的商品id
            $center_goo_id = $center_goo_id . $value['goo_id'] . ',';
        }
        $sql = $sql . ' `wago_stock_number`=  CASE `wago_goo_id` ' . $out_stock_num . ' END,';
        $sql = $sql . ' `wago_update_time`=  CASE `wago_goo_id` ' . $centre_time . ' END';

        // 出库
        $out_sql = $sql . ' WHERE `wago_ware_id` = ' . $request['out_war_id'] . ' AND `wago_goo_id` IN (' . trim($center_goo_id, ',') . ')';
        $out_stock_sql = DB::update($out_sql);

        // 入库
        $is_update = array_intersect($spread_goo_id, $is_update_num); // 对比商品id 查看是否需要修改
        if ($is_update) {
            //出库:-商品数量 入库+商品数量
            $sql = str_replace("-", "+", $sql);
            // 出库仓库id和入库仓库id不一致
            $in_sql = $sql . ' WHERE `wago_ware_id` = ' . $request['in_war_id'] . ' AND `wago_goo_id` IN (' . trim($center_goo_id, ',') . ')';
            $in_stock_sql = DB::update($in_sql);
        } else {
            $in_stock_sql = true;
        }

        // 对比商品id 查看是否需要新增
        $is_add = array_diff($spread_goo_id, $is_update_num);
        if ($is_add) {
            // 将调货的商品数量追加进去
            foreach ($goo_transfer as $key => $value) {
                foreach ($is_add as $k => $v) {
                    if ($v == $value['goo_id']) {
                        $add_goo[$k]['goo_id'] = $value['goo_id'];
                        $add_goo[$k]['goo_num'] = $value['goo_num'];
                    }
                }
            }

            foreach ($add_goo as $key => $value) {
                $ware_add_data[$key]['wago_ware_id'] = $request['in_war_id'];
                $ware_add_data[$key]['wago_goo_id'] = $value['goo_id'];
                $ware_add_data[$key]['wago_stock_number'] = $value['goo_num'];
            }
            $ware_add_res = DB::table('warehouse_goods')->insert($ware_add_data);
        } else {
            $ware_add_res = true;
        }

        // 4.生成出库记录
        $out_war = DB::table('warehouse')
            ->where('ware_id', $request['out_war_id'])
            ->select('ware_all_stock', 'ware_lock_quantity', 'ware_priority_all_stock', 'ware_priority_lock_quantity', 'ware_unchecked_all_stock')
            ->first();

        $oure_res = OutinRecord::add(
            $user_info, //用户信息
            '', //原始单号
            0, //入库仓库id
            $request['out_war_id'], //出库仓库id
            $tuned_cargo, //出库的商品总量
            3, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库
            $request['goo_id'], //数组，商品id
            $request['goo_num'], //数组，商品数量
            $goo_inventory, //数组，出库类型1良品2优先
            2, //操作类型：1锁定库存2出库3入库4调货5发货
            $out_war->ware_all_stock, //良品总库存
            $out_war->ware_lock_quantity, //良品锁定数量
            $out_war->ware_priority_all_stock, //优先总库存
            $out_war->ware_priority_lock_quantity, //优先锁定数量
            $out_war->ware_unchecked_all_stock, //待检测总库存
            1
        );

        // 5.生成入库记录
        $in_war = DB::table('warehouse')
            ->where('ware_id', $request['in_war_id'])
            ->select('ware_all_stock', 'ware_lock_quantity', 'ware_priority_all_stock', 'ware_priority_lock_quantity', 'ware_unchecked_all_stock')
            ->first();
        $oure_data = OutinRecord::add(
            $user_info, //用户信息
            '', //原始单号
            $request['in_war_id'], //入库仓库id
            0, //出库仓库id
            $tuned_cargo, //入库的商品总量
            3, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库
            $request['goo_id'], //数组，商品id
            $request['goo_num'], //数组，商品数量
            $goo_inventory, //数组，出库类型1良品2优先
            3, //操作类型：1锁定库存2出库3入库4调货5发货
            $in_war->ware_all_stock, //良品总库存
            $in_war->ware_lock_quantity, //良品锁定数量
            $in_war->ware_priority_all_stock, //优先总库存
            $in_war->ware_priority_lock_quantity, //优先锁定数量
            $in_war->ware_unchecked_all_stock, //待检测总库存
            2
        );

        if ($out_all_stock && $in_all_stock && $out_stock_sql && $in_stock_sql && $ware_add_res && $oure_res && $oure_data) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '我的仓库', '调货', '调货数量' . $tuned_cargo);
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '调货成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '调货失败']);
        }
    }

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

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 查询出仓库商品的库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['ware_id'])
            ->where('wago_id', $request['wago_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', 'wago_unchecked_stock_amount')
            ->first();
        $ware_type = DB::table('warehouse')
            ->where('ware_shop_id', $user_info->adm_shop_id)
            ->where('ware_id', $request['ware_id'])
            ->value('ware_type');
        // 4.4 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
        $sql = 'UPDATE `faster_warehouse_goods` SET ';
        $stock_number_sql = ''; //良品库存数量（仓库+仓位）
        $wago_stock_amount_sql = ''; //良品库存数量 （仓库）
        $priority_stock_number_sql = ''; //优先库存数量仓库+仓位）
        $wago_priority_stock_amount_sql = ''; //优先库存数量（仓库）
        $unchecked_stock_number_sql = ''; //待检测库存数量仓库+仓位）
        $wago_unchecked_stock_amount_sql = ''; //待检测库存数量（仓库）
        $update_time_sql = ''; //时间
        $ids = '';
        // 1良品转优先2优先转良品3待检测转优先4待检测转良品
        switch ($request['type']) {
            case '1': //1良品转优先
                $stock_number = $warehouse_goods->wago_stock_number - $request['goo_count']; //良品库存数量(仓库+仓位)
                if ($ware_type == 1) { //固定仓
                    $wago_stock_amount = $warehouse_goods->wago_stock_amount - $request['goo_count']; //良品库存数量(仓库)
                } else {
                    $wago_stock_amount = 0;
                }
                if ($stock_number < 0 || $wago_stock_amount < 0) {
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '仓库内商品良品库存数量不足']);
                }
                $priority_stock_number = $warehouse_goods->wago_priority_stock_number + $request['goo_count']; //优先库存数量（仓库+仓位）

                if ($ware_type == 1) { //固定仓
                    $wago_priority_stock_amount = $warehouse_goods->wago_priority_stock_amount + $request['goo_count']; //优先库存数量（仓库）
                } else {
                    $wago_priority_stock_amount = $warehouse_goods->wago_priority_stock_amount; //优先库存数量（仓库）
                }
                $unchecked_stock_number = $warehouse_goods->wago_unchecked_stock_number; //库存数量
                $wago_unchecked_stock_amount = $warehouse_goods->wago_unchecked_stock_amount; //仓库待检测数量
                // 仓库总库存
                $ware_one_sql = '`waon_stock_fine_amount`= `waon_stock_fine_amount` - ' . $request['goo_count'] . ','; //良品总库存
                $ware_two_sql = '`waon_stock_priority_amount`= `waon_stock_priority_amount` + ' . $request['goo_count']; //优先总库存
                $ware_three_sql = ''; //待检测总库存

                $hint_log = '：良品转优先，转换数量为' . $request['goo_count'];
                break;
            case '2': //优先转良品
                $priority_stock_number = $warehouse_goods->wago_priority_stock_number - $request['goo_count']; //优先库存数量（仓库+仓位）
                if ($ware_type == 1) { //固定仓
                    $wago_priority_stock_amount = $warehouse_goods->wago_priority_stock_amount - $request['goo_count']; //优先库存数量（仓库）
                } else {
                    $wago_priority_stock_amount = 0;
                }
                if ($priority_stock_number < 0 || $wago_priority_stock_amount < 0) {
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '仓库内商品优先库存数量不足']);
                }
                $stock_number = $warehouse_goods->wago_stock_number + $request['goo_count']; //良品库存数量（仓库+仓位）
                if ($ware_type == 1) { //固定仓
                    $wago_stock_amount = $warehouse_goods->wago_stock_amount + $request['goo_count']; //良品库存数量（仓库）
                } else {
                    $wago_stock_amount = $warehouse_goods->wago_stock_amount;
                }
                $unchecked_stock_number = $warehouse_goods->wago_unchecked_stock_number; //待检测库存数量
                $wago_unchecked_stock_amount = $warehouse_goods->wago_unchecked_stock_amount;
                // 仓库总库存
                $ware_one_sql = '`waon_stock_priority_amount`= `waon_stock_priority_amount` - ' . $request['goo_count'] . ','; //优先总库存
                $ware_two_sql = '`waon_stock_fine_amount`= `waon_stock_fine_amount` + ' . $request['goo_count']; //良品总库存
                $ware_three_sql = ''; //待检测总库存

                $hint_log = '：优先转良品，转换数量为' . $request['goo_count'];
                break;
            case '3': //待检测转优先
                $unchecked_stock_number = $warehouse_goods->wago_unchecked_stock_number - $request['goo_count']; //待检测库存数量（仓库+仓位）
                if ($ware_type == 1) { //固定仓
                    $wago_unchecked_stock_amount = $warehouse_goods->wago_unchecked_stock_amount - $request['goo_count']; //待检测库存数量（仓库）
                } else {
                    $wago_unchecked_stock_amount = 0;
                }
                if ($unchecked_stock_number < 0 || $wago_unchecked_stock_amount < 0) {
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '仓库内商品待检测库存数量不足']);
                }
                $priority_stock_number = $warehouse_goods->wago_priority_stock_number + $request['goo_count']; //优先库存数量(仓库+仓位)
                if ($ware_type == 1) { //固定仓
                    $wago_priority_stock_amount = $warehouse_goods->wago_priority_stock_amount + $request['goo_count']; //优先库存数量（仓库）
                } else {
                    $wago_priority_stock_amount = $warehouse_goods->wago_priority_stock_amount;
                }
                $stock_number = $warehouse_goods->wago_stock_number; //良品库存数量
                $wago_unchecked_stock_amount = $warehouse_goods->wago_unchecked_stock_amount;

                // 仓库总库存
                $ware_one_sql = '`waon_stock_unchecked_amount`= `waon_stock_unchecked_amount` - ' . $request['goo_count'] . ','; //待检测总库存
                $ware_two_sql = '`waon_stock_priority_amount`= `waon_stock_priority_amount` + ' . $request['goo_count']; //优先总库存
                $ware_three_sql = ''; //良品总库存

                $hint_log = '：待检测转优先，转换数量为' . $request['goo_count'];
                break;
            case '4': //待检测转良品
                $unchecked_stock_number = $warehouse_goods->wago_unchecked_stock_number - $request['goo_count']; //待检测库存数量（仓库+仓位）
                if ($ware_type == 1) { //固定仓
                    $wago_unchecked_stock_amount = $warehouse_goods->wago_unchecked_stock_amount - $request['goo_count']; //待检测库存数量（仓库）
                } else {
                    $wago_unchecked_stock_amount = 0;
                }
                if ($unchecked_stock_number < 0 || $wago_unchecked_stock_amount < 0) {
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => '仓库内商品待检测库存数量不足']);
                }
                $stock_number = $warehouse_goods->wago_stock_number + $request['goo_count']; //良品库存数量（仓库+仓位）
                if ($ware_type == 1) {
                    $wago_stock_amount = $warehouse_goods->wago_stock_amount + $request['goo_count']; //良品库存数量（仓库）
                } else {
                    $wago_stock_amount = $warehouse_goods->wago_stock_amount;
                }
                $priority_stock_number = $warehouse_goods->wago_priority_stock_number; //优先库存数量

                // 仓库总库存
                $ware_one_sql = '`waon_stock_unchecked_amount`= `waon_stock_unchecked_amount` - ' . $request['goo_count'] . ','; //待检测总库存
                $ware_two_sql = '`waon_stock_fine_amount`= `waon_stock_fine_amount` + ' . $request['goo_count']; //良品总库存
                $ware_three_sql = ''; //优先总库存

                $hint_log = '：待检测转良品，转换数量为' . $request['goo_count'];
                break;
            default:
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误']);
                break;
        }

        DB::beginTransaction();
        // 更改良品库存数量（仓库+仓位）
        $stock_number_sql = $stock_number_sql . ' WHEN ' . $warehouse_goods->wago_id;
        $stock_number_sql = $stock_number_sql . ' THEN ' . $stock_number;
        // 更改良品库存数量（仓库）
        $wago_stock_amount_sql = $wago_stock_amount_sql . ' WHEN ' . $warehouse_goods->wago_id;
        $wago_stock_amount_sql = $wago_stock_amount_sql . ' THEN ' . $wago_stock_amount;

        // 更改优先库存数量（仓库+仓位）
        $priority_stock_number_sql = $priority_stock_number_sql . ' WHEN ' . $warehouse_goods->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 ' . $warehouse_goods->wago_id;
        $wago_priority_stock_amount_sql = $wago_priority_stock_amount_sql . ' THEN ' . $wago_priority_stock_amount;

        // 更改待检测库存数量（仓库+仓位）
        $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' WHEN ' . $warehouse_goods->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 ' . $warehouse_goods->wago_id;
        $wago_unchecked_stock_amount_sql = $wago_unchecked_stock_amount_sql . ' THEN ' . $wago_unchecked_stock_amount;

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

        $ids = $ids . $warehouse_goods->wago_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);

        $warehouse_sql = 'UPDATE `faster_warehouse_onhand` SET  `waon_update_time` = "' . date('Y-m-d H:i:s') . '",' .
            $ware_one_sql . $ware_two_sql . $ware_three_sql .
            ' WHERE  `waon_ware_id` =' . $request['ware_id'] . ' and `waon_class` =' . $request['waon_class'];
        // 修改仓库表
        $update_warehouse = DB::update($warehouse_sql);
        if ($ware_edit_res && $update_warehouse) {
            DB::commit();
            $goo_name = DB::table('goods')->where('goo_id', $warehouse_goods->wago_goo_id)->value('goo_name');
            $ware_name = DB::table('warehouse')->where('ware_id', $request['ware_id'])->value('ware_name');
            Common::addLog($user_info, getRealIp($request), '我的仓库-查看', '转换库存', $ware_name . '->' . $goo_name . $hint_log . '，转换成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '转换成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '转换失败']);
        }
    }

    // 搜索员工
    public function searchEmployee(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_id = $user_info->adm_shop_id;

        if ($request['ware_type'] == 2) {
            // 移动仓查询有技师职位的账号
            $adm_leave = [3, 5];
        } else {
            $adm_leave = [1, 2, 3, 4, 5];
        }

        $list_data = DB::table('admin as a')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
            ->leftJoin('role as b', 'b.rol_id', '=', 'a.adm_role')
            ->where('asr.shop_cid', $user_info->adm_cid)
            ->where('asr.shop_id', $shop_id)
            ->where('asr.adm_state', 1)
            ->where('asr.create_source', 1)
            ->whereIn('asr.adm_shop_leave', $adm_leave)
            ->select('a.adm_id', 'a.adm_name', 'a.adm_phone', 'rol_name')
            ->orderBy('adm_id', 'desc')
            ->get();
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $list_data]);
    }

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

        $select_field = "ware_id, ware_name, ware_type";

        $public_search = new PublicSearch;
        $list_data = $public_search->searchWarehouse($user_info, $request->all(), $select_field);
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $list_data['data']]);
    }

    // 调货--搜索商品【暂时用不到】
    public function searchGoods(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $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']);
        $search_data = $request->all();

        $list_data = DB::table('warehouse_goods as w')
            ->leftJoin('goods as g', 'w.wago_goo_id', '=', 'g.goo_id')
            ->where('wago_ware_id', $search_data['ware_id'])
            ->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('g.goo_bra_id', $search_data['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('g.goo_cate_id', $search_data['goo_cate_id']);
                }
            })
            ->select('g.goo_id', 'g.goo_name', 'g.goo_goods_encode', 'w.wago_stock_number')
            ->paginate($this->show_count);
        // ->get(['g.goo_id', 'g.goo_name', 'g.goo_goods_encode', 'w.wago_stock_number']);
        $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();                //返回数据
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info]);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '暂无数据']);
        }
    }

    // 调货--从左向右调货获取库存量【暂时用不到】
    public function stock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->stockValidator($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();

        $stock_number = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['ware_id'])
            ->where('wago_goo_id', $request['goo_id'])
            ->value('wago_stock_number');
        if (!$stock_number) {
            $stock_number = 0;
        }
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $stock_number]);
    }

    // 调货--获取右侧商品的库存数量【暂时用不到】
    public function goodsStock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $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']);
        $search_data = $request->all();

        $stock_number = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['ware_id'])
            ->whereIn('wago_goo_id', $request['goo_id'])
            ->select('wago_goo_id', 'wago_stock_number')
            ->get();
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $stock_number]);
    }

    // 获取固定仓信息
    public function fixedWarehouse(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $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)
            ->get(['ware_id as ware_superior_id', 'ware_name as ware_superior_name']);
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $list_data]);
    }

    // 设置仓库预警类型
    public function setWarning(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->setWarningValidator($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_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        if ($request['type'] == 1) {
            $data = DB::table('warehouse_onhand as wo')
                ->join('warehouse_class as wc', 'wc.wacl_class_numerical', '=', 'wo.waon_class')
                ->where('waon_ware_id', $request['ware_id'])
                ->where('wacl_shop_id', $user_info->adm_shop_id)
                ->whereNotIn('waon_class', [2, 3, 4])
                ->select('wacl_class_name', 'waon_id', 'waon_warn_state', 'waon_class')
                ->get();
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        }

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

        foreach ($request['waon_id'] as $key => $value) {
            if (!is_numeric($value) || !is_numeric($request['waon_warn_state'][$key])) {
                return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误']);
            }
        }
        DB::beginTransaction();
        $ware_name = DB::table('warehouse')
            ->where('ware_id', $request['ware_id'])
            ->value('ware_name');
        //设置仓库类别预警状态
        $sql = 'UPDATE `faster_warehouse_onhand` SET ';
        $update_time = ''; //修改时间
        $warn_state = ''; //修改状态
        $ids = '';
        foreach ($request['waon_id'] as $key => $value) {
            // 更改出库商品库存数量(-)
            $warn_state = $warn_state . ' WHEN ' . $value;
            $warn_state = $warn_state . ' THEN ' . $request['waon_warn_state'][$key];
            $update_time = $update_time . ' WHEN ' . $value;
            $update_time = $update_time . ' THEN "' . date('Y-m-d H:i:s') . '"';
            //id
            $ids = $ids . $value . ',';
        }
        $sql = $sql . ' `waon_warn_state`=  CASE `waon_id` ' . $warn_state . ' END,';
        $sql = $sql . ' `waon_update_time`=  CASE `waon_id` ' . $update_time . ' END';
        // 修改
        $state_sql = $sql . ' WHERE `waon_ware_id` = ' . $request['ware_id'] . ' AND `waon_id` IN (' . trim($ids, ',') . ')';
        $update_sql = DB::update($state_sql);

        if ($update_sql) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '我的仓库', '设置预警', $ware_name . '，设置预警状态');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '设置成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '设置失败']);
        }
    }

    // 商品预警设置
    public function goodsWarning(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->goodsWarningValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        $sql = 'UPDATE `faster_warehouse_goods` SET ';
        $wago_min_warn_sql = '';
        $wago_min_warn_sqls = '';
        $time_sql = '';
        $ids = '';

        foreach ($request['wago_id'] as $key => $value) {
            // 查询原来的预警值
            $min_warn = DB::table('warehouse_goods')
                ->where('wago_id', $value)
                ->value('wago_min_warn');
            $wago_min_warn_sqls = $wago_min_warn_sqls . ' WHEN ' . $value . ' THEN `wago_min_warn` - ' . $min_warn;
            $wago_min_warn_sql = $wago_min_warn_sql . ' WHEN ' . $value . ' THEN `wago_min_warn` + ' . $request['wago_min_warn'][$key];

            $time_sql = $time_sql . ' WHEN ' . $value . ' THEN "' . date('Y-m-d H:i:s') . '"'; // 更改时间
            $ids = $ids . $value . ',';
        }

        // 2.1 固定仓商品表减锁定库存
        $sql = $sql . ' `wago_min_warn`=  CASE `wago_id` ' . $wago_min_warn_sqls . ' END,'; //修改良品库存数量
        $sql = $sql . ' `wago_min_warn`=  CASE `wago_id` ' . $wago_min_warn_sql . ' END,'; //修改良品库存数量
        $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $time_sql . ' END'; //修改时间
        $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ') and wago_ware_id = ' . $request['ware_id'];
        $wago_res = DB::update($sql);
        if ($wago_res) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            $find_goo_name = DB::table('goods')
                ->whereIn('goo_id', $request['wago_goo_id'])
                ->select('goo_name')
                ->get();
            foreach ($find_goo_name as $key => $value) {
                $goo_name[] = $value->goo_name;
            }
            Common::addLog($user_info, getRealIp($request), '我的仓库-查看', '设置预警', '商品：（' . implode(',', $goo_name) . '）设置成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '设置成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '设置失败']);
        }
    }

    // 临时仓转旧货仓
    public function adjacentTransition(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->adjacentTransitionValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 查询旧货仓商品
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['ware_id'])
            ->where('wago_class', 3)
            ->whereIn('wago_goo_id', $request['goo_id'])
            ->get()->toArray();
        // 查询临时仓商品
        $temporary_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['ware_id'])
            ->where('wago_class', 4)
            ->whereIn('wago_goo_id', $request['goo_id'])
            ->get()->toArray();
        $wago_goo_id_data = array_column($temporary_goods, null, 'wago_goo_id');
        // 查询旧货仓的仓库类别id
        $old_waon_id = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $request['ware_id'])
            ->where('waon_class', 3)
            ->value('waon_id');
        // 查询临时仓的仓库类别id
        $temporary_waon_id = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $request['ware_id'])
            ->where('waon_class', 4)
            ->value('waon_id');

        DB::beginTransaction();

        if (!empty($warehouse_goods)) {
            $sql = 'UPDATE `faster_warehouse_goods` SET ';
            $temp_sql = 'UPDATE `faster_warehouse_goods` SET ';
            $stock_fine_sql = '';
            $stock_priority_sql = '';
            $time_sql = '';
            $ids = '';

            $temp_stock_fine_sql = '';
            $temp_stock_priority_sql = '';
            $temp_time_sql = '';
            $temp_ids = '';

            $waon_class_fine_quantity = 0; //仓库类别对应良品库存总数量
            $waon_class_priority_quantity = 0; //仓库类别对应优先库存总数量
            foreach ($warehouse_goods as $key => $value) {
                // 判断仓库内是否有商品id,有商品id就更改库存数量
                // 判断移动仓库内是否有入库商品id，有商品id就更改库存数量
                // 良品库存
                if ($request['goo_inventory'][$key] == '1') {
                    // 旧货仓昆虫数量增加
                    $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $value->wago_id . ' THEN `wago_stock_number` + ' . $request['goo_num'][$key];
                    $stock_priority_sql = $stock_priority_sql . ' WHEN ' . $value->wago_id . ' THEN `wago_priority_stock_number` - 0';

                    // 临时仓库存数量减少
                    $temp_stock_fine_sql = $temp_stock_fine_sql . ' WHEN ' . $wago_goo_id_data[$value->wago_goo_id]->wago_id . ' THEN `wago_stock_number` - ' . $request['goo_num'][$key];
                    $temp_stock_priority_sql = $temp_stock_priority_sql . ' WHEN ' . $wago_goo_id_data[$value->wago_goo_id]->wago_id . ' THEN `wago_priority_stock_number` + 0';

                    $waon_class_fine_quantity += $request['goo_num'][$key]; //仓库类别对应良品库存总数量
                } else {
                    // 优先
                    // 旧货仓库存数量增加
                    $stock_priority_sql = $stock_priority_sql . ' WHEN ' . $value->wago_id . ' THEN `wago_priority_stock_number` + ' . $value->wago_priority_stock_number;
                    // 更改库存数量
                    $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $value->wago_id . ' THEN `wago_stock_number` - 0';
                    $waon_class_priority_quantity += $value->wago_priority_stock_number; //仓库类别对应优先库存总数量

                    // 临时仓库存数量减少
                    $temp_stock_priority_sql = $temp_stock_priority_sql . ' WHEN ' . $wago_goo_id_data[$value->wago_goo_id]->wago_id . ' THEN `wago_priority_stock_number` - ' . $value->wago_priority_stock_number;
                    // 更改库存数量
                    $temp_stock_fine_sql = $temp_stock_fine_sql . ' WHEN ' . $wago_goo_id_data[$value->wago_goo_id]->wago_id . ' THEN `wago_stock_number` + 0';

                    $waon_class_priority_quantity += $value->wago_priority_stock_number; //仓库类别对应优先库存总数量
                }

                // 进销存算法数组
                $purchase_goo_actual_count[$request['goo_id'][$key]] = $request['goo_num'][$key]; //进销存商品数量
                $purchase_goo_actual_price[$request['goo_id'][$key]] = 0; //进销存金额

                $time_sql = $time_sql . ' WHEN ' . $value->wago_id . ' THEN "' . date('Y-m-d H:i:s') . '"'; // 更改时间
                $ids = $ids . $value->wago_id . ',';

                $temp_time_sql = $temp_time_sql . ' WHEN ' . $wago_goo_id_data[$value->wago_goo_id]->wago_id . ' THEN "' . date('Y-m-d H:i:s') . '"'; // 更改时间
                $temp_ids = $temp_ids . $wago_goo_id_data[$value->wago_goo_id]->wago_id . ',';
            }

            // 2.1 固定仓商品表减锁定库存
            $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $stock_fine_sql . ' END,'; //修改良品库存数量
            $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $stock_priority_sql . ' END,'; //修改优先库存数量
            $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $time_sql . ' END'; //修改时间
            $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';

            $temp_sql = $temp_sql . ' `wago_stock_number`=  CASE `wago_id` ' . $temp_stock_fine_sql . ' END,'; //修改良品库存数量
            $temp_sql = $temp_sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $temp_stock_priority_sql . ' END,'; //修改优先库存数量
            $temp_sql = $temp_sql . ' `wago_update_time`=  CASE `wago_id` ' . $temp_time_sql . ' END'; //修改时间
            $temp_sql = $temp_sql . ' WHERE `wago_id` IN (' . trim($temp_ids, ',') . ')';
            $wago_edit_res = DB::update($sql);
            $temp_wago_edit_res = DB::update($temp_sql);

            // 修改仓库类别表库存数据
            $sql = 'UPDATE `faster_warehouse_onhand` SET ';
            $temp_sql = 'UPDATE `faster_warehouse_onhand` SET ';
            $stock_fine_sql = '';
            $all_amount_sql = '';
            $time_sql = '';
            $ids = '';

            $temp_stock_fine_sql = '';
            $temp_all_amount_sql = '';
            $temp_time_sql = '';
            $temp_ids = '';

            // 良品库存总数量更改
            if ($waon_class_fine_quantity) {
                // 旧货仓库存增加
                $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $old_waon_id . ' THEN `waon_stock_fine_amount` + ' . $waon_class_fine_quantity;
                $all_amount_sql = $all_amount_sql . ' WHEN ' . $old_waon_id . ' THEN `waon_all_amount` + ' . $waon_class_fine_quantity;
                $time_sql = $time_sql . ' WHEN ' . $old_waon_id . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $old_waon_id . ',';
                $sql = $sql . ' `waon_stock_fine_amount`=  CASE `waon_id` ' . $stock_fine_sql . ' END,';
                $sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $all_amount_sql . ' END,';

                // 临时仓库存减少
                $temp_stock_fine_sql = $temp_stock_fine_sql . ' WHEN ' . $temporary_waon_id . ' THEN `waon_stock_fine_amount` - ' . $waon_class_fine_quantity;
                $temp_all_amount_sql = $temp_all_amount_sql . ' WHEN ' . $temporary_waon_id . ' THEN `waon_all_amount` - ' . $waon_class_fine_quantity;
                $temp_time_sql = $temp_time_sql . ' WHEN ' . $temporary_waon_id . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $temp_ids = $temp_ids . $temporary_waon_id . ',';
                $temp_sql = $temp_sql . ' `waon_stock_fine_amount`=  CASE `waon_id` ' . $temp_stock_fine_sql . ' END,';
                $temp_sql = $temp_sql . ' `waon_all_amount`=  CASE `waon_id` ' . $temp_all_amount_sql . ' END,';
            }
            // 优先库存总数量更改
            if ($waon_class_priority_quantity) {
                // 旧货仓库存增加
                $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $old_waon_id . ' THEN `waon_stock_priority_amount` + ' . $waon_class_priority_quantity;
                $all_amount_sql = $all_amount_sql . ' WHEN ' . $old_waon_id . ' THEN `waon_all_amount` + ' . $waon_class_priority_quantity;
                $time_sql = $time_sql . ' WHEN ' . $old_waon_id . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $old_waon_id . ',';
                $sql = $sql . ' `waon_stock_priority_amount`=  CASE `waon_id` ' . $stock_fine_sql . ' END,';
                $sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $all_amount_sql . ' END,';

                // 临时仓库存减少
                $temp_stock_fine_sql = $temp_stock_fine_sql . ' WHEN ' . $temporary_waon_id . ' THEN `waon_stock_priority_amount` + ' . $waon_class_priority_quantity;
                $temp_all_amount_sql = $temp_all_amount_sql . ' WHEN ' . $temporary_waon_id . ' THEN `waon_all_amount` - ' . $waon_class_priority_quantity;
                $temp_time_sql = $temp_time_sql . ' WHEN ' . $temporary_waon_id . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $temp_ids = $temp_ids . $temporary_waon_id . ',';
                $temp_sql = $sql . ' `waon_stock_priority_amount`=  CASE `waon_id` ' . $temp_stock_fine_sql . ' END,';
                $temp_sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $temp_all_amount_sql . ' END,';
            }
            $sql = $sql . ' `waon_update_time`=  CASE `waon_id` ' . $time_sql . ' END';
            $sql = $sql . ' WHERE `waon_id` = (' . trim($ids, ',') . ')';

            $temp_sql = $temp_sql . ' `waon_update_time`=  CASE `waon_id` ' . $temp_time_sql . ' END';
            $temp_sql = $temp_sql . ' WHERE `waon_id` = (' . trim($temp_ids, ',') . ')';
            $waon_priority_res = DB::update($sql);
            $temp_waon_priority_res = DB::update($temp_sql);
            $wago_id = true;
        } else {
            $temp_sql = 'UPDATE `faster_warehouse_goods` SET ';
            $temp_stock_fine_sql = '';
            $temp_stock_priority_sql = '';
            $temp_time_sql = '';
            $temp_ids = '';
            // 旧货仓不存在的商品,新增商品数据
            $waon_class_fine_quantity = 0; //仓库类别对应良品库存总数量
            $waon_class_priority_quantity = 0; //仓库类别对应优先库存总数量
            foreach ($request['goo_id'] as $key => $value) {
                $add_data[$key]['wago_ware_id'] = $request['ware_id'];
                $add_data[$key]['wago_class'] = 3;
                $add_data[$key]['wago_goo_id'] = $value;

                // 良品库存
                if ($request['goo_inventory'][$key] == '1') {
                    $add_data[$key]['wago_stock_number'] = $request['goo_num'][$key];

                    // 临时仓库存数量减少
                    $temp_stock_fine_sql = $temp_stock_fine_sql . ' WHEN ' . $wago_goo_id_data[$value]->wago_id . ' THEN `wago_stock_number` - ' . $request['goo_num'][$key];
                    $temp_stock_priority_sql = $temp_stock_priority_sql . ' WHEN ' . $wago_goo_id_data[$value]->wago_id . ' THEN `wago_priority_stock_number` + 0';

                    $waon_class_fine_quantity += $request['goo_num'][$key]; //仓库类别对应良品库存总数量
                } else {
                    // 优先
                    $add_data[$key]['wago_priority_stock_number'] = $request['goo_num'][$key];

                    // 临时仓库存数量减少
                    $temp_stock_priority_sql = $temp_stock_priority_sql . ' WHEN ' . $wago_goo_id_data[$value]->wago_id . ' THEN `wago_priority_stock_number` - ' . $value->wago_priority_stock_number;
                    // 更改库存数量
                    $temp_stock_fine_sql = $temp_stock_fine_sql . ' WHEN ' . $wago_goo_id_data[$value]->wago_id . ' THEN `wago_stock_number` + 0';

                    $waon_class_priority_quantity += $request['goo_num'][$key]; //仓库类别对应优先库存总数量
                }

                // 进销存算法数组
                $purchase_goo_actual_count[$value] = $request['goo_num'][$key]; //进销存商品数量
                $purchase_goo_actual_price[$value] = 0; //进销存金额

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

            if ($add_data) {
                $wago_id = DB::table('warehouse_goods')->insert($add_data);
            } else {
                $wago_id = true;
            }

            if (empty($temp_ids)) {
                $wago_edit_res = true;
            } else {
                $temp_sql = $temp_sql . ' `wago_stock_number`=  CASE `wago_id` ' . $temp_stock_fine_sql . ' END,'; //修改良品库存数量
                $temp_sql = $temp_sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $temp_stock_priority_sql . ' END,'; //修改优先库存数量
                $temp_sql = $temp_sql . ' `wago_update_time`=  CASE `wago_id` ' . $temp_time_sql . ' END'; //修改时间
                $temp_sql = $temp_sql . ' WHERE `wago_id` IN (' . trim($temp_ids, ',') . ')';
                $wago_edit_res = DB::update($temp_sql);
            }

            // 修改仓库类别表库存数据
            $sql = 'UPDATE `faster_warehouse_onhand` SET ';
            $temp_sql = 'UPDATE `faster_warehouse_onhand` SET ';
            $stock_fine_sql = '';
            $all_amount_sql = '';
            $time_sql = '';
            $ids = '';

            $temp_stock_fine_sql = '';
            $temp_all_amount_sql = '';
            $temp_time_sql = '';
            $temp_ids = '';

            // 良品库存总数量更改
            if ($waon_class_fine_quantity) {
                // 旧货仓库存增加
                $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $old_waon_id . ' THEN `waon_stock_fine_amount` + ' . $waon_class_fine_quantity;
                $all_amount_sql = $all_amount_sql . ' WHEN ' . $old_waon_id . ' THEN `waon_all_amount` + ' . $waon_class_fine_quantity;
                $time_sql = $time_sql . ' WHEN ' . $old_waon_id . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $old_waon_id . ',';
                $sql = $sql . ' `waon_stock_fine_amount`=  CASE `waon_id` ' . $stock_fine_sql . ' END,';
                $sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $all_amount_sql . ' END,';

                // 临时仓库存减少
                $temp_stock_fine_sql = $temp_stock_fine_sql . ' WHEN ' . $temporary_waon_id . ' THEN `waon_stock_fine_amount` - ' . $waon_class_fine_quantity;
                $temp_all_amount_sql = $temp_all_amount_sql . ' WHEN ' . $temporary_waon_id . ' THEN `waon_all_amount` - ' . $waon_class_fine_quantity;
                $temp_time_sql = $temp_time_sql . ' WHEN ' . $temporary_waon_id . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $temp_ids = $temp_ids . $temporary_waon_id . ',';
                $temp_sql = $temp_sql . ' `waon_stock_fine_amount`=  CASE `waon_id` ' . $temp_stock_fine_sql . ' END,';
                $temp_sql = $temp_sql . ' `waon_all_amount`=  CASE `waon_id` ' . $temp_all_amount_sql . ' END,';
            }
            // 优先库存总数量更改
            if ($waon_class_priority_quantity) {
                // 旧货仓库存增加
                $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $old_waon_id . ' THEN `waon_stock_priority_amount` + ' . $waon_class_priority_quantity;
                $all_amount_sql = $all_amount_sql . ' WHEN ' . $old_waon_id . ' THEN `waon_all_amount` + ' . $waon_class_priority_quantity;
                $time_sql = $time_sql . ' WHEN ' . $old_waon_id . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $old_waon_id . ',';
                $sql = $sql . ' `waon_stock_priority_amount`=  CASE `waon_id` ' . $stock_fine_sql . ' END,';
                $sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $all_amount_sql . ' END,';

                // 临时仓库存减少
                $temp_stock_fine_sql = $temp_stock_fine_sql . ' WHEN ' . $temporary_waon_id . ' THEN `waon_stock_priority_amount` + ' . $waon_class_priority_quantity;
                $temp_all_amount_sql = $temp_all_amount_sql . ' WHEN ' . $temporary_waon_id . ' THEN `waon_all_amount` - ' . $waon_class_priority_quantity;
                $temp_time_sql = $temp_time_sql . ' WHEN ' . $temporary_waon_id . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $temp_ids = $temp_ids . $temporary_waon_id . ',';
                $temp_sql = $sql . ' `waon_stock_priority_amount`=  CASE `waon_id` ' . $temp_stock_fine_sql . ' END,';
                $temp_sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $temp_all_amount_sql . ' END,';
            }
            $sql = $sql . ' `waon_update_time`=  CASE `waon_id` ' . $time_sql . ' END';
            $sql = $sql . ' WHERE `waon_id` = (' . trim($ids, ',') . ')';

            $temp_sql = $temp_sql . ' `waon_update_time`=  CASE `waon_id` ' . $temp_time_sql . ' END';
            $temp_sql = $temp_sql . ' WHERE `waon_id` = (' . trim($temp_ids, ',') . ')';
            $waon_priority_res = DB::update($sql);
            $temp_waon_priority_res = DB::update($temp_sql);
            $wago_edit_res = true;
            $temp_wago_edit_res = true;
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 5.进销存
        // 查询仓库类别的进销存计算方式
        $algorithm_type = DB::table('warehouse_class')
            ->where('wacl_cid', $user_info->adm_cid)
            ->where('wacl_shop_id', $user_info->adm_shop_id)
            ->where('wacl_class_numerical', 3)
            ->value('wacl_sssa_id');
        $purchase_return = StockSellStorageGoods::purchaseSales(
            $user_info, //用户信息
            $algorithm_type, //进销存计算方式：1先进先出2移动加权平均法3无成本
            1, //类型：1采购，2销出，3调拨
            $request['ware_id'], //仓库id
            3, //仓库类别
            $request['goo_id'], //数组，商品id
            $purchase_goo_actual_count, //数组，商品数量；[商品id=>商品数量]
            $purchase_goo_actual_price, //数组，商品金额，成本价(不乘以100)；[商品id=>商品金额]
            1 //进销存的移动加权平均法算法类型：1计算平均价2不计算平均价【退换回收时不计算平均价】
        );
        if ($purchase_return['code'] == 500) {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '转换：失败']);
        }
        if ($wago_edit_res && $waon_priority_res && $temp_waon_priority_res && $wago_id && $temp_wago_edit_res) {
            DB::commit();
            $find_goo_name = DB::table('goods')
                ->whereIn('goo_id', $request['goo_id'])
                ->select('goo_name')
                ->get();
            foreach ($find_goo_name as $key => $value) {
                $goo_name[] = $value->goo_name;
            }
            Common::addLog($user_info, getRealIp($request), '我的库存-查看', '商品转换', '商品：（' . implode(',', $goo_name) . '）转换成功成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => '转换成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '转换失败']);
        }
    }

    // 商品库存导出
    public function exportGoods(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询字段
        $select_field = 'goo_goods_encode,goo_id, goo_type, goo_name,  goo_bra_name, goo_brse_id, goo_cate_name, wago_stock_number, wago_priority_stock_number, wago_unchecked_stock_number, wago_freight_stock_number, wago_freight_priority_stock_number, wago_freight_unchecked_stock_number, wago_stock_amount, wago_priority_stock_amount, wago_unchecked_stock_amount, wago_id, goo_class, goo_unit_conversion, goo_unit, wago_goo_price, wago_goo_amount,goo_unta_id';

        $search_data = $request->all();
        $waog_stock_type = true; //查询库存数量状态值：true查询有库存数量的，false查询所有的
        $wago_type = $request->input('wago_type', 1); //wago_type:1查询有库存数量的2查询所有的3查询库存数量为0的
        $data = DB::table('warehouse_goods as a')
            ->leftJoin('goods as b', 'b.goo_id', '=', 'a.wago_goo_id')
            ->where('wago_ware_id', $request['ware_id'])
            ->where('wago_class', $request['waon_class'])
            ->where(function ($query) use ($wago_type) {
                if ($wago_type == 1) {
                    $query->where('wago_stock_number', '>', 0)
                        ->orWhere('wago_lock_quantity', '>', 0)
                        ->orWhere('wago_priority_stock_number', '>', 0)
                        ->orWhere('wago_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_stock_number', '>', 0)
                        ->orWhere('wago_freight_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_priority_stock_number', '>', 0)
                        ->orWhere('wago_freight_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_unchecked_stock_number', '>', 0);
                } elseif ($wago_type == 3) {
                    $query->where('wago_stock_number', 0)
                        ->where('wago_lock_quantity', 0)
                        ->where('wago_priority_stock_number', 0)
                        ->where('wago_priority_lock_quantity', 0)
                        ->where('wago_freight_stock_number', 0)
                        ->where('wago_freight_lock_quantity', 0)
                        ->where('wago_freight_priority_stock_number', 0)
                        ->where('wago_freight_priority_lock_quantity', 0)
                        ->where('wago_unchecked_stock_number', 0);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('goo_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                }
            })
            ->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_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            }) //品牌系列id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            }) //品类id
            ->selectRaw($select_field)
            ->orderBy('goo_goods_encode', 'asc')
            ->get()->toArray();
        if (!empty($data)) {
            // 将对象转化为数组
            $data = json_decode(json_encode($data), true);
            // 查询系列数据
            $goo_brse_id = array_column($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($data, 'goo_id');
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            // 查询商品附属表信息
            $goaf_data = DB::table('goods_affiliate')
                ->where('goaf_shop_id', $user_info->adm_shop_id)
                ->whereIn('goaf_goo_id',  $goo_id)
                ->pluck('goaf_another_name', 'goaf_goo_id')
                ->toArray();
            // 查询系统商品属性表信息
            $gosa_data = DB::table('goods_system_affiliate')
                ->where('gosa_shop_id', $user_info->adm_shop_id)
                ->whereIn('gosa_goo_id',  $goo_id)
                ->pluck('gosa_another_name', 'gosa_goo_id')
                ->toArray();
            // 查询仓库名称
            $ware_name = DB::table('warehouse')
                ->where('ware_id', $request['ware_id'])
                ->value('ware_name');
            $dataarray = array();
            foreach ($data as $key => $value) {
                $dataarray[$key]['goo_goods_encode'] = "\t" . $value['goo_goods_encode']; //检索编码
                $dataarray[$key]['goo_name'] = empty($value['goo_name']) ? '' : $value['goo_name'];//商品名称
                if (isset($goaf_data[$value['goo_id']])) { // 商品别名
                    $dataarray[$key]['goaf_another_name'] = $goaf_data[$value['goo_id']];
                } else {
                    $dataarray[$key]['goaf_another_name'] = '';
                }


                //$dataarray[$key]['goo_cate_name'] = $value['goo_cate_name'];
                $dataarray[$key]['goo_bra_name'] = $value['goo_bra_name'];

                if (!empty($value['goo_brse_id']) && isset($brse_data[$value['goo_brse_id']])) {
                    $dataarray[$key]['goo_brse_id'] = $brse_data[$value['goo_brse_id']];
                } else {
                    $dataarray[$key]['goo_brse_id'] = '';
                }
                $dataarray[$key]['wago_stock_number'] = $value['wago_stock_number']; //良品库存数量(仓库+仓位)
                //$dataarray[$key]['goo_unit_conversion'] = $value['goo_unit_conversion'];
                $dataarray[$key]['wago_goo_price'] = number_format($value['wago_goo_price'],2);
                $dataarray[$key]['wago_goo_amount'] = number_format($value['wago_goo_amount'],2);
                $dataarray[$key]['goo_unit'] = $value['goo_unit'];
            }
        } else {
            return response()->json(['code' => 500, 'msg' => '没有符合条件的数据', 'data' => '没有符合条件的数据']);
        }
        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }

        $streamFileRand = $ware_name . rand(10000, 99999) . '.xls';
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' . $streamFileRand;

        $where['action_name'] = '我的仓库-商品库存表';
        //$where['field_name'] = ['检索编码', '商品名称', '商品别名',  '品牌', '系列', '单位', '单位长度', '库存数量', '单价', '总价'];
        $where['field_name'] = ['检索编码', '商品名称', '商品别名',  '品牌', '系列', '库存数量', '单价(元)', '总价(元)','单位'];

        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $dataarray      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($streamFilename)) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => 'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '导出失败']);
        }
    }

    // 我的仓库-直接入库
    public function warehousing(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->warehousingValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, '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;

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

        $rk_number = 'RK' . rand(10, 99) . date('mdHis') . rand(100000, 999999); //单号

        DB::beginTransaction();
        $wafr_ids[] = DB::table('warehouse_freight')
            ->where('wafr_ware_id', $request['ware_id'])
            ->value('wafr_id');
        $wafr_id = $wafr_ids[0];
        // 添加入库单，添加入库商品表数据
        $add_rkdata['pust_cid'] = $user_info->adm_cid;
        $add_rkdata['pust_shop_id'] = $shop_id;
        $add_rkdata['pust_ware_id'] = $request['ware_id'];
        $add_rkdata['pust_remark'] = !empty($request['rk_remark']) ? $request['rk_remark'] : '';
        $add_rkdata['pust_number'] = $rk_number;
        $add_rkdata['pust_create_id'] = $user_info->adm_id;
        $add_rkdata['pust_create_time'] = date('Y-m-d H:i:s');
        $add_rkdata['pust_put_time'] = date('Y-m-d H:i:s');
        $pusg_pust_id = DB::table('put_storage')->insertGetId($add_rkdata);
        $freight_goods_data = []; //仓位入库数据
        $actual_counts = 0;
        $goods_ware_price = [];//修改仓库商品金额需要得单价
        foreach ($goods_data as $key => $value) {
            $goo_data = DB::table('goods')
                ->where('goo_id', $value['goods_id'])
                ->select('goo_id', 'goo_name', 'goo_unit', 'goo_unta_id', 'goo_unit_conversion')
                ->first();
            // 出入库记录需要
            $oure_goods_id[$value['goods_id']] = $value['goods_id']; //出入库商品id
            if (isset($oure_goods_quantity[$value['goods_id']])) {
                if ($goo_data) {
                    $goo_unta_id = $goo_data->goo_unta_id;
                    $goo_unit_conversion = $goo_data->goo_unit_conversion;
                    $oure_goods_quantity[$value['goods_id']] += $value['num'];
                } else {
                    return ['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01'];
                }
            } else {
                if ($goo_data) {
                    $goo_unta_id = $goo_data->goo_unta_id;
                    $goo_unit_conversion = $goo_data->goo_unit_conversion;
                    $oure_goods_quantity[$value['goods_id']] = $value['num'];
                } else {
                    return ['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01'];
                }
            }
            $oure_goods_inventory[$value['goods_id']] = 1; //

            $goods_id[] = $value['goods_id'];
            // 仓位入库数据[仓位id][商品id][num商品入库数量]，用于判断仓位是否有库存同一商品选择多次
            if (isset($freight_goods_data[$wafr_id][$value['goods_id']])) {
                if ($goo_data) {
                    $goo_unta_id = $goo_data->goo_unta_id;
                    $goo_unit_conversion = $goo_data->goo_unit_conversion;
                    $freight_goods_data[$wafr_id][$value['goods_id']]['num'] += $value['num'];
                    $freight_goods_data[$wafr_id][$value['goods_id']]['wafr_id'] = $wafr_id;
                    $freight_goods_data[$wafr_id][$value['goods_id']]['wfog_type'] = 10;
                    $freight_goods_data[$wafr_id][$value['goods_id']]['wfog_outin_type'] = 2;
                    $freight_goods_data[$wafr_id][$value['goods_id']]['wfog_primary_id'] = $pusg_pust_id;
                } else {
                    return ['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01'];
                }
            } else {
                if ($goo_data) {
                    $goo_unta_id = $goo_data->goo_unta_id;
                    $goo_unit_conversion = $goo_data->goo_unit_conversion;
                    $freight_goods_data[$wafr_id][$value['goods_id']] = (array)$value;
                    $freight_goods_data[$wafr_id][$value['goods_id']]['num'] = $value['num'];
                    $freight_goods_data[$wafr_id][$value['goods_id']]['wafr_id'] = $wafr_id;
                    $freight_goods_data[$wafr_id][$value['goods_id']]['wfog_type'] = 10;
                    $freight_goods_data[$wafr_id][$value['goods_id']]['wfog_outin_type'] = 2;
                    $freight_goods_data[$wafr_id][$value['goods_id']]['wfog_primary_id'] = $pusg_pust_id;
                } else {
                    return ['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01'];
                }
            }

            // 仓库入库数据
            if (isset($ware_goods_data[$value['goods_id']])) {
                if ($goo_data) {
                    $goo_unta_id = $goo_data->goo_unta_id;
                    $goo_unit_conversion = $goo_data->goo_unit_conversion;
                    $ware_goods_data[$value['goods_id']] += $value['num'];
                } else {
                    return ['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01'];
                }
            } else {
                if ($goo_data) {
                    $goo_unta_id = $goo_data->goo_unta_id;
                    $goo_unit_conversion = $goo_data->goo_unit_conversion;
                    $ware_goods_data[$value['goods_id']] = $value['num'];
                } else {
                    return ['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01'];
                }
            }
            if ($goo_data) {
                $actual_counts += $value['num']; //当前入库提交商品的实际入库总数量
            }
            // 新的入库单商品数据
            $temp_storage_goods['pusg_ware_id'] = $user_info->adm_cid;
            $temp_storage_goods['pusg_shop_id'] = $user_info->adm_shop_id;
            $temp_storage_goods['pusg_goo_id'] = $value['goods_id'];
            $temp_storage_goods['pusg_goo_price'] = $value['goods_price'];
            $temp_storage_goods['pusg_fine_stock_number'] = $value['num'];
            $temp_storage_goods['pusg_update_time'] = date('Y-m-d H:i:s'); //到货时间
            // 添加入库商品数据
            $stgo_id = Db::table('put_storage_goods')->insertGetId($temp_storage_goods);
            //修改仓库商品金额需要得单价
            $goods_ware_price[$value['goods_id']]['price'] = $value['goods_price'];
            $goods_ware_price[$value['goods_id']]['goo_unta_id'] = $goo_data->goo_unta_id;
            $goods_ware_price[$value['goods_id']]['goo_unit_conversion'] = $goo_data->goo_unit_conversion;
        }

        $cg_data['cg_wareid'] = $request['ware_id'];
        $cg_data['cg_waon_class'] = 1;
        // 仓库库存调整
        $stgo_retrun = WarehouseFreight::warehouseAddition(
            $cg_data,
            $goods_id,
            $freight_goods_data,
            $ware_goods_data,
            $wafr_ids //数组，仓位id
        );
        if (!$stgo_retrun) {
            return ['code' => 500, 'msg' => 'error', 'data' => '入库失败！01'];
        }
        // 生成仓位商品出入库
        $oure_res = WarehouseFreight::addition(
            $user_info, //用户信息
            $cg_data,
            $pusg_pust_id,
            $rk_number,
            $freight_goods_data
        );
        if (!$oure_res) {
            return ['code' => 500, 'msg' => 'error', 'data' => '入库失败！02'];
        }

        // 2. 查询仓库的库存数量
        $find_waon = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $cg_data['cg_wareid'])
            ->where('waon_class', $cg_data['cg_waon_class'])
            ->select('waon_id', 'waon_all_amount', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount')
            ->first();
        // 更改仓库库存总数量
        $waon_data['waon_all_amount'] = $find_waon->waon_all_amount + $actual_counts; //商品总库存
        $waon_data['waon_stock_fine_amount'] = $find_waon->waon_stock_fine_amount + $actual_counts; //良品总库存
        $waon_res = DB::table('warehouse_onhand')
            ->where('waon_id', $find_waon->waon_id)
            ->update($waon_data);
        // 仓位库存
        $find_wafr = DB::table('warehouse_freight')
            ->where('wafr_id', $wafr_id)
            ->select('wafr_id', 'wafr_all_stock')
            ->first();
        $wafr_data['wafr_all_stock'] = $find_wafr->wafr_all_stock + $actual_counts;
        $wafr_data['wafr_update_time'] = date('Y-m-d H:i:s'); //入库时间
        $update_wafr_res = DB::table('warehouse_freight')
            ->where('wafr_id', $wafr_id)
            ->update($wafr_data);
        // 3.生成出入库记录
        $oure_res = OutinRecord::rkAddition(
            $user_info, //用户信息
            $pusg_pust_id, //原始单的关联id
            $rk_number, //原始单的关联单号
            10, //原始单的关联类型10基础版入库单
            0, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            0, //选择的客户id,会员id/单位id
            $rk_number, //原始单号，入库单单号
            $request['ware_id'], //入库仓库id
            0, //出库仓库id
            $actual_counts, //入库的商品总数量
            18, //出入库记录类型18.基础版入库单
            3, //操作类型：1锁定库存2出库3入库4调货5发货
            $find_waon->waon_stock_fine_amount, //良品总库存
            $find_waon->waon_lock_fine_amount, //良品锁定数量
            $find_waon->waon_stock_priority_amount, //优先总库存
            $find_waon->waon_lock_priority_amount, //优先锁定数量
            $find_waon->waon_stock_unchecked_amount, //待检测总库存
            2, //出入库类型：1出库，2入库
            1, //仓库类别
            $goods_data, //商品id
            $oure_goods_quantity, //商品数量
            $oure_goods_inventory //出库类型1良品2优先
        );

        //直接入库修改商品单价和总价
        $amount_ret = $this->updateWagoAmount($oure_goods_id,$goods_ware_price,$request['ware_id']);
        if($amount_ret['code'] != 200){
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'入库失败011']);
        }

        // 记录日志
        $log_data['user_info'] = $user_info;
        $log_data['rk_number'] = $request['rk_number'];
        $log_data['rk_type'] = '入库';
        $log_data['request'] = $request->all();
        Common::write_record_log($log_data, 'pc/MyWarehouseController.txt', 'warehousing');
        if ($pusg_pust_id) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '我的仓库', '入库', $rk_number . '成功');
            if ($request['rk_remark'] != '') {
                Common::addNote($user_info, $shop_id, $rk_number, $request['rk_remark'], '添加入库单');
            }
            return response()->json(['code' => 200, 'msg' => '入库成功', 'data' => '']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => '入库失败', 'data' => '']);
        }
    }

    /* 商品库存有变化的时候，修改仓库商品得总价 20230518
     * $goods_id 商品id
     * $goods_ware_price 商品id对应得商品单价
     * $ware_id 仓库id
     */
    public function updateWagoAmount($goods_id,$goods_ware_price,$ware_id)
    {
        // 查询仓库商品信息
        $find_tror = DB::table('warehouse_goods')
            ->whereIn('wago_goo_id', $goods_id)
            ->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 = [];
            $price = $v->wago_goo_price;//仓库里该商品得单价
            if(isset($goods_ware_price[$v->wago_goo_id])){
                $price = $goods_ware_price[$v->wago_goo_id]['price'];
            }
            //仓库商品得总价 = 商品单价 * （商品库存 + 商品锁定数量）
            $amount = $price * ($v->wago_stock_number + $v->wago_lock_quantity);
            $trod_data['wago_goo_price'] = $price;
            $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 downTemplate(Request $request)
    {
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => 'storage/Template/warehouses0530.xlsx']);
    }

    // 导入
    public function lead(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMyWarehouseController;
        $error_message = $verify_data->leadValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, '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;
        $post['string'] = 'goo_';
        $post['user_info'] = $user_info;
        $type = 3;
        $where_data = whereFunction($post,$type);
        $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' => '文件大小不能超过5M', 'data' => '文件大小不能超过5M']);
            }

            // 限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return response()->json(['code' => 500, 'msg' => '仅允许上传以xlsx结尾的后缀文件', '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 < 3) {
                return response()->json(['code' => 500, 'msg' => '未获取到数据', 'data' => '未获取到数据']);
            }
            if ($highestRow > 2503) {
                return response()->json(['code' => 500, 'msg' => '一次最多导入1500条数据', 'data' => '一次最多导入1500条数据']);
            }

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

            // 根据仓库名称查询对应的仓库id
            $find_ware_id = DB::table('warehouse')
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->where('ware_id', $request['ware_id'])
                ->select('ware_id', 'ware_state')
                ->first();
            if (empty($find_ware_id)) {
                return response()->json(['code' => 500, 'msg' => '非系统仓库1！', 'data' => '']);
            }
            if ($find_ware_id->ware_state != 1) {
                return response()->json(['code' => 500, 'msg' => '当前仓库已停用！', 'data' => '']);
            }

            $import_staff = []; //导入的仓库数据
            $import_key = 0;
            $data_null = [];//空字段
            for ($j = 3; $j <= $highestRow; $j++) {
                // 品类
                $import_staff[$import_key]['goo_cate_name'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                // 商品名称
                $import_staff[$import_key]['goo_name'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                $import_staff[$import_key]['goo_unit'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());
                // 检索编码
                $import_staff[$import_key]['retrieval_coding'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
                // 库存数量
                $import_staff[$import_key]['wago_stock_number'] = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());
                // 价格
                $import_staff[$import_key]['wago_price'] = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                if (empty($import_staff[$import_key]['goo_cate_name']) && empty($import_staff[$import_key]['goo_name']) && empty($import_staff[$import_key]['retrieval_coding']) && empty($import_staff[$import_key]['wago_stock_number']) && empty($import_staff[$import_key]['wago_price'])) {
                    $data_null[] = $j;
                }else {
                    // 品类
                    if (empty($import_staff[$import_key]['goo_cate_name'])) {
                        return response()->json(['code' => 500, 'msg' => '品类名称必填', 'data' => '']);
                    }
                    if (mb_strlen($import_staff[$import_key]['goo_cate_name']) > 20) {
                        return response()->json(['code' => 500, 'msg' => '品类名称最多20个字', 'data' => '']);
                    }
                    // 商品名称
                    if (empty($import_staff[$import_key]['goo_name'])) {
                        return response()->json(['code' => 500, 'msg' => '商品名称必填', 'data' => '']);
                    }
                    if (mb_strlen($import_staff[$import_key]['goo_name']) > 80) {
                        return response()->json(['code' => 500, 'msg' => '商品名称最多80个字', 'data' => '']);
                    }
                    // 库存数量
                    if (empty($import_staff[$import_key]['wago_stock_number'])) {
                        $import_staff[$import_key]['wago_stock_number'] = 0;
                    }
                }
            }
            if (empty($import_staff)) {
                return response()->json(['code' => 500, 'msg' => '导入表格不能为空，请重新上传！', 'data' => '']);
            }

            DB::beginTransaction();

            $waon_stock_fine_amount = 0; //良品总库存数量
            $freight_goods_data = []; //仓位入库数据

            $temp_hint = [];
            $all_goods_ids = [];
            // 对表格数据处理加入
            for ($j = 3; $j <= $highestRow; $j++) {
                // if(in_array($data_null, $j))
                // 品类
                $add_data['goo_cate_name'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                // 商品名称
                $add_data['goo_name'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                $add_data['goo_unit'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());
                // 检索编码
                $add_data['goo_goods_encode'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
                if (empty($add_data['goo_goods_encode'])) {
                    $add_data['goo_goods_encode'] = '';
                }
                // 库存数量
                $add_data['wago_stock_number'] = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());
                if (empty($add_data['wago_stock_number'])) {
                    $add_data['wago_stock_number'] = 0;
                }
                //商品价格
                $add_data['wago_price'] = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                if(empty($add_data['wago_price']) || $add_data['wago_price'] <= 0){
                    $add_data['wago_price'] = 0;
                }
                // 根据品类、商品名称查询对应的商品id
                $find_goo_data = DB::table('goods')
                    ->where(function ($query) use ($user_info) {
                        $query->where('goo_cid', $user_info->adm_cid)
                            ->orWhere('goo_cid', 0);
                    })
                    ->where(function ($query) use ($where_data) {
                        $query->whereIn($where_data['string'], $where_data['shop_id']);
                    })
                    ->where(function ($query) use ($add_data) {
                        if (!empty($add_data['goo_unit'])) {
                            $query->where('goo_unit', $add_data['goo_unit']);
                        }
                    })
                    ->where('goo_cate_name', $add_data['goo_cate_name']) //品类
                    ->where('goo_name', $add_data['goo_name']) //商品名称
                    ->where('goo_state', 1) //状态1启用2停用
                    ->where('goo_delete', 1)
                    ->select('goo_id', 'goo_name', 'goo_unit', 'goo_unta_id', 'goo_unit_conversion')
                    ->first();
                if (!empty($find_goo_data)) {
                    // 根据仓库id查询仓库名称
                    $find_wafr_data = DB::table('warehouse_freight')
                        ->where('wafr_shop_id', $user_info->adm_shop_id) //所属门店id
                        ->where('wafr_ware_id', $request['ware_id']) //仓库id
                        ->where('wafr_delete', 1)
                        ->select('wafr_id', 'wafr_name', 'wafr_all_stock')
                        ->orderBy('wafr_id', 'desc')
                        ->first();
                    if (empty($find_wafr_data)) {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => '当前仓位不存在，无法导入！', 'data' => '']);
                    }

                    // 查询仓库商品库存数量
                    $find_wago_data = DB::table('warehouse_goods')
                        ->where('wago_ware_id', $request['ware_id'])
                        ->where('wago_goo_id', $find_goo_data->goo_id)
                        ->select('wago_id', 'wago_goo_id', 'wago_stock_number', 'wago_freight_stock_number', 'wago_goo_price')
                        ->get()->toArray();
                    $wago_data = array_column($find_wago_data, null, 'wago_goo_id');

                    $goo_unta_id = $find_goo_data->goo_unta_id;
                    $goo_unit_conversion = $find_goo_data->goo_unit_conversion;
                    $waon_stock_fine_amount = $add_data['wago_stock_number']; //良品总库存量

                    // 判断仓库内是否有入库商品id，有商品id就更改库存数量,没有就新增
                    if (isset($wago_data[$find_goo_data->goo_id])) {
                        // 仓库商品库存数量更改
                        $wago_edit_data['wago_stock_number'] = $wago_data[$find_goo_data->goo_id]->wago_stock_number + $add_data['wago_stock_number']; //良品库存数量（仓库+仓位）
                        $wago_edit_data['wago_freight_stock_number'] = $wago_data[$find_goo_data->goo_id]->wago_freight_stock_number + $add_data['wago_stock_number']; //仓位良品库存数量
                        //商品单价
                        if($add_data['wago_price'] > 0){
                            $wago_edit_data['wago_goo_price'] = $add_data['wago_price'];
                        }
                        $wago_edit_data['wago_update_time'] = date('Y-m-d H:i:s');

                        $wago_id = $wago_data[$find_goo_data->goo_id]->wago_id;
                        // 更改商品库存数量
                        $wago_edit_res = DB::table('warehouse_goods')
                            ->where('wago_id', $wago_data[$find_goo_data->goo_id]->wago_id)
                            ->update($wago_edit_data);
                        if (!$wago_edit_res) {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '仓库商品入库失败1！', 'data' => '']);
                        }
                    } else {
                        // 新增入库商品
                        $wago_edit_data['wago_ware_id'] = $request['ware_id']; //仓库id
                        $wago_edit_data['wago_class'] = 1; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                        $wago_edit_data['wago_goo_id'] = $find_goo_data->goo_id; //商品id
                        // 仓库商品库存数量更改
                        $wago_edit_data['wago_stock_number'] = $add_data['wago_stock_number']; //良品库存数量（仓库+仓位）
                        $wago_edit_data['wago_freight_stock_number'] = $add_data['wago_stock_number']; //仓位良品库存数量
                        //商品单价
                        if($add_data['wago_price'] > 0){
                            $wago_edit_data['wago_goo_price'] = $add_data['wago_price'];
                        }
                        $wago_edit_data['wago_update_time'] = date('Y-m-d H:i:s');
                        $wago_edit_res = DB::table('warehouse_goods')->insertGetId($wago_edit_data);
                        $wago_id = $wago_edit_res; //仓库商品主键id
                        if (!$wago_edit_res) {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '仓库商品入库失败2！', 'data' => '']);
                        }
                    }

                    // 查询仓位商品表库存数量
                    $find_wafg_data = DB::table('warehouse_freight_goods')
                        ->where('wafg_wafr_id', $find_wafr_data->wafr_id) //仓位id
                        ->where('wafg_wago_id', $wago_id) //仓库商品id
                        ->where('wafg_ware_id', $request['ware_id']) //仓库id
                        ->where('wafg_class', 1) //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                        ->where('wafg_goo_id', $find_goo_data->goo_id)
                        ->select('wafg_id', 'wafg_wago_id', 'wafg_goo_id', 'wafg_stock_number')
                        ->first();
                    if (empty($find_wafg_data)) {
                        $wafg_data['wafg_wafr_id'] = $find_wafr_data->wafr_id; //仓位id
                        $wafg_data['wafg_wago_id'] = $wago_id; //仓库商品id
                        $wafg_data['wafg_ware_id'] = $request['ware_id']; //仓库id
                        $wafg_data['wafg_class'] = 1; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                        $wafg_data['wafg_goo_id'] = $find_goo_data->goo_id; //商品id
                        $wafg_data['wafg_stock_number'] = $add_data['wago_stock_number']; //良品库存数量
                        $wafg_res = DB::table('warehouse_freight_goods')->insertGetId($wafg_data);
                        if (!$wafg_res) {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '仓库商品入库失败3！', 'data' => '']);
                        }
                    } else {
                        $wafg_data['wafg_stock_number'] = $find_wafg_data->wafg_stock_number + $add_data['wago_stock_number']; //良品库存数量
                        $wafg_data['wafg_update_time'] = date('Y-m-d H:i:s');
                        $wafg_res = DB::table('warehouse_freight_goods')
                            ->where('wafg_id', $find_wafg_data->wafg_id)
                            ->update($wafg_data);
                        if (!$wafg_res) {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '仓库商品入库失败4！', 'data' => '']);
                        }
                    }

                    // 出入库记录需要
                    $oure_goods_id[$find_goo_data->goo_id] = $find_goo_data->goo_id; //出入库商品id
                    if (isset($oure_goods_quantity[$find_goo_data->goo_id])) {
                        if ($find_goo_data) {
                            $oure_goods_quantity[$find_goo_data->goo_id] += $add_data['wago_stock_number'];
                        } else {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01']);
                        }
                    } else {
                        if ($find_goo_data) {
                            $oure_goods_quantity[$find_goo_data->goo_id] = $add_data['wago_stock_number'];
                        } else {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01']);
                        }
                    }
                    $oure_goods_inventory[$find_goo_data->goo_id] = 1; //出入库商品类型，类型1良品2优先，页面没有用到这个，暂定1

                    // 仓位入库数据[仓位id][商品id][num商品入库数量]，用于判断仓位是否有库存同一商品选择多次
                    $find_goo_data->wfog_primary_id = $wago_id; //关联商品表主键id
                    $find_goo_data->wfog_type = 1; //关联类型：1采购入库
                    $find_goo_data->wfog_outin_type = 2; //出入库类型：1出库2入库
                    $find_goo_data->goods_id = $find_goo_data->goo_id; //商品id
                    $find_goo_data->wafr_id = $find_wafr_data->wafr_id; //仓位id
                    if (isset($freight_goods_data[$find_wafr_data->wafr_id][$find_goo_data->goo_id])) {
                        if ($find_goo_data) {
                            $goo_unta_id = $find_goo_data->goo_unta_id;
                            $freight_goods_data[$find_wafr_data->wafr_id][$find_goo_data->goo_id]['num'] += $add_data['wago_stock_number'];
                        } else {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01']);
                        }
                    } else {
                        if ($find_goo_data) {
                            $goo_unta_id = $find_goo_data->goo_unta_id;
                            $freight_goods_data[$find_wafr_data->wafr_id][$find_goo_data->goo_id] = (array)$find_goo_data;
                            $freight_goods_data[$find_wafr_data->wafr_id][$find_goo_data->goo_id]['num'] = $add_data['wago_stock_number'];
                        } else {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '查无商品信息', 'data' => '入库失败！01']);
                        }
                    }
                    unset($wago_edit_data);
                    unset($wafg_data);

                    $cg_data['cg_wareid'] = $request['ware_id'];
                    $cg_data['cg_waon_class'] = 1;
                    // 生成仓位商品出入库
                    $oure_res = WarehouseFreight::addition(
                        $user_info, //用户信息
                        $cg_data,
                        0,
                        time() . rand(10000, 99999),
                        $freight_goods_data
                    );
                    if (!$oure_res) {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => '入库失败！02', 'data' => '入库失败！02']);
                    }
                    unset($freight_goods_data);
                    // 查询仓库类别-总库存数量表
                    $find_waon_data = DB::table('warehouse_onhand')
                        ->where('waon_ware_id', $request['ware_id'])
                        ->where('waon_class', 1)
                        ->select('waon_id', 'waon_all_amount', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount')
                        ->first();
                    if (empty($find_waon_data)) {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => '仓库类别不存在，无法导入！', 'data' => '']);
                    }
                    if ($waon_stock_fine_amount != 0) {
                        $waon_edit_data['waon_all_amount'] = $find_waon_data->waon_all_amount + $waon_stock_fine_amount; //仓库类别所有商品的总库存
                        $waon_edit_data['waon_stock_fine_amount'] = $find_waon_data->waon_stock_fine_amount + $waon_stock_fine_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', $request['ware_id'])
                            ->where('waon_class', 1)
                            ->update($waon_edit_data);
                        unset($waon_edit_data);

                        // 更改仓位表库存
                        $wafr_edit_data['wafr_all_stock'] = $find_wafr_data->wafr_all_stock + $waon_stock_fine_amount; //良品总库存数量
                        $wafr_edit_data['wafr_update_time'] = date('Y-m-d H:i:s');
                        $wafr_edit_res = DB::table('warehouse_freight')
                            ->where('wafr_shop_id', $user_info->adm_shop_id) //所属门店id
                            ->where('wafr_ware_id', $request['ware_id']) //仓库id
                            ->where('wafr_delete', 1)
                            ->update($wafr_edit_data);
                        unset($wafr_edit_data);
                    } else {
                        $waon_edit_res = true;
                        $wafr_edit_res = true;
                    }


                    if (!$waon_edit_res || !$wafr_edit_res) {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => '仓库类别-总库存数量更新失败2222！', 'data' => '']);
                    }
                    $oure_res = OutinRecord::addition(
                        $user_info, //用户信息
                        0, //原始单的关联id
                        '', //原始单的关联单号
                        11, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
                        0, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                        0, //选择的客户id,会员id/单位id
                        time() . rand(10000, 99999), //原始单号，旧货回收单单号
                        $request['ware_id'], //入库仓库id
                        0, //出库仓库id
                        $waon_stock_fine_amount, //出库的商品总数量
                        19, //出入库记录类型19.库存导入
                        3, //操作类型：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, //待检测总库存
                        2, //出入库类型：1出库，2入库
                        1, //仓库类别
                        $oure_goods_id, //商品id
                        $oure_goods_quantity, //商品数量
                        $oure_goods_inventory, //出库类型1良品2优先
                        [],//仓位id
                        [],//仓库类别商品id
                        [$add_data['wago_price']]//商品单价
                    );
                    if (!$oure_res) {
                        DB::rollBack();
                        return response()->json(['code' => 500, 'msg' => 'error', 'data' => '商品流水记录更新失败']);
                    }
                    //20230530  入库得商品id
                    $all_goods_ids[] = $oure_goods_id;
                    unset($oure_res);
                    unset($oure_goods_id);
                    unset($oure_goods_quantity);
                    unset($oure_goods_inventory);
                } else {
                    $temp_hint[] = '商品名称：' . $add_data['goo_name'] . '  商品编码：' . $add_data['goo_goods_encode'] . '当前商品不存在！';
                }
            }
            //20230530  入库修改商品单价和总价
            if(!empty($all_goods_ids)){
                $amount_ret = $this->updateWagoAmountFromExport($request['ware_id'],$all_goods_ids);
                if($amount_ret['code'] != 200){
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'入库失败', 'data'=>'入库失败011']);
                }
            }

            Common::addLog($user_info, getRealIp($request), '我的仓库', '导入', '导入库存成功');
            DB::commit();
            return response()->json(['code' => 200, 'msg' => '导入成功1', 'data' => '导入成功2', 'encode' => $temp_hint]);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => '导入有误，请重新上传！！', 'data' => '导入有误，请重新上传！！']);
        }
    }

    /* 商品库存有变化的时候，修改仓库商品得总价 20230518
     * $ware_id  仓库id
     * $goods_ids  商品id
     */
    public function updateWagoAmountFromExport($ware_id,$goods_ids)
    {
        $good_ids_data = [];
        foreach ($goods_ids as $g_k => $g_v){
            foreach ($g_v as $d_k => $d_v){
                $good_ids_data[] = $d_v;
            }
        }
        if(empty(1)){
            return ['code'=>500, 'msg'=>'success', 'data'=>'商品不存在'];
        }
        // 查询仓库商品信息
        $find_tror = DB::table('warehouse_goods')
            ->whereIn('wago_goo_id', $good_ids_data)
            ->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'=>'修改总价成功'];
    }

    /**
     * 单位转库存
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-06-21
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function unitConversion(Request $request) {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($request['type'] == 1) {//转库存查询信息
            $find_wago = DB::table('warehouse_goods')
                ->leftJoin('goods', 'goo_id', '=', 'wago_goo_id')
                ->where('wago_id', $request['wago_id'])
                ->select('wago_id', 'goo_id', 'goo_unta_id', 'goo_unit','goo_unit_conversion','wago_stock_number', 'goo_level', 'wago_ware_id', 'goo_fid')
                ->first();
            $main_goods = [];
            $byGoods = [];
            $find_byGoods = [];
            if ($find_wago) {
                if ($find_wago->goo_level == 1) {
                    $main_goods = $find_wago;
                    $byGoods = DB::table('goods')
                        ->where('goo_fid', $main_goods->goo_id)
                        ->where('goo_level', 2)
                        ->select('goo_id', 'goo_unta_id', 'goo_unit','goo_unit_conversion')
                        ->first();
                    if ($byGoods) {
                        $find_byGoods = DB::table('warehouse_goods')
                            ->leftJoin('goods', 'goo_id', '=', 'wago_goo_id')
                            ->where('wago_ware_id', $main_goods->wago_ware_id)
                            ->where('wago_goo_id', $byGoods->goo_id)
                            ->select('wago_id', 'goo_id', 'goo_unta_id', 'goo_unit','goo_unit_conversion','wago_stock_number')
                            ->first();
                        if (empty($find_byGoods)) {
                            $byGoods->wago_stock_number = 0;
                        }
                        $find_byGoods = !empty($find_byGoods) ? $find_byGoods : $byGoods;
                    }
                } elseif($find_wago->goo_level == 2) {
                    $find_byGoods = $find_wago;
                    $main_goods_data = DB::table('goods')
                        ->where('goo_id', $find_byGoods->goo_fid)
                        ->where('goo_level', 1)
                        ->select('goo_id', 'goo_unta_id', 'goo_unit','goo_unit_conversion')
                        ->first();
                    if ($main_goods_data) {
                        $main_goods = DB::table('warehouse_goods')
                            ->leftJoin('goods', 'goo_id', '=', 'wago_goo_id')
                            ->where('wago_ware_id', $find_wago->wago_ware_id)
                            ->where('wago_goo_id', $main_goods_data->goo_id)
                            ->select('wago_id', 'goo_id', 'goo_unta_id', 'goo_unit','goo_unit_conversion','wago_stock_number')
                            ->first();
                        if (empty($main_goods)) {
                            $main_goods_data->wago_stock_number = 0;
                        }
                        $main_goods = !empty($main_goods) ? $main_goods : $main_goods_data;
                    }
                }
            }
            $return_data['main_goods'] = !empty($main_goods)  ? $main_goods:'';//主商品
            $return_data['find_byGoods'] = !empty($find_byGoods)  ? $find_byGoods:'';//副商品
            return response()->json(['code'=>200,'msg'=>'success','data'=>$return_data]);
        } else {
            DB::beginTransaction();
            $res = WashMyWarehouseService::unitConversion($user_info, $request->all());
            if ($res['code'] == 200) {
                Common::addLog($user_info, getRealIp($request), '仓库', '转库存', '仓库商品转库存成功');
                DB::commit();
            } else {
                DB::rollBack();
            }
            return response()->json(['code'=>200,'msg'=>'转库存成功','data'=>'']);
        }
    }
}

