<?php
namespace App\Http\Controllers\Api\WarehouseManage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\WarehouseManage\VerifyWarehouseFreightController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;

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

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

    // 设置仓位
    public function addFreight(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWarehouseFreightController;
        $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']);

        $wafr_data = json_decode($request['wafr_data'], true);
        $wafr_delete_data = json_decode($request['wafr_delete_data'], true);
        if (empty($wafr_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'至少设置一个仓位！']);
        }

        DB::beginTransaction();
        if ($wafr_delete_data) {
            // 删除仓位数据
            foreach ($wafr_delete_data as $key => $value) {
                $find_wafr_data = DB::table('warehouse_freight')
                    ->where('wafr_id', $value['wafr_id'])
                    ->select('wafr_id', 'wafr_all_stock', 'wafr_lock_quantity', 'wafr_priority_all_stock', 'wafr_priority_lock_quantity', 'wafr_unchecked_all_stock')
                    ->first();
                if ($find_wafr_data->wafr_all_stock > 0 || $find_wafr_data->wafr_lock_quantity > 0 || $find_wafr_data->wafr_priority_all_stock > 0 || $find_wafr_data->wafr_priority_lock_quantity > 0 || $find_wafr_data->wafr_unchecked_all_stock > 0) {
                    DB::rollBack();
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => $value['wafr_name'].'当前仓位有商品库存，无法删除！']);
                }
                $delete_data['wafr_delete'] = 2;
                $delete_data['wafr_update_time'] = date('Y-m-d H:i:s');
                $delete_wafr_res = DB::table('warehouse_freight')
                    ->where('wafr_id', $value['wafr_id'])
                    ->update($delete_data);
                if (!$delete_wafr_res) {
                    DB::rollBack();
                    return response()->json(['code' => 500, 'msg' => 'error', 'data' => $value['wafr_name'].'删除失败！']);
                }
            }
        }

        $request_data['ware_id'] = $request['ware_id'];
        $request_data['adm_shop_id'] = $user_info->adm_shop_id;
        foreach ($wafr_data as $wafr_key => $wafr_value) {
            $freight_data[] = $wafr_value;

            $superior_data['superior_wafr_id'] = $wafr_value['wafr_parent_id'];
            $superior_data['first_parent_id'] = $wafr_value['wafr_id'];
            $superior_data['superior_wafr_rank'] = 0;
            $return_wafr = $this->disposeWarehouseFreight($freight_data, $request_data, $superior_data);
            if ($return_wafr['code'] != 200) {
                DB::rollBack();
                return response()->json($return_wafr);
            }
            unset($freight_data);
        }

        DB::commit();
        Common::addLog($user_info, getRealIp($request), '仓位', '设置仓位', '设置仓位成功');
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => '设置仓位成功']);
    }

    /**
     * [disposeWarehouseFreight 设置仓位数据]
     * @param  [type] $wafr_data     [仓位数组数据]
     * @param  [type] $request_data  [门店id、仓库id]
     * @param  [type] $superior_data [仓位的上级数据]
     * @return [type]                [description]
     */
    private function disposeWarehouseFreight($wafr_data, $request_data, $superior_data)
    {
        foreach ($wafr_data as $key => $value) {
            $data['wafr_shop_id'] = $request_data['adm_shop_id'];//仓位隶属门店id
            $data['wafr_ware_id'] = $request_data['ware_id'];//仓位隶属仓库id
            $data['wafr_parent_id'] = $value['wafr_parent_id'];//仓位隶属上级id
            $data['wafr_rank'] = $value['wafr_rank'];//仓位级别，第几级
            $data['wafr_name'] = $value['wafr_name'];//仓位名称
            $data['wafr_delete'] = $value['wafr_delete'];//是否删除1否2是
            if ($value['wafr_rank'] > 5) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'仓位层级不能超过5级'];
            }
            // 判断是否有仓位id
            if ($value['wafr_id']) {
                // 有仓位id，编辑仓位
                // 查询仓位名称是否重复
                $find_wafr_id = DB::table('warehouse_freight')
                    ->where('wafr_shop_id', $request_data['adm_shop_id'])
                    ->where('wafr_ware_id', $request_data['ware_id'])
                    ->where('wafr_id', '<>', $value['wafr_id'])
                    ->where('wafr_name', $value['wafr_name'])
                    ->where('wafr_delete', 1)
                    ->value('wafr_id');
                if ($find_wafr_id) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>$value['wafr_name'].'仓位名称已存在'];
                }
                $data['wafr_update_time'] = date('Y-m-d H:i:s');
                $res = DB::table('warehouse_freight')->where('wafr_id', $value['wafr_id'])->update($data);
                if (!$res) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'仓位更新失败'];
                }

                if ($value['wafr_rank'] <= $superior_data['superior_wafr_rank']) {
                    $new_superior_data['superior_wafr_id'] = $superior_data['superior_wafr_id'];//仓位隶属上级id
                } else {
                    $new_superior_data['superior_wafr_id'] = $value['wafr_id'];//仓位隶属上级id
                }

                if ($value['wafr_rank'] != 1) {
                    $new_superior_data['first_parent_id'] = $superior_data['first_parent_id'];//仓位所属一级id
                } else {
                    $new_superior_data['first_parent_id'] = $value['wafr_id'];//仓位所属一级id
                }
            } else {
                if ($superior_data['superior_wafr_id'] && $superior_data['superior_wafr_rank'] != 0) {
                    $data['wafr_parent_id'] = $superior_data['superior_wafr_id'];//仓位隶属上级id
                }
                if ($superior_data['first_parent_id'] && $superior_data['superior_wafr_rank'] != 0) {
                    $data['wafr_first_parent_id'] = $superior_data['first_parent_id'];//仓位所属一级id
                }

                // 没有仓位id，新增仓位
                // 查询仓位名称是否重复
                $find_wafr_id = DB::table('warehouse_freight')
                    ->where('wafr_shop_id', $request_data['adm_shop_id'])
                    ->where('wafr_ware_id', $request_data['ware_id'])
                    ->where('wafr_name', $value['wafr_name'])
                    ->where('wafr_delete', 1)
                    ->value('wafr_id');
                if ($find_wafr_id) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>$value['wafr_name'].'仓位名称已存在'];
                }
                $wafr_id = DB::table('warehouse_freight')->insertGetId($data);
                if (!$wafr_id) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'仓位添加失败'];
                }
                if ($value['wafr_rank'] <= $superior_data['superior_wafr_rank']) {
                    $new_superior_data['superior_wafr_id'] = $superior_data['superior_wafr_id'];//仓位隶属上级id
                } else {
                    $new_superior_data['superior_wafr_id'] = $wafr_id;//仓位隶属上级id
                }

                if ($value['wafr_rank'] != 1) {
                    $new_superior_data['first_parent_id'] = $superior_data['first_parent_id'];//仓位所属一级id
                } else {
                    $new_superior_data['first_parent_id'] = $wafr_id;//仓位所属一级id
                }
            }
            $new_superior_data['superior_wafr_rank'] = $value['wafr_rank'];//仓位所属级别
            // echo "====";
            // dump($superior_data);
            // dump($new_superior_data);
            // echo "====";
            // $wafr_rank = $value['wafr_rank'];
            unset($data);
            if (!empty($value['children'])) {
                // 有自己仓位数据，递归处理
                $wafr_return = $this->disposeWarehouseFreight($value['children'], $request_data, $new_superior_data);
                if ($wafr_return['code'] == 500) {
                    return $wafr_return;
                }
            }
        }
        return ['code'=>200, 'msg'=>'success', 'data'=>'成功'];
    }

    // 仓位详情
    public function info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWarehouseFreightController;
        $error_message = $verify_data->infoValidator($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_wafr_data = DB::table('warehouse_freight')
            ->where('wafr_shop_id', $user_info->adm_shop_id)
            ->where('wafr_ware_id', $request['ware_id'])
            ->where('wafr_delete', 1)
            ->select('wafr_id', 'wafr_parent_id', 'wafr_first_parent_id', 'wafr_rank', 'wafr_name', 'wafr_delete')
            ->get()->toArray();
        $find_wafr_data = json_decode(json_encode($find_wafr_data), true);
        $find_wafr_data = array_column($find_wafr_data, null, 'wafr_id');
        // 递归处理无限级分类
        $new_data = $this->infoWarehouseFreight($find_wafr_data);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$new_data]);
    }

    // 递归处理多级仓位目录
    private function infoWarehouseFreight($wafr_data)
    {
        // 无限级分类，递归+引用
        // https://blog.csdn.net/ls1120704214/article/details/82590909?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&dist_request_id=1329188.9454.16178676012215699&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control
        $new_data = [];
        foreach ($wafr_data as $key => $value) {
            if ($value['wafr_parent_id'] > 0) {
                //不是根节点的将自己的地址放到父级的children节点
                $wafr_data[$value['wafr_parent_id']]['children'][] = &$wafr_data[$key];
            } else {
                //根节点直接把地址放到新数组中
                $new_data[] = &$wafr_data[$value['wafr_id']];
            }
        }
        return $new_data;
    }

    // 商品转仓位
    public function transitionFreight(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        if (empty($request['wafr_type'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
        }

        if ($request['wafr_type'] == 1) {
            $find_wafr_data = DB::table('warehouse_freight')
                ->where('wafr_shop_id', $user_info->adm_shop_id)
                ->where('wafr_ware_id', $request['ware_id'])
                ->where('wafr_delete', 1)
                // ->whereNotIn('wafr_id', DB::table('warehouse_freight')->pluck('wafr_parent_id'))
                ->select('wafr_id', 'wafr_parent_id', 'wafr_first_parent_id', 'wafr_rank', 'wafr_name')
                ->get()->toArray();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_wafr_data]);
        }

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

        DB::beginTransaction();

        // 判断仓位商品是否存在
        $find_wafg_id = DB::table('warehouse_freight_goods')
            ->where('wafg_wafr_id', $request['wafr_id'])
            ->where('wafg_ware_id', $request['ware_id'])
            ->where('wafg_class', $request['wago_class'])
            ->where('wafg_wago_id', $request['wago_id'])
            ->where('wafg_goo_id', $request['wago_goo_id'])
            ->select('wafg_id', 'wafg_stock_number', 'wafg_priority_stock_number', 'wafg_unchecked_stock_number')
            ->first();
        if ($find_wafg_id) {
            if ($request['type'] == 1) {
                $wafg_data['wafg_stock_number'] = $find_wafg_id->wafg_stock_number + $request['goo_count'];
            } elseif ($request['type'] == 2) {
                $wafg_data['wafg_priority_stock_number'] = $find_wafg_id->wafg_priority_stock_number + $request['goo_count'];
            } elseif ($request['type'] == 3) {
                $wafg_data['wafg_unchecked_stock_number'] = $find_wafg_id->wafg_unchecked_stock_number + $request['goo_count'];
            }
            $wafg_res = DB::table('warehouse_freight_goods')
                ->where('wafg_id', $find_wafg_id->wafg_id)
                ->update($wafg_data);
        } else {
            $wafg_data['wafg_wafr_id'] = $request['wafr_id'];
            $wafg_data['wafg_ware_id'] = $request['ware_id'];
            $wafg_data['wafg_class'] = $request['wago_class'];
            $wafg_data['wafg_wago_id'] = $request['wago_id'];
            $wafg_data['wafg_goo_id'] = $request['wago_goo_id'];
            if ($request['type'] == 1) {
                $wafg_data['wafg_stock_number'] = $request['goo_count'];
            } elseif ($request['type'] == 2) {
                $wafg_data['wafg_priority_stock_number'] = $request['goo_count'];
            } elseif ($request['type'] == 3) {
                $wafg_data['wafg_unchecked_stock_number'] = $request['goo_count'];
            }
            $wafg_res = DB::table('warehouse_freight_goods')->insertGetId($wafg_data);
        }

        $hint = '';
        // 仓库商品数量处理
        if ($request['type'] == 1) {
            $hint = '良品';
            // 仓库商品数量减少
            $wago_decrement = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->decrement('wago_stock_amount', $request['goo_count']);
            // 仓位商品数量增加
            $wago_increment = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->increment('wago_freight_stock_number', $request['goo_count']);
            // 仓位数量增加
            $wafr_increment = DB::table('warehouse_freight')
                ->where('wafr_id', $request['wafr_id'])
                ->increment('wafr_all_stock', $request['goo_count']);
        } elseif ($request['type'] == 2) {
            $hint = '优先';
            // 仓库商品数量减少
            $wago_decrement = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->decrement('wago_priority_stock_amount', $request['goo_count']);
            // 仓位商品数量增加
            $wago_increment = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->increment('wago_freight_priority_stock_number', $request['goo_count']);
            // 仓位数量增加
            $wafr_increment = DB::table('warehouse_freight')
                ->where('wafr_id', $request['wafr_id'])
                ->increment('wafr_priority_all_stock', $request['goo_count']);
        } elseif ($request['type'] == 3) {
            $hint = '待检测';
            // 仓库商品数量减少(仓库+仓位)
            $wago_decrement = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->decrement('wago_unchecked_stock_amount', $request['goo_count']);
            // 仓位商品数量增加
            $wago_increment = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->increment('wago_freight_unchecked_stock_number', $request['goo_count']);
            // 仓位数量增加
            $wafr_increment = DB::table('warehouse_freight')
                ->where('wafr_id', $request['wafr_id'])
                ->increment('wafr_unchecked_all_stock', $request['goo_count']);
        }

        if ($wafg_res && $wago_decrement && $wago_increment && $wafr_increment) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '我的仓库', '转仓位', $request['goo_name'].' '.$hint.' 转 '.$request['goo_count'].' 库存数量');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'转仓位成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'转仓位失败']);
        }
    }

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

        $search_data = $request->all();
        $wago_type = $request->input('wago_type', 1);//wago_type:1查询有库存数量的2查询所有的3查询库存数量为0的
        $list_data = DB::table('warehouse_freight_goods as wafg')
            ->leftJoin('goods as goo', 'goo.goo_id', '=', 'wafg.wafg_goo_id')
            ->leftJoin('warehouse_goods as wa_goo', 'wa_goo.wago_goo_id', '=', 'wafg.wafg_goo_id')
            ->where('wafg_ware_id', $request['ware_id'])
            ->where('wago_ware_id', $request['ware_id'])
            ->where('wafg_class', $request['waon_class'])
            ->where(function ($query) use ($wago_type) {
                if ($wago_type == 1) {
                    $query->where('wafg_stock_number', '>', 0)
                        ->orWhere('wafg_lock_quantity', '>', 0)
                        ->orWhere('wafg_priority_stock_number', '>', 0)
                        ->orWhere('wafg_priority_lock_quantity', '>', 0)
                        ->orWhere('wafg_unchecked_stock_number', '>', 0);
                } elseif ($wago_type == 3) {
                    $query->where('wafg_stock_number', 0)
                        ->where('wafg_lock_quantity', 0)
                        ->where('wafg_priority_stock_number', 0)
                        ->where('wafg_priority_lock_quantity', 0)
                        ->where('wafg_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
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wafr_id'])) {
                    $query->where('wafg_wafr_id', $search_data['wafr_id']);
                }
            })//仓位id
            ->select('goo_name', 'goo_goods_encode', 'goo_bra_name', 'goo_cate_name', 'wafg_stock_number', 'wafg_lock_quantity', 'wafg_priority_stock_number', 'wafg_priority_lock_quantity', 'wafg_unchecked_stock_number', 'goo_type', 'goo_brse_id', 'wafg_wago_id', 'wafg_wafr_id', 'wafg_id', 'goo_id', 'goo_class', 'goo_unit', 'goo_unta_id', 'wago_goo_price')
            ->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();                //返回数据
        $find_wafr_data1 = DB::table('warehouse_freight')
            ->where('wafr_ware_id', $request['ware_id'])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wafr_id'])) {
                    $query->where('wafr_id', $search_data['wafr_id']);
                }
            })//仓位id
            ->selectRaw('sum(wafr_all_stock) as wafr_all_stock')
            ->first();
        // 统计仓位库存数量
        $find_wafr_data = DB::table('warehouse_freight_goods')
            ->where('wafg_ware_id', $request['ware_id'])
            ->where('wafg_class', $request['waon_class'])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wafr_id'])) {
                    $query->where('wafg_wafr_id', $search_data['wafr_id']);
                }
            })//仓位id
            ->selectRaw('sum(wafg_stock_number) as stock_number, sum(wafg_lock_quantity) as lock_quantity, sum(wafg_priority_stock_number) as priority_stock_number, sum(wafg_priority_lock_quantity) as priority_lock_quantity, sum(wafg_unchecked_stock_number) as unchecked_stock_number')
            ->first();
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($user_info->adm_id == 258) {
            $data_info['wafr_all_stock'] = $find_wafr_data->stock_number.'--'.$find_wafr_data1->wafr_all_stock ?: 0;
        } else {
            $data_info['wafr_all_stock'] = $find_wafr_data->stock_number ?: 0;
        }
        $data_info['wafr_lock_quantity'] = $find_wafr_data->lock_quantity ?: 0;
        $data_info['wafr_priority_all_stock'] = $find_wafr_data->priority_stock_number ?: 0;
        $data_info['wafr_priority_lock_quantity'] = $find_wafr_data->priority_lock_quantity ?: 0;
        $data_info['wafr_unchecked_all_stock'] = $find_wafr_data->unchecked_stock_number ?: 0;
        //20230529  查询仓库总库存和总金额
        $ware_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', 'ware_goo_amount')
            ->first();
        $ware_data = json_decode(json_encode($ware_data),true);
        $data_info['all_stock_amount'] = $ware_data['waon_stock_fine_amount'];
        $data_info['ware_goo_amount'] = number_format($ware_data['ware_goo_amount'],2) .' 元';
        $data_info['brse_data'] = [];//品牌系列数据
        if ($data_info['data']) {
            // 查询品牌系列数据
            $goo_brse_id = array_filter(array_unique(array_column($data_info['data'], 'goo_brse_id')));
            if ($goo_brse_id) {
                $data_info['brse_data'] = DB::table('brand_serie')
                    ->whereIn('brse_id', $goo_brse_id)
                    ->select('brse_id', 'brse_name')
                    ->get();
            }
            // 查询仓位数据
            $wafg_wafr_id = array_column($data_info['data'], 'wafg_wafr_id');
            $wafr_data = DB::table('warehouse_freight')
                ->whereIn('wafr_id', $wafg_wafr_id)
                ->pluck('wafr_name', 'wafr_id')
                ->toArray();
            // 获取当前操作账号信息
            $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();
            foreach ($data_info['data'] as $key => $value) {
                if (!empty($value->wafg_wafr_id)) {
                    $data_info['data'][$key]->wafr_name = $wafr_data[$value->wafg_wafr_id];
                } else {
                    $data_info['data'][$key]->wafr_name = '';
                }
                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 = '';
                }
                //20230529 计算商品总金额   仓库商品单价 * 仓位商品库存
                $data_info['data'][$key]->wafg_goo_amount = number_format($value->wago_goo_price * ($value->wafg_stock_number + $value->wafg_lock_quantity),2) . ' 元';
                $data_info['data'][$key]->wago_goo_price = number_format($value->wago_goo_price,2) . ' 元';
            }
        }
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

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

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

        DB::beginTransaction();

        $find_wafg_id = DB::table('warehouse_freight_goods')
            ->where('wafg_id', $request['wafg_id'])
            ->where('wafg_class', $request['wago_class'])
            ->where('wafg_wago_id', $request['wago_id'])
            ->select('wafg_id', 'wafg_wafr_id', 'wafg_stock_number', 'wafg_priority_stock_number', 'wafg_unchecked_stock_number')
            ->first();
        if ($find_wafg_id) {
            if ($request['type'] == 1) {
                $wafg_number = $find_wafg_id->wafg_stock_number - $request['goo_count'];
            } elseif ($request['type'] == 2) {
                $wafg_number = $find_wafg_id->wafg_priority_stock_number - $request['goo_count'];
            } elseif ($request['type'] == 3) {
                $wafg_number = $find_wafg_id->wafg_unchecked_stock_number - $request['goo_count'];
            }
            if ($wafg_number < 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仓位库存数量不足']);
            }
        }

        // 仓位商品表库存减少,仓库商品表仓库库存增加,仓库商品表仓位库存减少
        $hint = '';
        // 仓库商品数量处理
        if ($request['type'] == 1) {
            $hint = '良品';
            // 仓位商品数量减少
            $wafg_decrement = DB::table('warehouse_freight_goods')
                ->where('wafg_id', $request['wafg_id'])
                ->decrement('wafg_stock_number', $request['goo_count']);
            // 仓库商品数量增加
            $wago_increment = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->increment('wago_stock_amount', $request['goo_count']);
            // 仓库仓位商品数量减少
            $wago_decrement = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->decrement('wago_freight_stock_number', $request['goo_count']);
            // 仓位数量减少
            $wafr_decrement = DB::table('warehouse_freight')
                ->where('wafr_id', $find_wafg_id->wafg_wafr_id)
                ->decrement('wafr_all_stock', $request['goo_count']);
        } elseif ($request['type'] == 2) {
            $hint = '优先';
            // 仓位商品数量减少
            $wafg_decrement = DB::table('warehouse_freight_goods')
                ->where('wafg_id', $request['wafg_id'])
                ->decrement('wafg_priority_stock_number', $request['goo_count']);
            // 仓库商品数量增加
            $wago_increment = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->increment('wago_priority_stock_amount', $request['goo_count']);
            // 仓库仓位商品数量减少
            $wago_decrement = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->decrement('wago_freight_priority_stock_number', $request['goo_count']);
            // 仓位数量减少
            $wafr_decrement = DB::table('warehouse_freight')
                ->where('wafr_id', $find_wafg_id->wafg_wafr_id)
                ->decrement('wafr_priority_all_stock', $request['goo_count']);
        } elseif ($request['type'] == 3) {
            $hint = '待检测';
            // 仓位商品数量减少
            $wafg_decrement = DB::table('warehouse_freight_goods')
                ->where('wafg_id', $request['wafg_id'])
                ->decrement('wafg_unchecked_stock_number', $request['goo_count']);
            // 仓库商品数量增加
            $wago_decrement = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->increment('wago_unchecked_stock_amount', $request['goo_count']);
            // 仓库仓位商品数量减少
            $wago_increment = DB::table('warehouse_goods')
                ->where('wago_id', $request['wago_id'])
                ->decrement('wago_freight_unchecked_stock_number', $request['goo_count']);
            // 仓位数量减少
            $wafr_decrement = DB::table('warehouse_freight')
                ->where('wafr_id', $find_wafg_id->wafg_wafr_id)
                ->decrement('wafr_unchecked_all_stock', $request['goo_count']);
        }

        if ($wafg_decrement && $wago_decrement && $wago_increment && $wafr_decrement) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '我的仓库', '仓位转仓库', $request['goo_name'].' '.$hint.' 转 '.$request['goo_count'].' 库存数量');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'仓位转仓库成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仓位转仓库失败']);
        }
    }

    // 仓位商品转其他仓位
    public function transitionOtherFreight(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWarehouseFreightController;
        $error_message = $verify_data->transitionOtherFreightValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $wafg_data = json_decode($request['wafg_data'],true);
        // $wafg_data = $request['wafg_data'];
        DB::beginTransaction();
        // 仓位商品表库存减少,仓库商品表仓库库存增加,仓库商品表仓位库存减少
        // 仓库商品数量处理
        foreach ($wafg_data as $key => $value) {
            if ($value['wafg_id'] < 0 || !is_numeric($value['wafg_id']) || !is_numeric($value['type']) || !is_numeric($value['goo_count']) || !is_numeric($value['after_wafr_id']) || !is_numeric($value['goo_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误']);
            }
            //转出仓位商品查询
            $find_wafg_id = DB::table('warehouse_freight_goods')
                ->where('wafg_id', $value['wafg_id'])
                ->select('wafg_id', 'wafg_class', 'wafg_ware_id', 'wafg_wago_id', 'wafg_goo_id', 'wafg_wafr_id', 'wafg_stock_number', 'wafg_priority_stock_number', 'wafg_unchecked_stock_number')
                ->first();

            if ($find_wafg_id) {
                if ($value['type'] == 1) {
                    $wafg_number = $find_wafg_id->wafg_stock_number - $value['goo_count'];
                } elseif ($value['type'] == 2) {
                    $wafg_number = $find_wafg_id->wafg_priority_stock_number - $value['goo_count'];
                } elseif ($value['type'] == 3) {
                    $wafg_number = $find_wafg_id->wafg_unchecked_stock_number - $value['goo_count'];
                }
                if ($wafg_number < 0) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仓位库存数量不足']);
                }
            }
            //转入仓位商品查询
            $find_after_wafg_data = DB::table('warehouse_freight_goods')
                ->where('wafg_wafr_id', $value['after_wafr_id'])
                ->where('wafg_goo_id', $value['goo_id'])
                ->where('wafg_class', $find_wafg_id->wafg_class)
                ->select('wafg_id', 'wafg_wafr_id', 'wafg_stock_number', 'wafg_priority_stock_number', 'wafg_unchecked_stock_number')
                ->first();
            if (empty($find_after_wafg_data)) {
                $add_data['wafg_wafr_id'] = $value['after_wafr_id'];
                $add_data['wafg_wago_id'] = $find_wafg_id->wafg_wago_id;
                $add_data['wafg_class'] = $find_wafg_id->wafg_class;
                $add_data['wafg_goo_id'] = $find_wafg_id->wafg_goo_id;
                $add_data['wafg_ware_id'] = $find_wafg_id->wafg_ware_id;
                if ($value['type'] == 1) {
                    // 转出仓位商品数量减少
                    $wafg_decrement = DB::table('warehouse_freight_goods')
                        ->where('wafg_id', $value['wafg_id'])
                        ->decrement('wafg_stock_number', $value['goo_count']);
                    // 新增转入仓位商品数量
                    $add_data['wafg_stock_number'] = $value['goo_count'];
                    // 仓位数量减少
                    $wafr_decrement = DB::table('warehouse_freight')
                        ->where('wafr_id', $find_wafg_id->wafg_wafr_id)
                        ->decrement('wafr_all_stock', $value['goo_count']);
                    // 仓位数量增加
                    $wafr_increment = DB::table('warehouse_freight')
                        ->where('wafr_id', $value['after_wafr_id'])
                        ->increment('wafr_all_stock', $value['goo_count']);
                } elseif ($value['type'] == 2) {
                    // 转出仓位商品数量减少
                    $wafg_decrement = DB::table('warehouse_freight_goods')
                        ->where('wafg_id', $value['wafg_id'])
                        ->decrement('wafg_priority_stock_number', $value['goo_count']);
                    // 转入仓位商品数量增加
                    $add_data['wafg_priority_stock_number'] = $value['goo_count'];
                    // 仓位数量减少
                    $wafr_decrement = DB::table('warehouse_freight')
                        ->where('wafr_id', $find_wafg_id->wafg_wafr_id)
                        ->decrement('wafr_priority_all_stock', $value['goo_count']);
                    // 仓位数量增加
                    $wafr_increment = DB::table('warehouse_freight')
                        ->where('wafr_id', $value['after_wafr_id'])
                        ->increment('wafr_priority_all_stock', $value['goo_count']);
                } elseif ($value['type'] == 3) {
                    // 转出仓位商品数量减少
                    $wafg_decrement = DB::table('warehouse_freight_goods')
                        ->where('wafg_id', $request['before_wafg_id'])
                        ->decrement('wafg_unchecked_stock_number', $value['goo_count']);
                    // 转入仓位商品数量增加
                    $add_data['wafg_unchecked_stock_number'] = $value['goo_count'];
                    // 仓位数量减少
                    $wafr_decrement = DB::table('warehouse_freight')
                        ->where('wafr_id', $find_wafg_id->wafg_wafr_id)
                        ->decrement('wafr_unchecked_all_stock', $value['goo_count']);
                    // 仓位数量增加
                    $wafr_increment = DB::table('warehouse_freight')
                        ->where('wafr_id', $value->after_wafr_id)
                        ->increment('wafr_unchecked_all_stock', $value['goo_count']);
                } 
                $add_data_res = DB::table('warehouse_freight_goods')->insertGetId($add_data);
                if (!$add_data_res || !$wafg_decrement || !$wafr_decrement || !$wafr_increment) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仓位转仓位失败']);
                }
            } else {
                if ($value['type'] == 1) {
                    // 转出仓位商品数量减少
                    $wafg_decrement = DB::table('warehouse_freight_goods')
                        ->where('wafg_id', $value['wafg_id'])
                        ->decrement('wafg_stock_number', $value['goo_count']);
                    // 转入仓位商品数量增加
                    $wafg_increment = DB::table('warehouse_freight_goods')
                        ->where('wafg_id', $find_after_wafg_data->wafg_id)
                        ->increment('wafg_stock_number', $value['goo_count']);
                    // 仓位数量减少
                    $wafr_decrement = DB::table('warehouse_freight')
                        ->where('wafr_id', $find_wafg_id->wafg_wafr_id)
                        ->decrement('wafr_all_stock', $value['goo_count']);
                    // 仓位数量增加
                    $wafr_increment = DB::table('warehouse_freight')
                        ->where('wafr_id', $find_after_wafg_data->wafg_wafr_id)
                        ->increment('wafr_all_stock', $value['goo_count']);
                } elseif ($value['type'] == 2) {
                    // 转出仓位商品数量减少
                    $wafg_decrement = DB::table('warehouse_freight_goods')
                        ->where('wafg_id', $value['wafg_id'])
                        ->decrement('wafg_priority_stock_number', $value['goo_count']);
                    // 转入仓位商品数量增加
                    $wafg_increment = DB::table('warehouse_freight_goods')
                        ->where('wafg_id', $find_after_wafg_data->wafg_id)
                        ->increment('wafg_priority_stock_number', $value['goo_count']);
                    // 仓位数量减少
                    $wafr_decrement = DB::table('warehouse_freight')
                        ->where('wafr_id', $find_wafg_id->wafg_wafr_id)
                        ->decrement('wafr_priority_all_stock', $value['goo_count']);
                    // 仓位数量增加
                    $wafr_increment = DB::table('warehouse_freight')
                        ->where('wafr_id', $find_after_wafg_data->wafg_wafr_id)
                        ->increment('wafr_priority_all_stock', $value['goo_count']);
                } elseif ($value['type'] == 3) {
                    // 转出仓位商品数量减少
                    $wafg_decrement = DB::table('warehouse_freight_goods')
                        ->where('wafg_id', $value['wafg_id'])
                        ->decrement('wafg_unchecked_stock_number', $value['goo_count']);
                   // 转入仓位商品数量增加
                    $wafg_increment = DB::table('warehouse_freight_goods')
                        ->where('wafg_id', $find_after_wafg_data->wafg_id)
                        ->increment('wafg_priority_stock_number', $value['goo_count']);
                    // 仓位数量减少
                    $wafr_decrement = DB::table('warehouse_freight')
                        ->where('wafr_id', $find_wafg_id->wafg_wafr_id)
                        ->decrement('wafr_unchecked_all_stock', $value['goo_count']);
                    // 仓位数量增加
                    $wafr_increment = DB::table('warehouse_freight')
                        ->where('wafr_id', $find_after_wafg_data->wafg_wafr_id)
                        ->increment('wafr_unchecked_all_stock', $value['goo_count']);
                } 
                if (!$wafg_decrement || !$wafg_increment || !$wafr_decrement || !$wafr_increment) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仓位转仓位失败']);
                }
            }
        }
        DB::commit();
        Common::addLog($user_info, getRealIp($request), '我的仓位', '仓位转仓位','仓位转仓位成功');
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'仓位转仓位成功']);
    }

    // 库存转换 - 提交
    public function transitions(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWarehouseFreightController;
        $error_message = $verify_data->transitionsValidator($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_freight_goods = DB::table('warehouse_freight_goods')
            ->where('wafg_id', $request['wafg_id'])
            ->where('wafg_ware_id', $request['ware_id'])
            ->select('wafg_id', 'wafg_goo_id', 'wafg_stock_number', 'wafg_lock_quantity', 'wafg_priority_stock_number', 'wafg_priority_lock_quantity', 'wafg_unchecked_stock_number', 'wafg_wago_id', 'wafg_wafr_id')
            ->first();
        // 查询出仓库商品的仓位库存数量
        $find_warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_id', $warehouse_freight_goods->wafg_wago_id)
            ->where('wago_ware_id', $request['ware_id'])
            ->select('wago_id', 'wago_goo_id', 'wago_stock_number', 'wago_priority_stock_number', 'wago_unchecked_stock_number', 'wago_freight_stock_number', 'wago_freight_lock_quantity', 'wago_freight_priority_stock_number', 'wago_freight_priority_lock_quantity', 'wago_freight_unchecked_stock_number')
            ->first();
        // 查询仓位表库存数量
        $find_warehouse_freight = DB::table('warehouse_freight')
            ->where('wafr_id', $warehouse_freight_goods->wafg_wafr_id)
            ->where('wafr_ware_id', $request['ware_id'])
            ->where('wafr_delete', 1)
            ->select('wafr_id', 'wafr_all_stock', 'wafr_priority_all_stock', 'wafr_unchecked_all_stock')
            ->first();
        // 查询仓位表库存数量
        $find_warehouse_onhand = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $request['ware_id'])
            ->where('waon_class', $request['wago_class'])
            ->select('waon_id', 'waon_all_amount', 'waon_stock_fine_amount', 'waon_stock_priority_amount', 'waon_stock_unchecked_amount')
            ->first();
        // 4.4 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
        $sql = 'UPDATE `faster_warehouse_freight_goods` SET ';
        $stock_number_sql = '';//良品库存数量
        $priority_stock_number_sql = '';//优先库存数量
        $unchecked_stock_number_sql = '';//待检测库存数量
        $update_time_sql = '';//时间
        $ids = '';
        // 1良品转优先2优先转良品3待检测转优先4待检测转良品
        switch ($request['type']) {
            case '1'://1良品转优先
                $stock_number = $warehouse_freight_goods->wafg_stock_number - $request['goo_count'];//良品库存数量
                $wago_freight_stock_number = $find_warehouse_goods->wago_freight_stock_number - $request['goo_count'];//良品库存数量
                $wago_stock_number = $find_warehouse_goods->wago_stock_number - $request['goo_count'];//良品库存数量（仓库+仓位）
                $wafr_all_stock = $find_warehouse_freight->wafr_all_stock - $request['goo_count'];//良品总库存数量
                $waon_stock_fine_amount = $find_warehouse_onhand->waon_stock_fine_amount - $request['goo_count'];//仓库总良品总库存数量
                if ($stock_number < 0 || $wago_freight_stock_number < 0 || $wago_stock_number < 0 || $wafr_all_stock < 0 || $waon_stock_fine_amount < 0) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'良品库存数量不足']);
                }
                $priority_stock_number = $warehouse_freight_goods->wafg_priority_stock_number + $request['goo_count'];//优先库存数量
                $unchecked_stock_number = $warehouse_freight_goods->wafg_unchecked_stock_number;//待检测库存数量

                // 仓库商品表的仓位库存数量调整
                $edit_data['wago_stock_number'] = $wago_stock_number;//良品库存数量（仓库+仓位）
                $edit_data['wago_priority_stock_number'] = $find_warehouse_goods->wago_priority_stock_number + $request['goo_count'];//优先库存数量（仓库+仓位）
                $edit_data['wago_unchecked_stock_number'] = $find_warehouse_goods->wago_unchecked_stock_number;//仓位待检测库存数量（仓库+仓位）
                $edit_data['wago_freight_stock_number'] = $wago_freight_stock_number;//仓位良品库存数量
                $edit_data['wago_freight_priority_stock_number'] = $find_warehouse_goods->wago_freight_priority_stock_number + $request['goo_count'];//仓位优先库存数量
                $edit_data['wago_freight_unchecked_stock_number'] = $find_warehouse_goods->wago_freight_unchecked_stock_number;//仓位待检测库存数量
                $edit_data['wago_update_time'] = date('Y-m-d H:i:s');//更新时间

                // 仓位表库存数量调整
                $edit_wafr_data['wafr_all_stock'] = $wafr_all_stock;//良品总库存数量
                $edit_wafr_data['wafr_priority_all_stock'] = $find_warehouse_freight->wafr_priority_all_stock + $request['goo_count'];//优先总库存
                $edit_wafr_data['wafr_unchecked_all_stock'] = $find_warehouse_freight->wafr_unchecked_all_stock;//待检测总库存
                $edit_wafr_data['wafr_update_time'] = date('Y-m-d H:i:s');//更新时间

                $edit_waon_data['waon_stock_fine_amount'] = $waon_stock_fine_amount;//总库存良品数量
                $edit_waon_data['waon_stock_priority_amount'] = $find_warehouse_onhand->waon_stock_priority_amount + $request['goo_count'];//总库存优先数量
                $edit_waon_data['waon_update_time'] = date('Y-m-d H:i:s');//更新时间

                $hint_log = '：良品转优先，转换数量为'.$request['goo_count'];
                break;
            case '2'://优先转良品
                $priority_stock_number = $warehouse_freight_goods->wafg_priority_stock_number - $request['goo_count'];//优先库存数量
                $wago_freight_priority_stock_number = $find_warehouse_goods->wago_freight_priority_stock_number - $request['goo_count'];//仓位优先库存数量
                $wago_priority_stock_number = $find_warehouse_goods->wago_priority_stock_number - $request['goo_count'];//优先库存数量（仓库+仓位）
                $wafr_priority_all_stock = $find_warehouse_freight->wafr_priority_all_stock - $request['goo_count'];//优先总库存
                $waon_stock_priority_amount = $find_warehouse_onhand->waon_stock_priority_amount - $request['goo_count'];//仓库总良品总库存数量
                if ($priority_stock_number < 0 || $wago_freight_priority_stock_number < 0 || $wago_priority_stock_number < 0 || $wafr_priority_all_stock < 0 || $waon_stock_priority_amount < 0) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'优先库存数量不足']);
                }
                $stock_number = $warehouse_freight_goods->wafg_stock_number + $request['goo_count'];//良品库存数量（仓库+仓位）
                $unchecked_stock_number = $warehouse_freight_goods->wafg_unchecked_stock_number;//待检测库存数量
                
                // 仓库商品表的仓位库存数量调整
                $edit_data['wago_stock_number'] = $find_warehouse_goods->wago_stock_number + $request['goo_count'];//良品库存数量（仓库+仓位）
                $edit_data['wago_priority_stock_number'] = $wago_priority_stock_number;//优先库存数量（仓库+仓位）
                $edit_data['wago_unchecked_stock_number'] = $find_warehouse_goods->wago_unchecked_stock_number;//待检测数量（仓库+仓位）
                $edit_data['wago_freight_stock_number'] = $find_warehouse_goods->wago_freight_stock_number + $request['goo_count'];//仓位良品库存数量
                $edit_data['wago_freight_priority_stock_number'] = $wago_freight_priority_stock_number;//仓位优先库存数量
                $edit_data['wago_freight_unchecked_stock_number'] = $find_warehouse_goods->wago_freight_unchecked_stock_number;//仓位待检测库存数量
                $edit_data['wago_update_time'] = date('Y-m-d H:i:s');//更新时间

                // 仓位表库存数量调整
                $edit_wafr_data['wafr_all_stock'] = $find_warehouse_freight->wafr_all_stock + $request['goo_count'];//良品总库存数量
                $edit_wafr_data['wafr_priority_all_stock'] = $wafr_priority_all_stock;//优先总库存
                $edit_wafr_data['wafr_unchecked_all_stock'] = $find_warehouse_freight->wafr_unchecked_all_stock;//待检测总库存
                $edit_wafr_data['wafr_update_time'] = date('Y-m-d H:i:s');//更新时间

                $edit_waon_data['waon_stock_priority_amount'] = $waon_stock_priority_amount;//总库存良品数量
                $edit_waon_data['waon_stock_fine_amount'] = $find_warehouse_onhand->waon_stock_fine_amount + $request['goo_count'];//总库存优先数量
                $edit_waon_data['waon_update_time'] = date('Y-m-d H:i:s');//更新时间

                $hint_log = '：优先转良品，转换数量为'.$request['goo_count'];
                break;
            case '3'://待检测转优先
                $unchecked_stock_number = $warehouse_freight_goods->wafg_unchecked_stock_number - $request['goo_count'];//待检测库存数量
                $wago_freight_unchecked_stock_number = $find_warehouse_goods->wago_freight_unchecked_stock_number - $request['goo_count'];//仓位优先库存数量
                $wago_unchecked_stock_number = $find_warehouse_goods->wago_unchecked_stock_number - $request['goo_count'];//待检测数量（仓库+仓位）
                $wafr_unchecked_all_stock = $find_warehouse_freight->wafr_unchecked_all_stock - $request['goo_count'];//良品总库存数量
                $waon_stock_unchecked_amount = $find_warehouse_onhand->waon_stock_unchecked_amount - $request['goo_count'];//仓库总待检测总库存数量
                if ($unchecked_stock_number < 0 || $wago_freight_unchecked_stock_number < 0 || $wago_unchecked_stock_number < 0 || $wafr_unchecked_all_stock < 0 || $waon_stock_unchecked_amount < 0) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仓库内商品待检测库存数量不足']);
                }
                $priority_stock_number = $warehouse_freight_goods->wago_priority_stock_number + $request['goo_count'];//优先库存数量(仓库+仓位)
                $stock_number = $warehouse_freight_goods->wafg_stock_number;//良品库存数量
                
                // 仓库商品表的仓位库存数量调整
                $edit_data['wago_stock_number'] = $find_warehouse_goods->wago_stock_number;//良品库存数量（仓库+仓位）
                $edit_data['wago_priority_stock_number'] = $find_warehouse_goods->wago_priority_stock_number + $request['goo_count'];//优先库存数量（仓库+仓位）
                $edit_data['wago_unchecked_stock_number'] = $wago_unchecked_stock_number;//待检测数量（仓库+仓位）
                $edit_data['wago_freight_stock_number'] = $find_warehouse_goods->wago_freight_stock_number;//仓位良品库存数量
                $edit_data['wago_freight_priority_stock_number'] = $find_warehouse_goods->wago_freight_priority_stock_number + $request['goo_count'];//仓位优先库存数量
                $edit_data['wago_freight_unchecked_stock_number'] = $wago_freight_unchecked_stock_number;//仓位待检测库存数量
                $edit_data['wago_update_time'] = date('Y-m-d H:i:s');//更新时间

                // 仓位表库存数量调整
                $edit_wafr_data['wafr_all_stock'] = $find_warehouse_freight->wafr_all_stock;//良品总库存数量
                $edit_wafr_data['wafr_priority_all_stock'] = $find_warehouse_freight->wafr_priority_all_stock + $request['goo_count'];//优先总库存
                $edit_wafr_data['wafr_unchecked_all_stock'] = $wafr_unchecked_all_stock;//待检测总库存
                $edit_wafr_data['wafr_update_time'] = date('Y-m-d H:i:s');//更新时间

                $edit_waon_data['waon_stock_unchecked_amount'] = $waon_stock_unchecked_amount;//总库存良品数量
                $edit_waon_data['waon_stock_priority_amount'] = $find_warehouse_onhand->waon_stock_priority_amount + $request['goo_count'];//总库存优先数量
                $edit_waon_data['waon_update_time'] = date('Y-m-d H:i:s');//更新时间

                $hint_log = '：待检测转优先，转换数量为'.$request['goo_count'];
                break;
            case '4'://待检测转良品
                $unchecked_stock_number = $warehouse_freight_goods->wafg_unchecked_stock_number - $request['goo_count'];//待检测库存数量（仓库+仓位）
                $wago_freight_unchecked_stock_number = $find_warehouse_goods->wago_freight_unchecked_stock_number - $request['goo_count'];//仓位优先库存数量
                $wago_unchecked_stock_number = $find_warehouse_goods->wago_unchecked_stock_number - $request['goo_count'];//仓位待检测库存数量（仓库+仓位）
                $wafr_unchecked_all_stock = $find_warehouse_freight->wafr_unchecked_all_stock - $request['goo_count'];//良品总库存数量
                $waon_stock_unchecked_amount = $find_warehouse_onhand->waon_stock_unchecked_amount - $request['goo_count'];//仓库总待检测总库存数量
                if ($unchecked_stock_number < 0 || $wago_freight_unchecked_stock_number < 0 || $wago_unchecked_stock_number < 0 || $wafr_unchecked_all_stock < 0 || $waon_stock_unchecked_amount < 0) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仓库内商品待检测库存数量不足']);
                }
                $stock_number = $warehouse_freight_goods->wafg_stock_number + $request['goo_count'];//良品库存数量（仓库+仓位）
                $priority_stock_number = $warehouse_freight_goods->wago_priority_stock_number;//优先库存数量
                
                // 仓库商品表的仓位库存数量调整
                $edit_data['wago_stock_number'] = $find_warehouse_goods->wago_stock_number + $request['goo_count'];//良品库存数量（仓库+仓位）
                $edit_data['wago_priority_stock_number'] = $find_warehouse_goods->wago_priority_stock_number;//优先库存数量（仓库+仓位）
                $edit_data['wago_unchecked_stock_number'] = $wago_unchecked_stock_number;//仓位待检测库存数量（仓库+仓位）
                $edit_data['wago_freight_stock_number'] = $find_warehouse_goods->wago_freight_stock_number + $request['goo_count'];//仓位良品库存数量
                $edit_data['wago_freight_priority_stock_number'] = $find_warehouse_goods->wago_freight_priority_stock_number;//仓位优先库存数量
                $edit_data['wago_freight_unchecked_stock_number'] = $wago_freight_unchecked_stock_number;//仓位待检测库存数量
                $edit_data['wago_update_time'] = date('Y-m-d H:i:s');//更新时间

                // 仓位表库存数量调整
                $edit_wafr_data['wafr_all_stock'] = $find_warehouse_freight->wafr_all_stock + $request['goo_count'];//良品总库存数量
                $edit_wafr_data['wafr_priority_all_stock'] = $find_warehouse_freight->wafr_priority_all_stock;//优先总库存
                $edit_wafr_data['wafr_unchecked_all_stock'] = $wafr_unchecked_all_stock;//待检测总库存
                $edit_wafr_data['wafr_update_time'] = date('Y-m-d H:i:s');//更新时间

                $edit_waon_data['waon_stock_unchecked_amount'] = $waon_stock_unchecked_amount;//总库存良品数量
                $edit_waon_data['waon_stock_fine_amount'] = $find_warehouse_onhand->waon_stock_fine_amount + $request['goo_count'];//总库存优先数量
                $edit_waon_data['waon_update_time'] = date('Y-m-d H:i:s');//更新时间
                $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_freight_goods->wafg_id . ' THEN ' .$stock_number;
        // 更改优先库存数量
        $priority_stock_number_sql = $priority_stock_number_sql . ' WHEN ' .$warehouse_freight_goods->wafg_id . ' THEN ' .$priority_stock_number;
        // 更改待检测库存数量
        $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' WHEN ' .$warehouse_freight_goods->wafg_id . ' THEN ' .$unchecked_stock_number;
        // 更改时间
        $update_time_sql = $update_time_sql . ' WHEN ' .$warehouse_freight_goods->wafg_id . ' THEN "' .date('Y-m-d H:i:s').'"';

        $ids = $ids . $warehouse_freight_goods->wafg_id.',';
        $sql = $sql .' `wafg_stock_number`=  CASE `wafg_id` '.$stock_number_sql.' END,';
        $sql = $sql .' `wafg_priority_stock_number`=  CASE `wafg_id` '.$priority_stock_number_sql.' END,';
        $sql = $sql .' `wafg_unchecked_stock_number`=  CASE `wafg_id` '.$unchecked_stock_number_sql.' END,';

        $sql = $sql .' `wafg_update_time`=  CASE `wafg_id` '.$update_time_sql.' END';
        $sql = $sql . ' WHERE `wafg_id` IN ('.trim($ids, ',').')';
        $ware_edit_res = DB::update($sql);

        // 更改仓库库存数量
        $wago_edit_res = DB::table('warehouse_goods')
            ->where('wago_id', $warehouse_freight_goods->wafg_wago_id)
            ->where('wago_ware_id', $request['ware_id'])
            ->update($edit_data);
        // 更改仓位表库存数量
        $wafr_edit_res = DB::table('warehouse_freight')
            ->where('wafr_id', $warehouse_freight_goods->wafg_wafr_id)
            ->where('wafr_ware_id', $request['ware_id'])
            ->update($edit_wafr_data);

        // 更改库存表库存数量
        $waon_edit_res = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $request['ware_id'])
            ->where('waon_class', $request['wago_class'])
            ->update($edit_waon_data);

        if ($ware_edit_res && $wago_edit_res && $wafr_edit_res && $waon_edit_res) {
            DB::commit();
            $goo_name = DB::table('goods')->where('goo_id', $warehouse_freight_goods->wafg_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 searchFreight(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        // 查询上级id
        // $wafr_parent_id = DB::table('warehouse_freight')
        //     ->where('wafr_shop_id', $shop_id)
        //     ->where('wafr_ware_id', $request['ware_id'])
        //     ->where('wafr_delete', 1)
        //     // ->where('wafr_parent_id', '<>', 0)
        //     ->groupBy('wafr_parent_id')
        //     ->pluck('wafr_id', 'wafr_id')->toArray();

        $list_data = DB::table('warehouse_freight')
            ->where('wafr_shop_id', $shop_id)
            ->where('wafr_ware_id', $request['ware_id'])
            ->where('wafr_delete', 1)
            // ->whereNotIn('wafr_id', $wafr_parent_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wafr_name'])) {
                    $query->where('wafr_name', 'like', '%'.$search_data['wafr_name'].'%');
                }
            })
            ->select('wafr_id', 'wafr_name', 'wafr_rank')
            ->paginate(1500);
        $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();
        
        return response()->json(['code'=>200, 'msg'=>'success', 'data_info'=>$data_info]);
    }

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

        $search_data = $request->all();

        $list_data = DB::table('warehouse_freight')
            ->where('wafr_shop_id', $shop_id)
            ->where('wafr_delete', 1)
            ->where('wafr_ware_id', $request['ware_id'])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wafr_name'])) {
                    $query->where('wafr_name', 'like', '%'.$search_data['wafr_name'].'%');
                }
            })
            ->select('wafr_id', 'wafr_name', 'wafr_rank')
            ->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();
        
        return response()->json(['code'=>200, 'msg'=>'success', 'data_info'=>$data_info]);
    }

    // 获取仓位库存数量
    public function getFreightStock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWarehouseFreightController;
        $error_message = $verify_data->getFreightStockValidator($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_data = DB::table('warehouse_freight')
            ->where('wafr_shop_id', $user_info->adm_shop_id)
            ->where('wafr_id', $request['wafr_id'])
            ->select('wafr_all_stock', 'wafr_lock_quantity', 'wafr_priority_all_stock', 'wafr_priority_lock_quantity', 'wafr_unchecked_all_stock')
            ->first();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_data]);
    }

    // 获取推荐仓位
    public function getRecommendFreight(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 采购入库的推荐仓位
        // 查询采购单的商品数数据
        $storage_goods = DB::table('storage_goods')
            ->where('relation_number', $request['cg_number'])
            ->select('goods_id')
            ->get()->toArray();
        // 查询商品的推荐仓位，仓位有库存，库存从多到少
        // 没有库存的，仓位内有商品的，上一次入库仓位
        foreach ($storage_goods as $key => $value) {
            // 查询商品id所在仓库，所在仓位库存，仓位库存有多到少
            $find_wafr_data = DB::table('warehouse_freight_goods as wafg')
                    ->leftjoin('warehouse_freight as wafr', 'wafg.wafg_wafr_id', '=', 'wafr.wafr_id')
                    ->where('wafg_ware_id', $request['ware_id'])
                    ->where('wafg_class', 1)
                    ->where('wafg_goo_id', $value->goods_id)
                    ->where(function ($query) use ($request) {
                        $query->where('wafg_stock_number', '>', 0)
                            ->orWhere('wafg_priority_stock_number', '>', 0);
                    })
                    ->select('wafr_id', 'wafr_name', 'wafr_rank')
                    ->orderBy('wafg_stock_number', 'desc')
                    ->orderBy('wafg_priority_stock_number', 'desc')
                    ->get()->toArray();
            if (empty($find_wafr_data)) {
                // 查询仓位商品出入库表，查询商品入库的仓位历史记录
                $find_wafr_data = DB::table('warehouse_freight_outin_goods as wfog')
                    ->leftjoin('warehouse_freight as wafr', 'wfog.wfog_wafr_id', '=', 'wafr.wafr_id')
                    ->where('wfog_ware_id', $request['ware_id'])
                    ->where('wfog_type', 1)//关联类型：1采购入库2采购退货出库
                    ->where('wfog_goo_id', $value->goods_id)
                    ->select('wafr_id', 'wafr_name', 'wafr_rank')
                    ->orderBy('wfog_id', 'desc')
                    ->get()->toArray();

                // 如果没有历史记录，查询仓库的仓位数据
                if (empty($find_wafr_data)) {
                    $find_wafr_data = DB::table('warehouse_freight')
                        ->where('wafr_ware_id', $request['ware_id'])
                        ->where('wafr_shop_id', $user_info->adm_shop_id)
                        ->where('wafr_delete', 1)//是否删除1否2是
                        ->select('wafr_id', 'wafr_name', 'wafr_rank', 'wafr_shop_id')
                        ->limit(10)
                        ->get()->toArray();
                }
            }
            $storage_goods[$key]->wafr_data = $find_wafr_data;
            unset($find_wafr_data);
        }
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$storage_goods]);
    }

}
