<?php

namespace App\Http\Controllers\Api\recycleManage;

use App\Services\CommonService;
use Illuminate\Http\Request;
use Illuminate\Database\Query\Builder;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\recycleManage\VerifyRecedeRecycleController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Services\WarehouseManage\OutinStockLock;
use App\Http\Models\Services\WarehouseManage\ReturnWarehousing;
use App\Services\ReturnGoods\ReturnGoodsService;
use App\Services\Business\WashOrderBasicService;
use App\Services\Business\WashOrderService;

// 仓储系统 -- 退换入库
class RecedeRecycleController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

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

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->adm_shop_id;
        $page_size  = (int) $request->input('show_count', 10);
        $search_data = $request->all();
        $list_data = DB::table('recede_recycle as r')
            ->leftJoin('recede_client as c', 'r.rec_id', '=', 'c.recl_rec_id')
            ->leftjoin('work_order as wor', 'wor.wor_id', '=', 'r.rec_ord_id')
            ->where('rec_cid', $user_info->adm_cid)
            ->where('rec_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) { //是否回收
                if (!empty($search_data['rec_state'])) {
                    $query->where('r.rec_state', $search_data['rec_state']);
                }
            })
            ->where(function ($query) use ($search_data) { //日期
                if (!empty($search_data['rec_date'])) {
                    $query->where('r.rec_date', 'like', '%' . $search_data['rec_date'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //回收单号
                if (!empty($search_data['rec_number'])) {
                    $query->where('r.rec_number', 'like', '%' . $search_data['rec_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //原订单编号
                if (!empty($search_data['rec_ord_order_number'])) {
                    $query->where('r.rec_ord_order_number', 'like', '%' . $search_data['rec_ord_order_number'] . '%')
                        ->orWhere('wor_order_number', 'like', '%' . $search_data['rec_ord_order_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //仓库名称
                if (!empty($search_data['rec_ware_id'])) {
                    $query->where('r.rec_ware_id', $search_data['rec_ware_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //记录人
                if (!empty($search_data['rec_create_adm_id'])) {
                    $query->where('r.rec_create_adm_id', $search_data['rec_create_adm_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户单位
                if (!empty($search_data['recl_channel_unit'])) {
                    $query->where('c.recl_channel_unit', 'like', '%' . $search_data['recl_channel_unit'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //客户电话
                if (!empty($search_data['recl_phone'])) {
                    $query->where('c.recl_phone', 'like', '%' . $search_data['recl_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //买家类型
                if (!empty($search_data['rec_type'])) {
                    $query->where('r.rec_type', $search_data['rec_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户id
                if (!empty($search_data['recl_client_id'])) {
                    $query->where('recl_client_id', $search_data['recl_client_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //来源类型1. 售后退货 2. 工单退货(换货单) 3 页面新增 4 (工单号)退货单 5技师退回 6技师拒单 7技师终止 8(订单号)退货单
                if (!empty($search_data['rec_source_type'])) {
                    $query->where('rec_source_type', $search_data['rec_source_type']);
                }
            })
            ->select('r.rec_id', 'r.rec_date', 'r.rec_number', 'r.rec_ord_order_number', 'r.rec_type', 'r.rec_price', 'r.rec_amount', 'c.recl_channel_unit', 'c.recl_name', 'c.recl_phone', 'r.rec_remark', 'r.rec_create_adm_id', 'r.rec_ware_id', 'r.rec_state', 'rec_source_type', 'recl_client_id', 'wor_order_number as rec_ord_id', 'rec_type','rec_cancel')
            ->orderBy('r.rec_id', 'desc')
            ->paginate($page_size);
        $info = $list_data->items();
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($info) {
            // 查询出当前列表的账号信息
            $adm_id = array_unique(array_column($info, 'rec_create_adm_id'));
            $recl_client_id = array_unique(array_column($info, 'recl_client_id')); //客户id
            $admin = DB::table('admin')
                ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
                ->where('asr.shop_cid', $user_info->adm_cid)
                ->where('asr.shop_id', $shop_id)
                ->whereIn('admin.adm_id', $adm_id)
                ->pluck('admin.adm_name', 'admin.adm_id')->toArray();
            // 查询出当前列表的仓库信息
            $rec_ware_id = array_unique(array_column($info, 'rec_ware_id'));
            $warehouse = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_shop_id', $shop_id)
                ->whereIn('ware_id', $rec_ware_id)
                // ->pluck('ware_type','ware_name','ware_id')->toArray();
                ->select('ware_type', 'ware_name', 'ware_id')
                ->get()
                ->keyBy('ware_id')->toArray();

            $adms_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_ware_id');
                ->value('adms_myware_id');
            $adms_ware_id = explode(',', $adms_ware_id);
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $recl_client_id)
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            // 查询会员客户
            $member_data = DB::table('member')
                ->where('mem_shop_id', $user_info->adm_shop_id)
                ->whereIn('mem_id', $recl_client_id)
                ->pluck('mem_name', 'mem_id')
                ->toArray();
            foreach ($info as $key => $value) {
                // 创建人
                if (isset($admin[$value->rec_create_adm_id])) {
                    $info[$key]->rec_create_adm_name = $admin[$value->rec_create_adm_id];
                } else {
                    $info[$key]->rec_create_adm_name = '';
                }
                // 仓库名称
                if (isset($warehouse[$value->rec_ware_id])) {
                    $info[$key]->rec_ware_name = $warehouse[$value->rec_ware_id]->ware_name;
                } else {
                    $info[$key]->rec_ware_name = '';
                }
                if (isset($warehouse[$value->rec_ware_id])) {
                    $info[$key]->ware_type = $warehouse[$value->rec_ware_id]->ware_type;
                    if ($warehouse[$value->rec_ware_id]->ware_type == 2 || in_array($value->rec_ware_id, $adms_ware_id)) {
                        $info[$key]->privilege_state = 1;
                    } else {
                        $info[$key]->privilege_state = 2;
                    }
                } else {
                    $info[$key]->ware_type = '';
                }
                if ($value->rec_type == 1) { //会员零售
                    if (isset($member_data[$value->recl_client_id])) {
                        $info[$key]->recl_channel_unit = $member_data[$value->recl_client_id];
                    } else {
                        $info[$key]->recl_channel_unit = $value->recl_channel_unit ? $value->recl_channel_unit : $value->recl_name;
                    }
                } else {
                    // 客户单位名称
                    if (isset($channel[$value->recl_client_id])) {
                        $info[$key]->recl_channel_unit = $channel[$value->recl_client_id];
                    } else {
                        $info[$key]->recl_channel_unit = $value->recl_channel_unit ? $value->recl_channel_unit : $value->recl_name;
                    }
                }
                unset($buttonData);
                $buttonData[] = 'details';
                if($value->rec_state == 1 && $value->rec_cancel != 2){
                    $buttonData[] = 'recycle';//入库
                }
                $button = CommonService::getListButton($buttonData,$list_button);
                $info[$key]->button_one = $button['button_one']??[];
                $info[$key]->button_two = $button['button_two']??[];
                $info[$key]->button_three = $button['button_three']??[];
            }
        }

        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $page_size;        //一页显示多少个
        $data['data'] = $info;                              //返回数据


        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data, 'list_button'=>$list_button]);
    }

    // 新增【废弃】
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyRecedeRecycleController;
        $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;

        $all_price = 0; //回收商品总金额
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || $request['goo_name'][$key] < 0  || !is_numeric($request['goo_goods_encode'][$key]) || $request['goo_goods_encode'][$key] < 0  || !is_numeric($request['goo_amount'][$key]) || $request['goo_amount'][$key] < 0  || !is_numeric($request['goo_price'][$key]) || $request['goo_price'][$key] < 0  || !is_numeric($request['goo_recycle_amount'][$key]) || $request['goo_recycle_amount'][$key] < 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误']);
            }

            $rego_data[$key]['rego_goo_id'] = $value;
            $rego_data[$key]['rego_goo_name'] = $request['goo_name'][$key];
            $rego_data[$key]['rego_goo_goods_encode'] = $request['goo_goods_encode'][$key];
            $rego_data[$key]['rego_goo_price'] = $request['goo_price'][$key] * 100;
            $rego_data[$key]['rego_sell_number'] = $request['goo_amount'][$key];
            $rego_data[$key]['rego_recycle_number'] = $request['goo_recycle_amount'][$key];

            $all_price = $request['goo_price'][$key] * $request['goo_recycle_amount'][$key];
        }

        // 1.退换回收单表添加数据
        $rec_number = 'TH' . rand(100, 999) . date('mdHis') . rand(100000, 999999); // 回收单号

        $add_recycle['rec_cid'] = $user_info->adm_cid; //公司id
        $add_recycle['rec_shop_id'] = $user_info->adm_shop_id; //门店id
        $add_recycle['rec_superior_shop_id'] = $shop_id; //所属总店id
        $add_recycle['rec_date'] = $request['rec_date']; //日期
        $add_recycle['rec_number'] = $rec_number; //回收单号
        $add_recycle['rec_source_type'] = 3; //类型
        $add_recycle['rec_price'] = $all_price * 100; //回收总金额（单位：分）
        $add_recycle['rec_amount'] = $request['rec_amount']; //回收总数量
        $add_recycle['rec_state'] = 1; //回收状态 1.未回收 2.已回收
        $add_recycle['rec_type'] = $request['rec_type']; //买家类型 1.门店零售 2.来往单位
        $add_recycle['rec_ware_id'] = $request['rec_ware_id']; //仓库id
        $add_recycle['rec_create_adm_id'] = $user_info->adm_id; //创建人id
        $add_recycle['rec_remark'] = $request['rec_remark'] ? $request['rec_remark'] : ''; //备注

        DB::beginTransaction();

        $recycle_id = DB::table('recede_recycle')->insertGetId($add_recycle);

        // 回收单商品表
        foreach ($rego_data as $key => $value) {
            $rego_data[$key]['rego_rec_id'] = $recycle_id;
        }
        $add_goods =  DB::table('recede_goods')->insert($rego_data);

        // 3.回收单客户表添加数据
        $jucl_data['recl_rec_id'] = $recycle_id; //回收单id
        $jucl_data['recl_client_id'] = $request['mem_id']; //来往单位id/客户id
        $jucl_data['recl_name'] = $request['mem_name']; //客户姓名
        $jucl_data['recl_phone'] = $request['mem_phone']; //联系电话
        if ($request['rec_type'] == 2) {
            $jucl_data['recl_channel_unit'] = $request['chun_unit_name']; //渠道单位
            $mem_res = true;
        } else {
            // 零售类型，会员对应的退货数量加1
            $mem_res =  DB::table('member')
                ->where('mem_id', $request['mem_id'])
                ->increment('mem_retreat_trade');
        }
        $add_client =  DB::table('recede_client')->insert($jucl_data);

        if ($recycle_id && $add_goods && $add_client && $add_client) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '退换回收', '新增', '新增退换回收单：' . $rec_number . '成功');
            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 VerifyRecedeRecycleController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 回收单数据
        $find_recede = DB::table('recede_recycle')
            ->where('rec_id', $request['rec_id'])
            ->first(['rec_state', 'rec_date', 'rec_type', 'rec_ware_id', 'rec_remark']);

        if (empty($find_recede)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前回收单不存在']);
        }
        // 限制 已经回收了的回收单 无法编辑
        if ($find_recede->rec_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前回收单无法编辑']);
        }
        // 获取到 渠道单位id/客户id
        $find_recede->jucl_client_id = DB::table('recede_client')
            ->where('recl_rec_id', $request['rec_id'])
            ->value('recl_client_id');

        if ($request['type'] == 1) {
            // 获取页面数据
            $find_goods = DB::table('recede_goods')
                ->where('rego_rec_id', $request['rec_id'])
                ->select('rego_goo_id as goo_id', 'rego_goo_name as goo_name', 'rego_goo_goods_encode as goo_goods_encode', 'rego_goo_price as goo_price', 'rego_sell_number as goo_amount', 'rego_recycle_number as goo_recycle_amount')
                ->get();
            $find_recede_client = DB::table('recede_client')
                ->where('recl_rec_id', $request['rec_id'])
                ->first(['recl_channel_unit', 'recl_name', 'recl_phone']);
            $data['recede_data'] = $find_recede;
            $data['goods_data'] = $find_goods;
            $data['client_data'] = $find_recede_client;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

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

        // 验证数据  组合回收单商品表数组
        $all_price = 0;
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || $request['goo_name'][$key] < 0  || !is_numeric($request['goo_goods_encode'][$key]) || $request['goo_goods_encode'][$key] < 0  || !is_numeric($request['goo_amount'][$key]) || $request['goo_amount'][$key] < 0  || !is_numeric($request['goo_price'][$key]) || $request['goo_price'][$key] < 0  || !is_numeric($request['goo_recycle_amount'][$key]) || $request['goo_recycle_amount'][$key] < 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误']);
            }

            $rego_data[$key]['rego_rec_id'] = $request['rec_id'];
            $rego_data[$key]['rego_goo_id'] = $value;
            $rego_data[$key]['rego_goo_name'] = $request['goo_name'][$key];
            $rego_data[$key]['rego_goo_goods_encode'] = $request['goo_goods_encode'][$key];
            $rego_data[$key]['rego_goo_price'] = $request['goo_price'][$key] * 100;
            $rego_data[$key]['rego_sell_number'] = $request['goo_amount'][$key];
            $rego_data[$key]['rego_recycle_number'] = $request['goo_recycle_amount'][$key];

            $all_price += $request['goo_price'][$key] * $request['goo_recycle_amount'][$key];
        }

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

        // 1.退换回收单表修改数据
        $update_recycle['rec_date'] = $request['rec_date']; //日期
        $update_recycle['rec_price'] = $all_price * 100; //回收总金额（单位：分）
        $update_recycle['rec_amount'] = $request['rec_amount']; //回收总数量
        $update_recycle['rec_type'] = $request['rec_type']; //买家类型 1.门店零售 2.来往单位
        $update_recycle['rec_ware_id'] = $request['rec_ware_id']; //仓库id
        $update_recycle['rec_remark'] = $request['rec_remark'] ? $request['rec_remark'] : ''; //备注
        $update_recycle['rec_update_time'] = date("Y-m-d H:i:s"); //更新时间

        DB::beginTransaction();
        $update_recycle = DB::table('recede_recycle')->where('rec_id', $request['rec_id'])->update($update_recycle);

        // 2.1 删除原来收回单id对应的商品数据
        $del_goods =  DB::table('recede_goods')->where('rego_rec_id', $request['rec_id'])->delete();
        // 2.2 重新添加提交的商品数据
        $add_goods =  DB::table('recede_goods')->insert($rego_data);

        // 3.回收单客户表修改数据
        $jucl_data['recl_rec_id'] = $request['rec_id']; //回收单id
        $jucl_data['recl_client_id'] = $request['mem_id']; //来往单位id/客户id
        $jucl_data['recl_name'] = $request['mem_name']; //客户姓名
        $jucl_data['recl_phone'] = $request['mem_phone']; //联系电话
        $jucl_data['recl_update_time'] = date("Y-m-d H:i:s"); //更新时间
        if ($request['rec_type'] == 2) {
            $jucl_data['recl_channel_unit'] = $request['chun_unit_name']; //渠道单位
        } else {
            $jucl_data['recl_channel_unit'] = ""; //渠道单位
        }
        $update_client =  DB::table('recede_client')
            ->where('recl_rec_id', $request['rec_id'])
            ->update($jucl_data);

        if ($update_recycle && $add_goods && $del_goods && $update_client) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '退换回收', '编辑', '编辑退换回收单：' . $request['rec_number'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'编辑退换回收单：成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'编辑退换回收单：失败']);
        }
    }

    // 备注【废除】
    public function remark(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyRecedeRecycleController;
        $error_message = $verify_data->remarkValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $recede_data = DB::table('recede_recycle')
            ->where('rec_id', $request['rec_id'])
            ->value('rec_id');
        if (empty($recede_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前回收单不存在']);
        }

        $update_data['rec_remark'] = $request['rec_remark'];
        $update_data['rec_update_time'] = date('Y-m-d H:i:s');
        $update_remark = DB::table('recede_recycle')
            ->where('rec_id', $request['rec_id'])
            ->update($update_data);

        if ($update_remark) {
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '退换回收', '备注', '备注退换回收单：' . $request['rec_number'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'备注退换回收单：成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'备注退换回收单：失败']);
        }
    }

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

        // 获取回收单数据
        $find_recede = DB::table('recede_recycle as re')
            ->leftjoin('admin as a', 'a.adm_id', '=', 're.rec_create_adm_id')
            ->leftjoin('recede_client as recl', 'recl.recl_rec_id', '=', 're.rec_id')
            ->where('rec_id', $request['rec_id'])
            ->select('rec_number', 'rec_ord_id', 'rec_ord_order_number', 'rec_create_time', 'rec_state', 'rec_amount', 'rec_remark', 'rec_date', 'rec_price', 'rec_mobile_ware_id', 'rec_source_type', 'rec_ware_id', 'adm_name as rec_create_adm_name', 'rec_waon_class', 'rec_id', 'rec_type', 'recl_client_id', 'recl_channel_unit', 'recl_name')
            ->first();
        if (empty($find_recede)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前退换入库单不存在']);
        }
        if ($find_recede->rec_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前退货入库单已回收']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        // 查询出客户单位名称 客户姓名 联系电话
        $client = DB::table('recede_client')
            ->where('recl_rec_id', $request['rec_id'])
            ->select('recl_channel_unit', 'recl_name', 'recl_phone', 'recl_client_id')
            ->first();

        if ($request['type'] == 1) { //获取页面数据
            if ($find_recede->rec_type == 1) {
                $find_recede->recl_channel_unit = DB::table('member')
                    ->where('mem_id', $client->recl_client_id)
                    ->value('mem_name as chun_unit_name');
            } else {
                $find_recede->recl_channel_unit = DB::table('channel_unit')
                    ->where('chun_id', $client->recl_client_id)
                    ->value('chun_unit_name');
            }
            unset($client->recl_client_id);
            $find_recede->recl_name = $client->recl_name;
            $find_recede->recl_phone = $client->recl_phone;
            // 查询出仓库名称
            $find_recede->ware_name = DB::table('warehouse')
                ->where('ware_id', $find_recede->rec_ware_id)
                ->value('ware_name');

            $find_goods = DB::table('recede_goods as rego')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'rego.rego_goo_id')
                ->where('rego_rec_id', $request['rec_id'])
                ->select('rego_goo_id as goo_id', 'rego_goo_name as goo_name', 'rego_goo_goods_encode as goo_goods_encode', 'rego_goo_price as goo_price', 'rego_sell_number as goo_amount', 'rego_recycle_number as goo_recycle_amount', 'rego_fine_quantity', 'rego_priority_quantity', 'rego_unchecked_quantity', 'rego_ware_id', 'rego_waon_class', 'rego_wago_id', 'goo_type', 'goo_bra_name', 'goo_brse_id', 'goo_class', 'rego_wafg_id', 'rego_goo_inventory', 'rego_orgo_id', 'rego_goo_unit', 'rego_goo_unta_id', 'goo_unit_conversion')
                ->get()->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($find_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($find_goods as $key => $value) {
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($value->goo_brse_id)) {
                        if ($value->goo_class == 2) {
                            $find_goods[$key]->goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->goo_name;
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $find_goods[$key]->goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->goo_name;
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $value->goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $value->goo_name;
                        }
                    }
                }
                unset($find_goods[$key]->goo_brse_id);
                unset($find_goods[$key]->goo_class);
            }

            // 查询当前账号所拥有的仓库权限
            $adms_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_ware_id');
            $adms_ware_id = explode(',', $adms_ware_id);

            // 搜索仓库
            $find_ware = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_superior_shop_id', $shop_id)
                ->where('ware_state', 1)
                ->whereIn('ware_id', $adms_ware_id)
                ->select('ware_id', 'ware_name')
                ->get()->toArray();

            $data['recede_data'] = $find_recede;
            $data['goods_data'] = $find_goods;
            $data['warehouse_data'] = $find_ware;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

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

        $goo_data = json_decode($request['goo_data'], true);
        $goo_amount = 0;
        if (!empty($goo_data)) {
            foreach ($goo_data as $key => $value) {
                // $find_wor_data = DB::table('work_good as wogo')
                //     ->leftjoin('goods as g', 'g.goo_id', '=', 'wogo.wogo_goo_id')
                //     ->where('wogo_wor_id', $find_recede->rec_ord_id)
                //     ->where('wogo_goo_id', $value['goo_id'])
                //     ->select('wogo_goo_amount', 'wogo_recycle_quantity', 'wogo_goo_waste_number', 'goo_unit_conversion', 'wogo_goo_unta_id')
                //     ->first();
                // if(empty($find_wor_data)){
                //     $find_wor_data = DB::table('order_goods as wogo')
                //         ->leftjoin('goods as g', 'g.goo_id', '=', 'wogo.orgo_goo_id')
                //         ->where('orgo_ord_id', $find_recede->rec_ord_id)
                //         ->where('orgo_goo_id', $value['goo_id'])
                //         ->select('orgo_new_goo_quantity as wogo_goo_amount', 'orgo_recycle_quantity as wogo_recycle_quantity', 'goo_unit_conversion', 'orgo_goo_unta_id as wogo_goo_unta_id')
                //         ->first();
                // }
                // if ($find_wor_data->wogo_goo_unta_id == 1) {
                //     $wogo_goo_amount = $find_wor_data->wogo_goo_amount * $find_wor_data->goo_unit_conversion;
                // } else {
                //     $wogo_goo_amount = $find_wor_data->wogo_goo_amount;
                // }
                $find_disgoods = DB::table('dispatch_goods')
                    ->leftjoin('dispatch_bill', 'dego_id', '=', 'digo_dego_id')
                    ->leftjoin('goods', 'goo_id', '=', 'digo_goo_id')
                    ->where('dego_order_type', 1)
                    ->where('dego_wor_id', $find_recede->rec_ord_id)
                    ->where('digo_goo_id', $value['goo_id'])
                    ->first();
                if (empty($find_disgoods)) {
                    // $wor_data = DB::table('work_order')
                    //     ->where('wor_order_id', $find_recede->rec_ord_id)
                    //     ->first();
                    // dump($wor_data);
                    // dump($find_recede->rec_ord_id);
                    // die;
                    $find_disgoods = DB::table('dispatch_goods')
                        ->leftjoin('dispatch_bill', 'dego_id', '=', 'digo_dego_id')
                        ->leftjoin('goods', 'goo_id', '=', 'digo_goo_id')
                        ->where('dego_order_type', 2)
                        ->where('dego_wor_id', $find_recede->rec_ord_id)
                        ->where('digo_goo_id', $value['goo_id'])
                        ->first();
                }
                $wogo_goo_amount = $find_disgoods->digo_goo_quantity;
                
                if ($value['goo_recycle_amount'] > $wogo_goo_amount) {
                    return ['code'=>500, 'msg'=>'退回数量错误', 'data'=>'退回数量错误'];
                }
            }
        }
        // rec_source_type 来源类型1. 售后退货 2. 工单退货(换货单) 3 页面新增 4 (工单号)退货单 5技师退回 6技师拒单 7技师终止 8(订单号)退货单
        if ($find_recede->rec_source_type == 8) {
            // 根据原始单id,查询到订单id
            $find_order = DB::table('order')
                ->where('ord_id', $find_recede->rec_ord_id)
                ->select('ord_id as wor_order_id', 'ord_order_number as wor_order_number', 'ord_type', 'ord_client_id', 'ord_collection_price', 'ord_service_type as wor_service_type', 'ord_actual_price')
                ->first();
        } else {
            // 根据原始单id,查询到订单id
            $find_order = DB::table('work_order')
                ->where('wor_id', $find_recede->rec_ord_id)
                ->select('wor_order_id', 'wor_order_number', 'wor_service_type')
                ->first();
            // 查询速电订单状态值是否为撤销状态
            $ord_wor_state = DB::table('order')
                ->where('ord_id', $find_order->wor_order_id)
                ->where('ord_order_number', $find_order->wor_order_number)
                ->value('ord_wor_state');
        }

        // 查询仓库类型 类型：1固定仓2技师库3移动仓
        $rec_ware_type = DB::table('warehouse')
            ->where('ware_id', $find_recede->rec_ware_id)
            ->value('ware_type');
        // 来源类型 6技师拒单
        if ($find_recede->rec_source_type == 6 || $find_recede->rec_source_type == 7) {
            DB::beginTransaction();
            // 技师拒单
            $return_warehousing_data = ReturnWarehousing::technicianRejection(
                $user_info, //用户信息
                $request->all(), //前端传过来的数据
                $find_recede, //退货入库数据
                $find_order, //原始单相关数据
                $rec_ware_type, //类型：1固定仓2技师库3移动仓
                $ord_wor_state, //查询速电订单状态值是否为撤销状态
                $goo_data //商品数据
            );
            if ($return_warehousing_data['code'] == 200) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '退换回收', '回收', '回收退换回收单：' . $request['rec_number'] . '成功');
            } else {
                DB::rollBack();
            }
            return response()->json($return_warehousing_data);
        }

        $shop_state = true;
        if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
            $shop_state = false;
        }
        $goo_id = array_column($goo_data, 'goo_id');
        // 查询商品名称
        $find_goods = DB::table('goods')
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_cid', 0)
                        ->orwhere('goo_cid', $user_info->adm_cid);
                } else {
                    $query->where('goo_cid', $user_info->adm_cid);
                }
            })
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_shop_id', 0)
                        ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                } else {
                    $query->where('goo_shop_id', $user_info->adm_shop_id);
                }
            })
            ->whereIn('goo_id', $goo_id)
            ->select('goo_id', 'goo_name', 'goo_goods_encode', 'goo_class')
            ->get()->toArray();
        $find_goods = array_column($find_goods, null, 'goo_id');
        $goo_id = array_column($find_goods, 'goo_id');
        DB::beginTransaction();
        // 有移动仓库id，不是技师退回和换货单退回的
        if ($find_recede->rec_mobile_ware_id && $find_recede->rec_source_type != 5 && $find_recede->rec_source_type != 2) {
            // 减少移动仓库的库存数量
            $recede_return = $this->reduceStock($user_info, $find_recede, $request->all());
            if ($recede_return['code'] == 500) {
                DB::rollBack();
                return response()->json($recede_return);
            }
        }

        // // 来源类型1. 售后退货 2. 工单退货(换货单) 3 页面新增 4 (工单号)退货单 5技师退回 6技师拒单 7技师终止 8(订单号)退货单
        // if ($find_recede->rec_source_type == 4 || $find_recede->rec_source_type == 8) {
        //     $oure_type = 13;
        // } elseif ($find_recede->rec_source_type == 2) {
        //     // 减少移动仓库的库存数量
        //     $recede_return = $this->exchangeReduceStock($user_info, $find_recede, $request->all());
        //     if ($recede_return['code'] == 500) {
        //         DB::rollBack();
        //         return response()->json($recede_return);
        //     }
        //     $oure_type = 12;
        // } else {
        //     $oure_type = 5;
        // }
        $oure_type = 5;

        // // 来源类型5技师退回
        // if ($find_recede->rec_source_type == 5) {
        //     // 减少技师库的库存数量
        //     $recede_return_data = ReturnWarehousing::technicianReduceStock(
        //         $user_info, //用户信息
        //         $find_recede, //退换入库数据
        //         $request->all() //前端传过来的数据
        //     );
        //     if ($recede_return_data['code'] == 500) {
        //         DB::rollBack();
        //         return response()->json($recede_return_data);
        //     }
        // }

        // 退货单入库
        $recede_return_data = ReturnWarehousing::returnOrder(
            $user_info, //用户信息
            $find_recede, //退换入库数据
            $request->all(), //前端传过来的数据
            $goo_data,
            $find_order,
            $rec_ware_type
        );
        //退换入库修改商品单价和总价
        $amount_ret = $this->updateWagoAmountRecede($goo_data,$request['rec_ware_id']);
        if($amount_ret['code'] != 200){
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'退换货入库失败011']);
        }
        //申请退货，更新退货管理的退货状态
        $amount_ret = $this->updateOrderGoods($find_recede,$goo_data,$user_info,$client->recl_client_id);
        if($amount_ret['code'] != 200){
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'退换货入库失败012']);
        }

        $post_data['ware_id'] = $find_recede->rec_ware_id;
        $post_data['new_goods_data'] = $goo_data;
        $res = WashOrderBasicService::addGoodPlan($user_info, $post_data);

        /*DB::rollBack();
        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$amount_ret]);*/
        // 记录日志
        $log_data['user_info'] = $user_info;
        $log_data['rec_number'] = $request['rec_number'];
        $log_data['rec_type'] = '技师退回';
        $log_data['request'] = $request->all();
        Common::write_record_log($log_data, 'pc/RecedeRecycleController.txt', 'recycle');
        if ($recede_return_data['code'] == 200) {
            Common::addLog($user_info, getRealIp($request), '退换入库', '入库', '退换入库单：' . $request['rec_number'] . '入库成功');
            DB::commit();
            return response()->json($recede_return_data);
        } else {
            DB::rollBack();
            return response()->json($recede_return_data);
        }
    }

    /*
     * @name 申请退货，更新退货管理的退货状态
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/9/18 14:47
     *
    */
    public function updateOrderGoods($find_recede,$goo_data,$user_info,$recl_client_id){
        //申请退货，更新退货管理的退货状态
        $retgo_data = DB::table('return_goods')->where('retgo_number', $find_recede->rec_number)->first();
        if($retgo_data){
            $new_order_number = $find_recede->rec_ord_order_number;
            $order_data = DB::table('order_goods')->where('orgo_order_number', $find_recede->rec_ord_order_number)
                ->get()->toArray();
            if(empty($order_data)){
                $order_number = DB::table('work_order')
                    ->where('wor_number', $find_recede->rec_ord_order_number)
                    ->value('wor_order_number');
                $new_order_number = $order_number;
                $order_data = DB::table('order_goods')->where('orgo_order_number',$order_number)
                    ->get()->toArray();
            }
            foreach ($order_data as $o_key => $o_value){
                $order_goods[$o_value->orgo_order_number][$o_value->orgo_goo_id] = $o_value->orgo_goo_return_quantity;//已退数量
            }
            DB::table('return_goods')->where('retgo_number',  $find_recede->rec_number)->update(['retgo_return_status'=>3]);
            //更新订单退货数量
            foreach ($goo_data as $t_key => $t_value){
                $order = DB::table('order')->where('ord_order_number', $retgo_data->retgo_order_number)
                    ->select('ord_state','ord_id','ord_client_id','ord_order_price','ord_type')->first();
                if($order->ord_state == 1){//未结算,发货，数量不变，金额变
                    $order_good = DB::table('order')->where('ord_order_number', $retgo_data->retgo_order_number)
                        ->update(['ord_order_price'=>$retgo_data->retgo_amount]);
                    $order_goods_num = DB::table('order_goods')->where('orgo_order_number', $retgo_data->retgo_order_number)
                        ->where('orgo_goo_id', $t_value['goo_id'])->first();
                    //$up_order_goods['orgo_goo_quantity'] = $order_goods_num->orgo_goo_quantity - $t_value['goo_recycle_amount'];
                    $up_order_goods['orgo_can_assign_quantity'] = $order_goods_num->orgo_can_assign_quantity - $t_value['goo_recycle_amount'];
                    $up_order_goods['orgo_new_goo_quantity'] = $order_goods_num->orgo_new_goo_quantity - $t_value['goo_recycle_amount'];
                    $up_order_goods['orgo_goo_amount'] = $order_goods_num->orgo_goo_amount - $t_value['goo_recycle_amount'] * $order_goods_num->orgo_goo_price;
                    $order_good = DB::table('order_goods')->where('orgo_order_number', $retgo_data->retgo_order_number)
                        ->where('orgo_goo_id', $t_value['goo_id'])
                        ->update($up_order_goods);

                    if($order->ord_type == 1){
                        //修改会员欠收金额
                        $find_mem = DB::table('member')->where('mem_id', $order->ord_client_id)
                            ->value('mem_arrears');
                        $mem_arrears = $find_mem - ($order->ord_order_price - $retgo_data->retgo_amount);//欠收金额 = 本来欠收的金额 - （订单原金额 - 订单现在的金额）
                        $update_mem = DB::table('member')->where('mem_id', $order->ord_client_id)
                            ->update(['mem_arrears'=>$mem_arrears]);
                    }else if($order->ord_type == 2){
                        //修改企业会员欠收金额
                        $find_bucl = DB::table('business_client')->where('bucl_id', $order->ord_client_id)
                            ->value('bucl_arrears');
                        $mem_arrears = $find_bucl - ($order->ord_order_price - $retgo_data->retgo_amount);//欠收金额 = 本来欠收的金额 - （订单原金额 - 订单现在的金额）
                        $update_mem = DB::table('business_client')->where('bucl_id', $order->ord_client_id)
                            ->update(['bucl_arrears'=>$mem_arrears]);
                    }
                }
                DB::table('order_goods')->where('orgo_order_number', $new_order_number)
                    ->where('orgo_goo_id', $t_value['goo_id'])
                    ->update(['orgo_goo_return_quantity'=>$order_goods[$new_order_number][$t_value['goo_id']] + $t_value['goo_recycle_amount']]);
                //工单
                $work_order = DB::table('work_order')->where('wor_order_number', $retgo_data->retgo_order_number)
                    ->select('wor_id','wor_goo_amount','wor_new_goo_amount')->first();
                if($work_order){
                    $up_work_order['wor_goo_amount'] = $work_order->wor_goo_amount - $t_value['goo_recycle_amount'];
                    $up_work_order['wor_new_goo_amount'] = $work_order->wor_goo_amount - $t_value['goo_recycle_amount'];
                    $order_good = DB::table('work_order')->where('wor_order_number', $retgo_data->retgo_order_number)
                        ->update($up_work_order);
                    $find_work_good = DB::table('work_good')->where('wogo_wor_id', $work_order->wor_id)
                        ->where('wogo_goo_id', $t_value['goo_id'])
                        ->first();
                    $up_work_order_goods['wogo_goo_amount'] = $find_work_good->wogo_goo_amount - $t_value['goo_recycle_amount'];
                    $rec_goods_one = DB::table('recede_goods as re')
                        ->leftjoin('goods as g', 'g.goo_id', '=', 're.rego_goo_id')
                        ->where('rego_rec_id', $find_recede->rec_id)
                        ->where('rego_goo_id', $t_value['goo_id'])
                        ->select('rego_goo_unta_id','goo_unit_conversion')
                        ->first();
                    $wogo_new_goo_amount = $t_value['goo_recycle_amount'];
                    $up_work_order_goods['wogo_new_goo_amount'] = $find_work_good->wogo_new_goo_amount - $wogo_new_goo_amount;
                    $work_good = DB::table('work_good')->where('wogo_wor_id', $work_order->wor_id)
                        ->where('wogo_goo_id', $t_value['goo_id'])
                        ->update($up_work_order_goods);
                }
            }
            //如果货和款都退了就取消订单
            $params['ord_id'] = $order->ord_id;
            $params['ord_order_number'] = $find_recede->rec_ord_order_number;
            $params['remark'] = '全部退货取消订单';
            $cancel_ret = WashOrderService::cancelOrder($user_info,$params);
            if($cancel_ret['code'] != 200){
                return ['code'=>500, 'msg'=>'取消订单失败', 'data'=>''];
            }
        }
        return ['code'=>200, 'msg'=>'success', 'data'=>'修改订单成功'];
    }

    /* 商品库存有变化的时候，修改仓库商品得总价 20230518
     * $ware_id  商品id
     * $goo_data 退换商品信息
     */
    public function updateWagoAmountRecede($goo_data,$ware_id)
    {
        if(empty($goo_data)){
            return ['code'=>500, 'msg'=>'success', 'data'=>'仓库商品不存在'];
        }
        $good_ids = array_column($goo_data,'goo_id');//商品id

        // 查询仓库商品信息
        $find_tror = DB::table('warehouse_goods')
            ->whereIn('wago_goo_id', $good_ids)
            ->where('wago_class', 1)
            ->where('wago_ware_id', $ware_id)
            ->select('wago_id', 'wago_goo_price', 'wago_goo_amount', 'wago_stock_number', 'wago_lock_quantity', 'wago_ware_id', 'wago_goo_id')
            ->get()->toArray();
        if(empty($find_tror)){
            return ['code'=>500, 'msg'=>'success', 'data'=>'仓库商品不存在'];
        }
        foreach ($find_tror as $k => $v){
            $trod_data = [];
            //仓库商品得总价 = 商品单价 * （商品库存 + 商品锁定数量）
            $amount = $v->wago_goo_price * ($v->wago_stock_number + $v->wago_lock_quantity);
            $trod_data['wago_goo_amount'] = $amount;
            $trod_data['wago_update_time'] =  date('Y-m-d H:i:s'); //更新时间
            //修改仓库商品的总价
            $ware_goo_ret = DB::table('warehouse_goods')
                ->where('wago_ware_id', $v->wago_ware_id)
                ->where('wago_goo_id', $v->wago_goo_id)
                ->where('wago_class', 1)
                ->update($trod_data);
        }
        //查找仓库所有商品总价
        $find_tror_all = DB::table('warehouse_goods')
            ->where('wago_ware_id', $ware_id)
            ->where('wago_class', 1)
            ->select('wago_id', 'wago_goo_amount', 'wago_ware_id')
            ->get()->toArray();
        if(empty($find_tror_all)){
            return ['code'=>500, 'msg'=>'success', 'data'=>'仓库不存在'];
        }
        $ware_all_data = [];
        foreach ($find_tror_all as $a_k => $a_v){
            if(isset($ware_all_data[$a_v->wago_ware_id])){
                $ware_all_data[$a_v->wago_ware_id] += $a_v->wago_goo_amount;
            }else{
                $ware_all_data[$a_v->wago_ware_id] = $a_v->wago_goo_amount;
            }
        }
        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'=>'修改总价成功'];
    }

    /**
     * [reduceStock 减少移动仓库的库存数量]
     * @param  [type] $user_info   [用户信息]
     * @param  [type] $find_recede [退换回收信息数据]
     * @param  [type] $request     [提交的数据]
     * @return [type]              [description]
     */
    private function reduceStock(
        $user_info,
        $find_recede,
        $request
    ) {
        //查询当前工单id商品的退回数量
        $find_work_goods = DB::table('work_good')
            ->where('wogo_wor_id', $find_recede->rec_ord_id)
            ->whereIn('wogo_goo_id', $request['goo_id'])
            ->get(['wogo_goo_id', 'wogo_waon_class', 'wogo_goo_inventory', 'wogo_goo_amount'])
            ->toArray();
        foreach ($find_work_goods as $key => $value) {
            if (isset($wago_class_goods[$value->wogo_goo_inventory][$value->wogo_waon_class][$value->wogo_goo_id])) {
                $wago_class_goods[$value->wogo_goo_inventory][$value->wogo_waon_class][$value->wogo_goo_id]['wogo_goo_amount'] += $value->wogo_goo_amount;
            } else {
                $wago_class_goods[$value->wogo_goo_inventory][$value->wogo_waon_class][$value->wogo_goo_id] = (array)$value;
            }
        }
        $wogo_goo_id = array_column($find_work_goods, 'wogo_goo_id');
        $wogo_waon_class = array_unique(array_column($find_work_goods, 'wogo_waon_class'));

        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $find_recede->rec_mobile_ware_id)
            ->whereIn('wago_class', $wogo_waon_class)
            ->whereIn('wago_goo_id', $wogo_goo_id)
            ->get(['wago_id', 'wago_class', 'wago_stock_number', 'wago_priority_stock_number', 'wago_goo_id'])
            ->toArray();
        if (empty($warehouse_goods)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'退换回收：失败4'];
        }
        foreach ($warehouse_goods as $key => $value) {
            $warehouse_class_goods[$value->wago_class][$value->wago_goo_id] = (array)$value;
        }
        $sql = 'UPDATE `faster_warehouse_goods` SET ';
        $lock_quantity_sql = '';
        $priority_lock_quantity_sql = '';
        $time_sql = '';
        $ids = '';
        $waon_class_fine_quantity = []; //仓库类别对应良品库存总数量
        $waon_class_priority_quantity = []; //仓库类别对应优先库存总数量
        // 移动仓库要出库的商品
        foreach ($wago_class_goods as $goo_inventory => $new_wago_class_goods) {
            foreach ($new_wago_class_goods as $waon_class => $class_goods_data) {
                foreach ($class_goods_data as $goo_id => $value) {
                    // 商品出库类型，良品出库
                    if ($value['wogo_goo_inventory'] == 1) {
                        // 良品剩余库存数量
                        $surplus_quantity = $warehouse_class_goods[$waon_class][$goo_id]['wago_stock_number'] - $value['wogo_goo_amount'];
                        if ($surplus_quantity < 0) {
                            return ['code'=>500, 'msg'=>'error', 'data'=>'移动仓库内商品数量不足'];
                        }
                        // 更改良品库存数量
                        $lock_quantity_sql = $lock_quantity_sql . ' WHEN ' . $warehouse_class_goods[$waon_class][$goo_id]['wago_id'] . ' THEN `wago_stock_number` - ' . $value['wogo_goo_amount'];

                        if (isset($waon_class_fine_quantity[$waon_class])) {
                            $waon_class_fine_quantity[$waon_class] += $value['wogo_goo_amount']; //仓库类别对应良品库存总数量
                        } else {
                            $waon_class_fine_quantity[$waon_class] = $value['wogo_goo_amount']; //仓库类别对应良品库存总数量
                        }
                        // 商品出库类型，优先出库
                    } else {
                        // 优先剩余库存数量
                        $surplus_quantity = $warehouse_class_goods[$waon_class][$goo_id]['wago_priority_stock_number'] - $value['wogo_goo_amount'];
                        if ($surplus_quantity < 0) {
                            return ['code'=>500, 'msg'=>'error', 'data'=>'移动仓库内商品数量不足'];
                        }
                        // 更改优先库存数量
                        $priority_lock_quantity_sql = $priority_lock_quantity_sql . ' WHEN ' . $warehouse_class_goods[$waon_class][$goo_id]['wago_id'] . ' THEN `wago_priority_stock_number` - ' . $value['wogo_goo_amount'];

                        if (isset($waon_class_priority_quantity[$waon_class])) {
                            $waon_class_priority_quantity[$waon_class] += $value['wogo_goo_amount']; //仓库类别对应优先库存总数量
                        } else {
                            $waon_class_priority_quantity[$waon_class] = $value['wogo_goo_amount']; //仓库类别对应优先库存总数量
                        }
                    }

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

        // 2.1 移动仓商品表减锁定库存
        $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $lock_quantity_sql . ' END,';
        $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $priority_lock_quantity_sql . ' END,';
        $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $time_sql . ' END'; //修改时间
        $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
        $wago_res = DB::update($sql);

        // 查询仓库总数量仓库的类别对应的id
        $find_waon_data = DB::table('warehouse_onhand')
            ->where('waon_ware_id', '=', $find_recede->rec_mobile_ware_id)
            ->whereIn('waon_class', $wogo_waon_class)
            ->pluck('waon_id', 'waon_class')->toArray();
        // 良品库存总数量更改
        if ($waon_class_fine_quantity) {
            $sql = 'UPDATE `faster_warehouse_onhand` SET ';
            $lock_fine_sql = '';
            $all_amount_sql = '';
            $time_sql = '';
            $ids = '';
            foreach ($waon_class_fine_quantity as $key => $value) {
                // 查询库存数量
                $stock_fine_amount = DB::table('warehouse_onhand')
                    ->where('waon_id', $find_waon_data[$key])
                    ->value('waon_stock_fine_amount');
                if ($stock_fine_amount - $value < 0) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'当前库存数量不足'];
                }
                $lock_fine_sql = $lock_fine_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_stock_fine_amount` - ' . $value;
                $all_amount_sql = $all_amount_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_all_amount` - ' . $value;
                $time_sql = $time_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $find_waon_data[$key] . ',';
            }
            $sql = $sql . ' `waon_stock_fine_amount`=  CASE `waon_id` ' . $lock_fine_sql . ' END,';
            $sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $all_amount_sql . ' END,';
            $sql = $sql . ' `waon_update_time`=  CASE `waon_id` ' . $time_sql . ' END';
            $sql = $sql . ' WHERE `waon_id` IN (' . trim($ids, ',') . ')';
            $waon_fine_res = DB::update($sql);
        } else {
            $waon_fine_res = true;
        }

        // 优先库存总数量更改
        if ($waon_class_priority_quantity) {
            $sql = 'UPDATE `faster_warehouse_onhand` SET ';
            $lock_fine_sql = '';
            $all_amount_sql = '';
            $time_sql = '';
            $ids = '';
            foreach ($waon_class_priority_quantity as $key => $value) {
                // 查询库存数量
                $stock_priority_amount = DB::table('warehouse_onhand')
                    ->where('waon_id', $find_waon_data[$key])
                    ->value('waon_stock_priority_amount');
                if ($stock_priority_amount - $value < 0) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'当前库存数量不足'];
                }
                $lock_fine_sql = $lock_fine_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_stock_priority_amount` - ' . $value;
                $all_amount_sql = $all_amount_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_all_amount` - ' . $value;
                $time_sql = $time_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $find_waon_data[$key] . ',';
            }
            $sql = $sql . ' `waon_stock_priority_amount`=  CASE `waon_id` ' . $lock_fine_sql . ' END,';
            $sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $all_amount_sql . ' END,';
            $sql = $sql . ' `waon_update_time`=  CASE `waon_id` ' . $time_sql . ' END';
            $sql = $sql . ' WHERE `waon_id` IN (' . trim($ids, ',') . ')';
            $waon_priority_res = DB::update($sql);
        } else {
            $waon_priority_res = true;
        }
        $osld_out_key = 0;
        foreach ($wago_class_goods as $goo_inventory => $new_wago_class_goods) {
            // 遍历仓库类型数据，处理固定仓库对应仓库类型的出入库记录
            foreach ($new_wago_class_goods as $waon_class_key => $class_goods_data) {
                // 进销存，固定仓库，进销存库存数量减少
                // 查询仓库类别的进销存计算方式
                $goo_all_amount = 0;
                foreach ($class_goods_data as $goo_id_key => $value) {
                    // 出入库记录需要的的商品数组
                    $oure_goods_data[$goo_id_key]['goo_quantity'] = $value['wogo_goo_amount']; //出入库商品数量
                    $oure_goods_data[$goo_id_key]['goo_inventory'] = $value['wogo_goo_inventory']; //出入库商品类型，类型1良品2优先，页面没有用到这个，暂定1
                    $goo_all_amount += $value['wogo_goo_amount'];

                    // 出入库记录需要
                    $oure_goods_id[$goo_id_key] = $value['wogo_goo_id']; //出入库商品id
                    $oure_goods_quantity[$goo_id_key] = $value['wogo_goo_amount']; //出入库商品数量
                    $oure_goods_inventory[$goo_id_key] = $value['wogo_goo_inventory']; //出入库商品类型，类型1良品2优先，页面没有用到这个，暂定1

                    // 库存锁定-出入库记录表
                    $osld_goo_data[$osld_out_key]['goo_waon_class'] = $waon_class_key; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                    $osld_goo_data[$osld_out_key]['goo_id'] = $value['rego_goo_id']; //商品id
                    $osld_goo_data[$osld_out_key]['goo_number'] = $value['rego_recycle_number']; //商品数量
                    $osld_goo_data[$osld_out_key]['goo_out_in_type'] = 1; //出入库类型：1出库2入库3锁定4取消锁定
                    $osld_goo_data[$osld_out_key]['goo_inventory'] = $value['rego_goo_inventory']; //类型1良品2优先3待检测
                    // 查询仓库商品库存数量
                    $find_wago_data = DB::table('warehouse_goods')
                        ->where('wago_ware_id', $find_recede->rec_mobile_ware_id)
                        ->where('wago_class', $waon_class_key)
                        ->where('wago_goo_id', $value['rego_goo_id'])
                        ->select('wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                        ->first();
                    if ($value['rego_goo_inventory'] == 1) { //良品
                        $osld_goo_data[$osld_out_key]['old_stock_number'] = $find_wago_data->wago_stock_number + $value['rego_recycle_number']; //旧的商品良品库存数量
                        $osld_goo_data[$osld_out_key]['old_priority_number'] = $find_wago_data->wago_priority_stock_number; //旧的商品优先库存数量
                        $osld_goo_data[$osld_out_key]['new_stock_number'] = $find_wago_data->wago_stock_number; //新的商品良品库存数量
                        $osld_goo_data[$osld_out_key]['new_priority_number'] = $find_wago_data->wago_priority_stock_number; //新的商品优先库存数量
                    } else { //优先
                        $osld_goo_data[$osld_out_key]['old_stock_number'] = $find_wago_data->wago_stock_number; //旧的商品良品库存数量
                        $osld_goo_data[$osld_out_key]['old_priority_number'] = $find_wago_data->wago_priority_stock_number + $value['rego_recycle_number']; //旧的商品优先库存数量
                        $osld_goo_data[$osld_out_key]['new_stock_number'] = $find_wago_data->wago_stock_number; //新的商品良品库存数量
                        $osld_goo_data[$osld_out_key]['new_priority_number'] = $find_wago_data->wago_priority_stock_number; //新的商品优先库存数量
                    }
                    $osld_goo_data[$osld_out_key]['old_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //旧的商品良品库存锁定数量
                    $osld_goo_data[$osld_out_key]['old_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //旧的商品优先库存锁定数量
                    $osld_goo_data[$osld_out_key]['old_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量
                    $osld_goo_data[$osld_out_key]['new_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
                    $osld_goo_data[$osld_out_key]['new_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
                    $osld_goo_data[$osld_out_key]['new_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
                    $osld_goo_data[$osld_out_key]['osld_update_time'] = date('Y-m-d H:i:s'); //更新时间
                    $osld_goo_data[$osld_out_key] = (object)$osld_goo_data[$osld_out_key];
                    $osld_out_key++;
                }

                $find_ware = DB::table('warehouse_onhand')
                    ->where('waon_ware_id', '=', $find_recede->rec_mobile_ware_id)
                    ->where('waon_class', $waon_class_key)
                    ->select('waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_unchecked_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount')
                    ->first();
                // 新增一条出库记录
                // 根据原始单id,查询到订单id
                $find_order = DB::table('work_order')
                    ->where('wor_id', $find_recede->rec_ord_id)
                    ->select('wor_order_id', 'wor_order_number')
                    ->first();
                $oure_res = OutinRecord::addition(
                    $user_info, //用户信息
                    $find_order->wor_order_id, //原始单的关联id
                    $find_order->wor_order_number, //原始单的关联单号
                    1, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
                    $find_recede->rec_type, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                    $find_recede->recl_client_id, //选择的客户id,会员id/单位id
                    $find_recede->rec_number, //原始单号
                    0, //入库仓库id
                    $find_recede->rec_mobile_ware_id, //出库仓库id
                    $goo_all_amount, //出库的商品总量
                    14, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
                    2, //操作类型：1锁定库存2出库3入库4调货5发货
                    $find_ware->waon_stock_fine_amount, //良品总库存
                    $find_ware->waon_lock_fine_amount, //良品锁定数量
                    $find_ware->waon_stock_priority_amount, //优先总库存
                    $find_ware->waon_lock_priority_amount, //优先锁定数量
                    $find_ware->waon_stock_unchecked_amount, //待检测总库存
                    1, //出入库类型：1出库，2入库
                    $waon_class_key, //数组，出库类型1良品2优先
                    $oure_goods_id, //数组，商品id
                    $oure_goods_quantity, //数组，商品数量
                    $oure_goods_inventory //数组，出库类型1良品2优先
                );
                // 库存锁定-出入库记录
                $oslr_res = OutinStockLock::addition(
                    $user_info, //用户信息
                    $find_order->wor_order_id, //原始单的关联id
                    $find_order->wor_order_number, //原始单的关联单号
                    1, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
                    $find_recede->rec_type, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                    $find_recede->recl_client_id, //选择的客户id,会员id/单位id
                    $find_recede->rec_number, //原始单号
                    $find_recede->rec_mobile_ware_id, //出库/入库的仓库id
                    $goo_all_amount, //出库/入库总数量
                    14, //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单
                    $find_ware->waon_stock_fine_amount, //良品总库存
                    $find_ware->waon_lock_fine_amount, //良品锁定数量
                    $find_ware->waon_stock_priority_amount, //优先总库存
                    $find_ware->waon_lock_priority_amount, //优先锁定数量
                    $find_ware->waon_stock_unchecked_amount, //待检测总库存
                    1, //出入库类型：1出库，2入库
                    $osld_goo_data
                );
                unset($osld_goo_data);
            }
        }

        if ($wago_res && $waon_priority_res && $waon_fine_res) {
            return ['code'=>200, 'msg'=>'error', 'data'=>'移动仓库库存减少成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'退换回收：失败5'];
        }
    }

    /**
     * [exchangeReduceStock 减少技师库的库存数量（暂时用不到）]
     * @param  [type] $user_info   [用户信息]
     * @param  [type] $find_recede [退换回收信息数据]
     * @param  [type] $request     [提交的数据]
     * @return [type]              [description]
     */
    private function exchangeReduceStock(
        $user_info,
        $find_recede,
        $request
    ) {
        //查询当前工单id商品的换回数量
        $find_work_goods = DB::table('work_good')
            ->where('wogo_wor_id', $find_recede->rec_ord_id)
            ->where('wogo_state', 4)
            ->get(['wogo_goo_id', 'wogo_waon_class', 'wogo_goo_inventory', 'wogo_goo_amount'])
            ->toArray();
        foreach ($find_work_goods as $key => $value) {
            if (isset($wago_class_goods[$value->wogo_goo_inventory][$value->wogo_waon_class][$value->wogo_goo_id])) {
                $wago_class_goods[$value->wogo_goo_inventory][$value->wogo_waon_class][$value->wogo_goo_id]['wogo_goo_amount'] += $value['wogo_goo_amount'];
            } else {
                $wago_class_goods[$value->wogo_goo_inventory][$value->wogo_waon_class][$value->wogo_goo_id] = (array)$value;
            }
        }
        $wogo_goo_id = array_column($find_work_goods, 'wogo_goo_id');
        $wogo_waon_class = array_unique(array_column($find_work_goods, 'wogo_waon_class'));
        // 查询服务技师
        $service_adm_id = DB::table('work_order')
            ->where('wor_id', $find_recede->rec_ord_id)
            ->value('wor_service_adm_id');
        $adm_ware_id = DB::table('warehouse')
            ->where('ware_type', 2)
            ->where('ware_leader_id', $service_adm_id)
            ->value('ware_id');
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $adm_ware_id)
            ->whereIn('wago_class', $wogo_waon_class)
            ->whereIn('wago_goo_id', $wogo_goo_id)
            ->get(['wago_id', 'wago_class', 'wago_stock_number', 'wago_priority_stock_number', 'wago_goo_id'])
            ->toArray();
        if (empty($warehouse_goods)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'退换回收：失败6'];
        }
        foreach ($warehouse_goods as $key => $value) {
            $warehouse_class_goods[$value->wago_class][$value->wago_goo_id] = (array)$value;
        }
        $sql = 'UPDATE `faster_warehouse_goods` SET ';
        $lock_quantity_sql = '';
        $priority_lock_quantity_sql = '';
        $time_sql = '';
        $ids = '';
        $waon_class_fine_quantity = []; //仓库类别对应良品库存总数量
        $waon_class_priority_quantity = []; //仓库类别对应优先库存总数量
        // 技师库要出库的商品
        foreach ($wago_class_goods as $goo_inventory => $new_wago_class_goods) {
            foreach ($new_wago_class_goods as $waon_class => $class_goods_data) {
                foreach ($class_goods_data as $goo_id => $value) {
                    // 商品出库类型，良品出库
                    if ($value['wogo_goo_inventory'] == 1) {
                        // 良品剩余库存数量
                        $surplus_quantity = $warehouse_class_goods[$waon_class][$goo_id]['wago_stock_number'] - $value['wogo_goo_amount'];
                        if ($surplus_quantity < 0) {
                            return ['code'=>500, 'msg'=>'error', 'data'=>'技师库内商品数量不足1'];
                        }
                        // 更改良品库存数量
                        $lock_quantity_sql = $lock_quantity_sql . ' WHEN ' . $warehouse_class_goods[$waon_class][$goo_id]['wago_id'] . ' THEN `wago_stock_number` - ' . $value['wogo_goo_amount'];

                        if (isset($waon_class_fine_quantity[$waon_class])) {
                            $waon_class_fine_quantity[$waon_class] += $value['wogo_goo_amount']; //仓库类别对应良品库存总数量
                        } else {
                            $waon_class_fine_quantity[$waon_class] = $value['wogo_goo_amount']; //仓库类别对应良品库存总数量
                        }
                        // 商品出库类型，优先出库
                    } else {
                        // 优先剩余库存数量
                        $surplus_quantity = $warehouse_class_goods[$waon_class][$goo_id]['wago_priority_stock_number'] - $value['wogo_goo_amount'];
                        if ($surplus_quantity < 0) {
                            return ['code'=>500, 'msg'=>'error', 'data'=>'技师库内商品数量不足2'];
                        }
                        // 更改优先库存数量
                        $priority_lock_quantity_sql = $priority_lock_quantity_sql . ' WHEN ' . $warehouse_class_goods[$waon_class][$goo_id]['wago_id'] . ' THEN `wago_priority_stock_number` - ' . $value['wogo_goo_amount'];

                        if (isset($waon_class_priority_quantity[$waon_class])) {
                            $waon_class_priority_quantity[$waon_class] += $value['wogo_goo_amount']; //仓库类别对应优先库存总数量
                        } else {
                            $waon_class_priority_quantity[$waon_class] = $value['wogo_goo_amount']; //仓库类别对应优先库存总数量
                        }
                    }

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

        // 2.1 技师库商品表减锁定库存
        $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $lock_quantity_sql . ' END,';
        $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $priority_lock_quantity_sql . ' END,';
        $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $time_sql . ' END'; //修改时间
        $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
        $wago_res = DB::update($sql);

        // 查询仓库总数量仓库的类别对应的id
        $find_waon_data = DB::table('warehouse_onhand')
            ->where('waon_ware_id', '=', $adm_ware_id)
            ->whereIn('waon_class', $wogo_waon_class)
            ->pluck('waon_id', 'waon_class')->toArray();
        // 良品库存总数量更改
        if ($waon_class_fine_quantity) {
            $sql = 'UPDATE `faster_warehouse_onhand` SET ';
            $lock_fine_sql = '';
            $all_amount_sql = '';
            $time_sql = '';
            $ids = '';
            foreach ($waon_class_fine_quantity as $key => $value) {
                // 查询库存数量
                $stock_fine_amount = DB::table('warehouse_onhand')
                    ->where('waon_id', $find_waon_data[$key])
                    ->value('waon_stock_fine_amount');
                if ($stock_fine_amount - $value < 0) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'当前库存数量不足'];
                }
                $lock_fine_sql = $lock_fine_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_stock_fine_amount` - ' . $value;
                $all_amount_sql = $all_amount_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_all_amount` - ' . $value;
                $time_sql = $time_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $find_waon_data[$key] . ',';
            }
            $sql = $sql . ' `waon_stock_fine_amount`=  CASE `waon_id` ' . $lock_fine_sql . ' END,';
            $sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $all_amount_sql . ' END,';
            $sql = $sql . ' `waon_update_time`=  CASE `waon_id` ' . $time_sql . ' END';
            $sql = $sql . ' WHERE `waon_id` IN (' . trim($ids, ',') . ')';
            $waon_fine_res = DB::update($sql);
        } else {
            $waon_fine_res = true;
        }

        // 优先库存总数量更改
        if ($waon_class_priority_quantity) {
            $sql = 'UPDATE `faster_warehouse_onhand` SET ';
            $lock_fine_sql = '';
            $all_amount_sql = '';
            $time_sql = '';
            $ids = '';
            foreach ($waon_class_priority_quantity as $key => $value) {
                // 查询库存数量
                $stock_priority_amount = DB::table('warehouse_onhand')
                    ->where('waon_id', $find_waon_data[$key])
                    ->value('waon_stock_priority_amount');
                if ($stock_priority_amount - $value < 0) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'当前库存数量不足'];
                }
                $lock_fine_sql = $lock_fine_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_stock_priority_amount` - ' . $value;
                $all_amount_sql = $all_amount_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_all_amount` - ' . $value;
                $time_sql = $time_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $find_waon_data[$key] . ',';
            }
            $sql = $sql . ' `waon_stock_priority_amount`=  CASE `waon_id` ' . $lock_fine_sql . ' END,';
            $sql = $sql . ' `waon_all_amount`=  CASE `waon_id` ' . $all_amount_sql . ' END,';
            $sql = $sql . ' `waon_update_time`=  CASE `waon_id` ' . $time_sql . ' END';
            $sql = $sql . ' WHERE `waon_id` IN (' . trim($ids, ',') . ')';
            $waon_priority_res = DB::update($sql);
        } else {
            $waon_priority_res = true;
        }

        // 遍历仓库类型数据，处理固定仓库对应仓库类型的出入库记录
        foreach ($wago_class_goods as $goo_inventory => $new_wago_class_goods) {
            foreach ($new_wago_class_goods as $waon_class_key => $class_goods_data) {
                // 进销存，固定仓库，进销存库存数量减少
                // 查询仓库类别的进销存计算方式
                $goo_all_amount = 0;
                foreach ($class_goods_data as $goo_id_key => $value) {
                    // 出入库记录需要的的商品数组
                    $oure_goods_data[$goo_id_key]['goo_quantity'] = $value['wogo_goo_amount']; //出入库商品数量
                    $oure_goods_data[$goo_id_key]['goo_inventory'] = $value['wogo_goo_inventory']; //出入库商品类型，类型1良品2优先
                    $goo_all_amount += $value['wogo_goo_amount'];

                    // 出入库记录需要
                    $oure_goods_id[$goo_id_key] = $value['wogo_goo_id']; //出入库商品id
                    $oure_goods_quantity[$goo_id_key] = $value['wogo_goo_amount']; //出入库商品数量
                    $oure_goods_inventory[$goo_id_key] = $value['wogo_goo_inventory']; //出入库商品类型，类型1良品2优先
                }

                $find_ware = DB::table('warehouse_onhand')
                    ->where('waon_ware_id', '=', $adm_ware_id)
                    ->where('waon_class', $waon_class_key)
                    ->select('waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_unchecked_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount')
                    ->first();
                // 新增一条入库记录
                // 根据原始单id,查询到订单id
                $find_order = DB::table('work_order')
                    ->where('wor_id', $find_recede->rec_ord_id)
                    ->select('wor_order_id', 'wor_order_number')
                    ->first();
                $oure_res = OutinRecord::addition(
                    $user_info, //用户信息
                    $find_order->wor_order_id, //原始单的关联id
                    $find_order->wor_order_number, //原始单的关联单号
                    1, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
                    $find_recede->rec_type, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                    $find_recede->recl_client_id, //选择的客户id,会员id/单位id
                    $find_recede->rec_number, //原始单号
                    0, //入库仓库id
                    $adm_ware_id, //出库仓库id
                    $goo_all_amount, //出库的商品总量
                    11, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
                    2, //操作类型：1锁定库存2出库3入库4调货5发货
                    $find_ware->waon_stock_fine_amount, //良品总库存
                    $find_ware->waon_lock_fine_amount, //良品锁定数量
                    $find_ware->waon_stock_priority_amount, //优先总库存
                    $find_ware->waon_lock_priority_amount, //优先锁定数量
                    $find_ware->waon_stock_unchecked_amount, //待检测总库存
                    1, //出入库类型：1出库，2入库
                    $waon_class_key, //数组，出库类型1良品2优先
                    $oure_goods_id, //数组，商品id
                    $oure_goods_quantity, //数组，商品数量
                    $oure_goods_inventory //数组，出库类型1良品2优先
                );
            }
        }

        if ($wago_res && $waon_priority_res && $waon_fine_res) {
            return ['code'=>200, 'msg'=>'error', 'data'=>'技师库库存减少成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'退换回收：失败7'];
        }
    }

    // 详情
    public function details(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyRecedeRecycleController;
        $error_message = $verify_data->detailsValidator($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_recede = DB::table('recede_recycle as re')
            ->leftjoin('admin as a', 'a.adm_id', '=', 're.rec_create_adm_id')
            ->where('rec_id', $request['rec_id'])
            ->first(['rec_number', 'rec_ord_order_number', 'rec_create_time', 'rec_state', 'rec_amount', 'rec_remark', 'rec_date', 'rec_price', 'rec_ware_id', 'adm_name as rec_create_adm_name', 'rec_type']);

        if (empty($find_recede)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前回收单不存在']);
        }

        // 查询出客户单位名称 客户姓名 联系电话
        $client = DB::table('recede_client')
            ->where('recl_rec_id', $request['rec_id'])
            ->first(['recl_channel_unit', 'recl_name', 'recl_phone', 'recl_client_id']);
        if ($find_recede->rec_type == 1) {
            $find_recede->recl_channel_unit = DB::table('member')
                ->where('mem_id', $client->recl_client_id)
                ->value('mem_name as chun_unit_name');
        } else {
            $find_recede->recl_channel_unit = DB::table('channel_unit')
                ->where('chun_id', $client->recl_client_id)
                ->value('chun_unit_name');
        }
        unset($client->recl_client_id);
        $find_recede->recl_name = $client->recl_name;
        $find_recede->recl_phone = $client->recl_phone;
        // 查询出仓库名称
        $find_recede->ware_name = DB::table('warehouse')
            ->where('ware_id', $find_recede->rec_ware_id)
            ->value('ware_name');

        $find_goods = DB::table('recede_goods as rego')
            ->leftjoin('goods as goo', 'goo.goo_id', '=', 'rego.rego_goo_id')
            ->where('rego_rec_id', $request['rec_id'])
            ->select('rego_goo_id as goo_id', 'rego_goo_name as goo_name', 'rego_goo_goods_encode as goo_goods_encode', 'rego_goo_price as goo_price', 'rego_sell_number as goo_amount', 'rego_recycle_number as goo_recycle_amount', 'rego_fine_quantity', 'rego_priority_quantity', 'rego_unchecked_quantity', 'goo_type', 'goo_bra_name', 'goo_brse_id', 'goo_class', 'rego_wafr_id', 'rego_goo_inventory', 'rego_waon_class', 'rego_id', 'rego_goo_unit', 'rego_goo_unta_id', 'goo_unit_conversion')
            ->get()->toArray();
        // 查询系列数据
        $goo_brse_id = array_column($find_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        foreach ($find_goods as $key => $value) {
            $find_wfog_data = DB::table('warehouse_freight_outin_goods as w')
                ->leftJoin('warehouse_freight as wf', 'w.wfog_wafr_id', '=', 'wf.wafr_id')
                ->where('wfog_original_id', $request['rec_id'])
                ->where('wfog_outin_type', 2)
                ->where('wfog_primary_id', $value->rego_id)
                ->select('wfog_wafr_id', 'wfog_stock_amount as goo_recycle_amount', 'wafr_name as rego_wafr_name', 'wfog_stock_type as rego_goo_inventory')
                ->get()->toArray();
            $find_wfog_data = json_decode(json_encode($find_wfog_data, true), true);
            if ($find_wfog_data) {
                $find_goods[$key]->rego_wafr_data = $find_wfog_data;
            } else {
                $ware_name = DB::table('warehouse')
                    ->where('ware_id', $find_recede->rec_ware_id)
                    ->value('ware_name');
                $new_data['goo_recycle_amount'] = $value->goo_recycle_amount;
                $new_data['rego_goo_inventory'] = $value->rego_goo_inventory;
                $new_data['rego_wafr_name'] = $ware_name;
                $find_goods[$key]->rego_wafr_data[] = $new_data;
            }
            // // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
            // if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
            //     if (!empty($value->goo_brse_id)) {
            //         if ($value->goo_class == 2) {
            //             $find_goods[$key]->goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->goo_name;
            //         }
            //     }
            // }
            // // 显示品牌名称
            // if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
            //     if ($value->goo_class == 2) {
            //         $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $value->goo_name;
            //     } else {
            //         if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
            //             $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $value->goo_name;
            //         }
            //     }
            // }
            unset($find_goods[$key]->goo_brse_id);
            unset($find_goods[$key]->goo_class);
        }
        $data['goods_data'] = $find_goods;
        $data['recede_data'] = $find_recede;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

}
