<?php
namespace App\Http\Models\Services\WarehouseManage;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Models\Services\WarehouseLock;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Api\WarehouseManage\Stocktake;
use App\Http\Models\Services\Dispatch;
use App\Http\Models\Services\WarehouseManage\OutinStockLock;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\AccountingSettlement;
use App\Http\Models\Api\WorkOrder;

// 仓储系统 -- 销售出库单
class Sales extends Model
{
    // 销售单详情
    public static function info(
        $request,
        $user_info
    ) {
        // 销售出库单数据
        $sell_data = DB::table('sell as a')
            ->leftJoin('warehouse as ware', 'ware.ware_id', '=', 'a.sell_ware_id')
            ->leftJoin('sell_client as secl', 'secl.secl_sell_id', '=', 'a.sell_id')
            ->leftJoin('admin as ad', 'ad.adm_id', '=', 'sell_audit_adm_id')
            ->where('sell_id', $request['sell_id'])
            ->select('sell_id', 'sell_number', 'sell_state', 'sell_count', 'sell_adm_id', 'sell_price', 'sell_actual_price', 'sell_payment_way', 'sell_create_time', 'secl_channel_unit', 'secl_name', 'secl_phone', 'secl_address', 'ware_name', 'sell_data', 'sell_remark', 'sell_actual_count', 'secl_province', 'secl_city', 'secl_county', 'sell_waon_class', 'sell_chun_id', 'sell_system_type', 'sell_reject_reason', 'sell_moling', 'sell_audit_adm_id', 'adm_name as sell_audit_adm_name', 'sell_settlement_state')
            ->first();
        $sell_data = json_decode(json_encode($sell_data, true), true);
        if (empty($sell_data)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库单不存在！'];
        }
        if ($sell_data['sell_system_type'] == 1) { //系统类型1自营（门店提交）2系统
            $sell_data['secl_channel_unit'] = DB::table('shop')
                ->where('shop_id', $sell_data['sell_chun_id'])
                ->value('shop_store_name');
        } else {
            $sell_data['secl_channel_unit'] = DB::table('channel_unit')
                ->where('chun_id', $sell_data['sell_chun_id'])
                ->value('chun_unit_name');
        }

        // 获取销售商品数据
        $find_goods = DB::table('sell_goods as sego')
            ->leftJoin('goods as goo', 'sego.sego_goo_id', '=', 'goo.goo_id')
            ->where('sego_sell_id', $request['sell_id'])
            ->where('goo_delete', 1)
            ->where('goo_type', 1) //商品类型 1正常商品2赠品商品3活动商品4旧货商品
            ->select('sego_sell_number', 'sego_sell_price', 'sego_actual_number', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_id', 'goo_brse_id', 'goo_bra_name', 'goo_class')
            ->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_class);
            unset($find_goods[$key]->goo_brse_id);
        }
        // 查询账号id对应姓名
        $find_admin = DB::table('admin')
            ->where('adm_id', $sell_data['sell_adm_id'])
            ->select('adm_id', 'adm_name')
            ->first();
        $data['sell_data'] = $sell_data;
        $data['goods_data'] = $find_goods;
        $data['find_admin'] = $find_admin;
        if ($sell_data) {
            return ['code'=>200, 'msg'=>'success', 'data'=>$data];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'查无数据'];
        }
    }

    // 销售单审核
    public static function audit(
        $user_info,
        $request,
        $find_sell
    ) {
        if ($request['audit_type'] == 1) { //通过
            if (empty($request['ware_id'])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'请选择仓库'];
            }
            if (empty($request['goo_data'])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'商品不能为空'];
            }
            // 获取采购商品数据
            $find_goods = DB::table('sell_goods as a')
                ->leftJoin('goods as b', 'a.sego_goo_id', '=', 'b.goo_id')
                ->where('sego_sell_id', $request['sell_id'])
                ->where('goo_delete', 1)
                ->where('goo_type', 1) //商品类型 1正常商品2赠品商品3活动商品4旧货商品
                ->pluck('sego_sell_number', 'goo_id');
            $goods_data = json_decode($request['goo_data'], true);
            if (empty($goods_data)) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'出库商品不能为空！'];
            }
            $find_goods = json_decode(json_encode($find_goods, true), true);
            $neaten_goods_data = []; //整理后的仓库商品库存数据
            foreach ($goods_data as $key => $value) {
                if (!isset($find_goods[$value['goo_id']])) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'出库中没有此商品！'];
                } else {
                    if ($find_goods[$value['goo_id']] != $value['goo_quantity']) {
                        return ['code'=>500, 'msg'=>'error', 'data'=>'出库商品数量错误！'];
                    }
                }
                $wago_id = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $request['ware_id'])
                    ->where('wago_class', 1)
                    ->where('wago_goo_id', $value['goo_id'])
                    ->value('wago_id');
                if (empty($wago_id)) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'仓库中没有此商品'];
                }
                $value['goo_inventory'] = 1;
                $value['goo_waon_class'] = 1;
                if ($value['goo_inventory'] != 1) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'请选择良品出库'];
                }

                // [仓库商品id][出库类型：良品/优先]，用于判断仓库是否有库存
                if (isset($neaten_goods_data[$wago_id][$value['goo_inventory']])) {
                    $neaten_goods_data[$wago_id][$value['goo_inventory']]['goo_quantity'] += $value['goo_quantity'];
                } else {
                    $neaten_goods_data[$wago_id][$value['goo_inventory']] = $value;
                }
            }

            if (!empty($neaten_goods_data)) {
                $type = 3;
                $order_data['data']['ord_id'] = $request['sell_id'];
                $order_data['data']['ord_order_number'] = $find_sell->sell_number;
                $ware_lock_return = WarehouseLock::warehouseLockInventory(
                    $user_info,
                    $request,
                    $order_data,
                    $neaten_goods_data,
                    $type
                );
                if ($ware_lock_return['code'] == 500) {
                    return $ware_lock_return;
                }
                $neaten_wago_id = []; //良品商品
                $priority_neaten_wago_id = []; //优先商品
                $wagl_key = 0;
                $wagl_lock_quantity = []; //仓库锁定表的商品锁定数量
                foreach ($neaten_goods_data as $wago_id => $wago_id_value) {
                    foreach ($wago_id_value as $goo_inventory => $goo_value) {
                        if ($goo_inventory == 1) {
                            // 良品商品锁定库存
                            $ware_id[$wago_id] = $request['ware_id'];
                            $wago_goo_id[$wago_id] = $goo_value['goo_id'];
                            $wago_goo_quantity[$wago_id] = $goo_value['goo_quantity'];
                            $wago_goo_inventory[$wago_id] = $goo_inventory;
                            $wago_goo_class[$wago_id] = $goo_value['goo_waon_class'];
                            $neaten_wago_id[] = $wago_id;
                        } else {
                            // 优先商品锁定库存
                            $priority_ware_id[$wago_id] = $request['ware_id'];
                            $priority_wago_goo_id[$wago_id] = $goo_value['goo_id'];
                            $priority_wago_goo_quantity[$wago_id] = $goo_value['goo_quantity'];
                            $priority_wago_goo_inventory[$wago_id] = $goo_inventory;
                            $priority_wago_goo_class[$wago_id] = $goo_value['goo_waon_class'];
                            $priority_neaten_wago_id[] = $wago_id;
                        }
                        // 仓库锁定表的商品锁定数量：良品+优先 总的锁定数量
                        if (isset($wagl_lock_quantity[$wago_id])) {
                            $wagl_lock_quantity[$wago_id] += $goo_value['goo_quantity'];
                        } else {
                            $wagl_lock_quantity[$wago_id] = $goo_value['goo_quantity'];
                        }
                    }

                    // 仓库商品锁定表
                    $wagl_data[$wagl_key]['wagl_shop_id'] = $user_info->adm_shop_id;
                    $wagl_data[$wagl_key]['wagl_ware_id'] = $request['ware_id'];
                    $wagl_data[$wagl_key]['wagl_wago_id'] = $wago_id;
                    $wagl_data[$wagl_key]['wagl_original_id'] = $order_data['data']['ord_id'];
                    $wagl_data[$wagl_key]['wagl_original_number'] = $order_data['data']['ord_order_number'];
                    $wagl_data[$wagl_key]['wagl_original_correlation_id'] = $order_data['data']['ord_id']; //关联id：订单id/发货单id/调拨单id
                    $wagl_data[$wagl_key]['wagl_correlation_type'] = 4; //关联类型：1订单2发货单3调拨单4.销售单
                    $wagl_data[$wagl_key]['wagl_type'] = 3; //  原始单类型：1订单2调拨单3.销售单
                    $wagl_data[$wagl_key]['wagl_state'] = 1; //锁定状态：1下单锁定2出库解锁
                    $wagl_data[$wagl_key]['wagl_lock_quantity'] = $wagl_lock_quantity[$wago_id]; //商品锁定库存数量
                    $wagl_key++;
                }
                if (!empty($wagl_data)) {
                    $wagl_res = DB::table('warehouse_goods_lock')->insert($wagl_data);
                    if (!$wagl_res) {
                        return ['code'=>500, 'msg'=>'error', 'data'=>'审核销售单失败'];
                    }
                }
            }
            // 添加锁定记录
            $update_data['sell_state'] = 3; //状态1保存/待提交2提交/待审核3通过/待出库4驳回5出库（6部分出库7异常出库 暂时不用）
            $update_data['sell_ware_id'] = $request['ware_id']; //出库仓库id
            $update_puor_data['cg_state'] = 6; //采购单状态：1.审核中 2.财务审核 3.驳回编辑5.未入库 6.未出库 8.部分入库 11.完成
        } elseif ($request['audit_type'] == 2) { //驳回
            if (empty($request['sell_reject_reason'])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'请填写驳回原因'];
            }
            $update_data['sell_state'] = 4; //4驳回
            $update_data['sell_reject_reason'] = $request['sell_reject_reason']; //驳回原因
            $update_puor_data['cg_state'] = 3; //采购单状态：3.驳回编辑
            $update_puor_data['puor_reject_reason'] = $request['sell_reject_reason']; //采购单状态：3.驳回编辑
            $add_data = [
                'note_adm_cid' => $user_info->adm_cid,
                'note_shop_id' => $find_sell->sell_cg_shop_id,
                'note_number' => $find_sell->sell_cg_number,
                'note_adm_id' => $user_info->adm_id,
                'note_higher_adm_id' => $user_info->adm_id,
                'note_name' => 0,
                'note_content' => $request['sell_reject_reason'],
                'note_type' => '销售单驳回'
            ];
            $add_note_res = DB::table('note')->insert($add_data);
        }
        $update_data['sell_update_time'] = date("Y-m-d H:i:s"); //更新时间
        $update_data['sell_audit_adm_id'] = $user_info->adm_id; //审核人id
        $update_data['sell_audit_time'] = date("Y-m-d H:i:s"); //审核时间
        $update_sell_res = DB::table('sell')
            ->where('sell_id', $request['sell_id'])
            ->where('sell_state', '!=', 4)
            ->update($update_data);
        $update_puor_data['auditor_user'] = $user_info->adm_id; //审核人id
        $update_puor_data['edit_time'] = date("Y-m-d H:i:s"); //更新时间
        $update_puor_res = DB::table('purchase_order')
            ->where('cg_id', $find_sell->sell_cg_id)
            ->update($update_puor_data);
        if ($update_puor_res && $update_sell_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'审核销售单成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'审核销售单失败'];
        }
    }

    /**
     * [outStorage 出库操作，部分出库、出库、原单出库的共有代码]
     * @param  [type] $request   [出库提交的数据]
     * @param  [type] $user_info [用户信息]
     * @param  [type] $find_sell [销售出库单信息]
     * @param  [type] $type      [出库类型：1部分出库2出库3原单出库]
     * @return [type]            [数组，返回出库结果]
     */
    public static function outStorage(
        $request,
        $user_info,
        $find_sell,
        $type
    ) {
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        // 新增销售出库记录表【21.07.01】
        $sere_data['sere_cid'] = $user_info->adm_cid;//公司id
        $sere_data['sere_superior_shop_id'] = $shop_id;//总店id
        $sere_data['sere_shop_id'] = $user_info->adm_shop_id;//门店id
        $sere_data['sere_number'] = 'XSCH' . date('mdHis') . rand(100000, 999999);//销售出库单单号
        $sere_data['sere_sell_id'] = $request['sell_id'];//销售单id
        $sere_data['sere_sell_number'] = $find_sell->sell_number;//销售单单号
        $sere_data['sere_ware_id'] = $find_sell->sell_ware_id;//销售出库仓库id
        $sere_data['sere_waon_class'] = $find_sell->sell_waon_class;//仓库类别：1货物仓2非货物仓3旧货仓4临时仓
        $sere_data['sere_create_name'] = $user_info->adm_name;//出库人名称
        $sere_data['sere_create_id'] = $user_info->adm_id;//出库人id
        $sere_data['sere_remark'] = $request['sell_remark']?:'';//出库备注
        $sere_data['sere_type'] = 1;//出库金额
        $sere_id = DB::table('sell_record')->insertGetId($sere_data);
        // 原单出库
        if ($type == 3) {
            // 查询销售出库的商品数据
            $find_sego_goods = DB::table('sell_goods')
                ->where('sego_sell_id', $request['sell_id'])
                ->select('sego_id', 'sego_goo_id', 'sego_sell_price', 'sego_sell_number', 'sego_actual_number')
                ->get()->toArray();
            // 对前端提交的出库商品数组重新排序,方便与下面查询仓位商品数据匹配
            // 首先按照仓库商品id排序
            if (empty($request['goo_data'])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'请选择出库商品！'];
            }
            $request_goods_data = json_decode($request['goo_data'], true); //前端提交的出库商品数据
            $request_goo_wago_id = array_column($request_goods_data, 'goo_wago_id');
            $sego_goo_id = array_column($find_sego_goods, 'sego_goo_id');
            $sego_goods_id = array_column($find_sego_goods, null, 'sego_goo_id');
            array_multisort($request_goods_data, SORT_ASC, $request_goo_wago_id);
            // 其次按照商品数量排序
            $request_goo_quantity = array_column($request_goods_data, 'goo_quantity');
            array_multisort($request_goods_data, SORT_ASC, $request_goo_quantity);

            // 查询仓位商品锁定表
            $find_wfgl_goods = DB::table('warehouse_freight_goods_lock')
                ->where('wfgl_shop_id', $user_info->adm_shop_id)
                ->where('wfgl_type', 3) //原始单类型：1订单2调拨单3.销售单
                ->where('wfgl_state', 1) //锁定状态：1下单锁定2出库解锁
                ->where('wfgl_original_id', $find_sell->sell_id)
                ->where('wfgl_original_number', $find_sell->sell_number)
                ->select('wfgl_id', 'wfgl_ware_id', 'wfgl_wago_id', 'wfgl_wafr_id', 'wfgl_wafg_id', 'wfgl_lock_quantity', 'wfgl_lock_type')
                ->orderby('wfgl_wago_id', 'asc')
                ->orderby('wfgl_lock_quantity', 'asc')
                ->get()->toArray();
            $goods_change_sate = false; //商品变化状态
            $request_goo_amount = 0; //提交商品出库总数量
            $goo_all_fine = 0; //总的良品出库商品数量
            $goo_all_priority = 0; //总的优先出库商品数量
            $neaten_goods_data = []; //仓库商品数据
            $neaten_wago_id = []; //仓库商品id
            $freight_goods_data = []; //仓位商品数据

            $wfgl_lock_key = 0; //仓位商品锁定数组键值
            $wagl_key = 0; //仓库商品锁定数组键值
            $orgf_wfgl_key = 0; //订单商品仓位数组键值
            $wagl_wago_id = [];
            $wagl_data = [];
            // 判断提交的商品出库数据是否更改
            $sere_amount = 0;//出库总金额
            foreach ($request_goods_data as $key => $value) {
                $request_goo_amount += $value['goo_quantity'];
                if (!empty($find_wfgl_goods)) {
                    // 仓位id
                    if (isset($find_wfgl_goods[$key])) {
                        // 仓库商品id
                        if ($value['goo_wago_id'] != $find_wfgl_goods[$key]->wfgl_wago_id) {
                            $goods_change_sate = true;
                        }
                        // 出库类型1良品2优先
                        if ($value['goo_inventory'] != $find_wfgl_goods[$key]->wfgl_lock_type) {
                            $goods_change_sate = true;
                        }
                        // 出库数量
                        if ($value['goo_quantity'] != $find_wfgl_goods[$key]->wfgl_lock_quantity) {
                            $goods_change_sate = true;
                        }
                        // 出库仓位
                        if ($value['goo_wafr_id'] != $find_wfgl_goods[$key]->wfgl_wafr_id) {
                            $goods_change_sate = true;
                        }
                    } else {
                        $goods_change_sate = true;
                    }
                } else {
                    $goods_change_sate = true;
                }

                // 有仓位id的相关库存数据，处理仓位商品表的库存锁定数量
                if (!empty($value['goo_wafr_id'])) {
                    // [仓位id][仓库商品id][出库类型：良品/优先]，用于判断仓位是否有库存
                    if (isset($freight_goods_data[$value['goo_wafr_id']][$value['goo_wago_id']][$value['goo_inventory']])) {
                        $freight_goods_data[$value['goo_wafr_id']][$value['goo_wago_id']][$value['goo_inventory']]['goo_quantity'] += $value['goo_quantity'];
                    } else {
                        $freight_goods_data[$value['goo_wafr_id']][$value['goo_wago_id']][$value['goo_inventory']] = (array)$value;
                    }
                    $freight_wafr_id[] = $value['goo_wafr_id']; //仓位商品id
                }

                // 仓库商品表库存数据处理
                // [仓库商品id][出库类型：良品/优先]，用于判断仓库是否有库存
                if (isset($neaten_goods_data[$value['goo_wago_id']][$value['goo_inventory']])) {
                    // 判断是否有仓位id，如果有仓位id，说明从仓位出库，如果没有说明从仓库出库
                    if ($value['goo_wafr_id']) {
                        $neaten_goods_data[$value['goo_wago_id']][$value['goo_inventory']]['wafr_goo_quantity'] += $value['goo_quantity']; //从仓位商品出库的商品数量
                    } else {
                        $neaten_goods_data[$value['goo_wago_id']][$value['goo_inventory']]['wago_goo_quantity'] += $value['goo_quantity']; //从仓位商品出库的商品数量
                    }
                    $neaten_goods_data[$value['goo_wago_id']][$value['goo_inventory']]['goo_quantity'] += $value['goo_quantity'];
                    $new_neaten_goods_data[$value['goo_id']]['goo_quantity'] += $value['goo_quantity'];
                } else {
                    $temp_data = $value;
                    // 判断是否有仓位id，如果有仓位id，说明从仓位出库，如果没有说明从仓库出库
                    if ($value['goo_wafr_id']) {
                        $temp_data['wafr_goo_quantity'] = $value['goo_quantity']; //从仓位商品出库的商品数量
                        $temp_data['wago_goo_quantity'] = 0; //从仓库商品出库的商品数量
                    } else {
                        $temp_data['wafr_goo_quantity'] = 0; //从仓位商品出库的商品数量
                        $temp_data['wago_goo_quantity'] = $value['goo_quantity']; //从仓库商品出库的商品数量
                    }
                    $neaten_goods_data[$value['goo_wago_id']][$value['goo_inventory']] = $temp_data;
                    $new_neaten_goods_data[$value['goo_id']] = $temp_data;
                }
                $neaten_wago_id[] = $value['goo_wago_id']; //仓库商品id

                // goo_inventory 库存扣除方式1良品2优先
                if ($value['goo_inventory'] == 1) {
                    $goo_all_fine += $value['goo_quantity'];
                } else {
                    $goo_all_priority += $value['goo_quantity'];
                }
                $goo_id[] = $value['goo_id'];
                $goo_waon_class[] = $value['goo_waon_class'];

                if (isset($wago_class_goods[$value['goo_waon_class']][$value['goo_id']])) {
                    // 判断是否有仓位id，如果有仓位id，说明从仓位出库，如果没有说明从仓库出库
                    if ($value['goo_wafr_id']) {
                        $wago_class_goods[$value['goo_waon_class']][$value['goo_id']]['wafr_goo_quantity'] = $wago_class_goods[$value['goo_waon_class']][$value['goo_id']]['wafr_goo_quantity'] + $value['goo_quantity']; //仓库类型对应的商品，出入库记录
                    } else {
                        $wago_class_goods[$value['goo_waon_class']][$value['goo_id']]['wago_goo_quantity'] = $wago_class_goods[$value['goo_waon_class']][$value['goo_id']]['wago_goo_quantity'] + $value['goo_quantity']; //从仓库商品出库的商品数量
                    }
                    $wago_class_goods[$value['goo_waon_class']][$value['goo_id']]['goo_quantity'] = $wago_class_goods[$value['goo_waon_class']][$value['goo_id']]['goo_quantity'] + $value['goo_quantity']; //仓库类型对应的商品，出入库记录
                } else {
                    $temp_data = $value;
                    // 判断是否有仓位id，如果有仓位id，说明从仓位出库，如果没有说明从仓库出库
                    if ($value['goo_wafr_id']) {
                        $temp_data['wafr_goo_quantity'] = $value['goo_quantity']; //从仓位商品出库的商品数量
                        $temp_data['wago_goo_quantity'] = 0; //从仓库商品出库的商品数量
                    } else {
                        $temp_data['wafr_goo_quantity'] = 0; //从仓位商品出库的商品数量
                        $temp_data['wago_goo_quantity'] = $value['goo_quantity']; //从仓库商品出库的商品数量
                    }
                    $wago_class_goods[$value['goo_waon_class']][$value['goo_id']] = $temp_data; //仓库类型对应的商品，出入库记录
                    unset($temp_data);
                }
                // 仓位商品锁定表
                $wfgl_data[$wfgl_lock_key]['wfgl_shop_id'] = $user_info->adm_shop_id; //门店id
                $wfgl_data[$wfgl_lock_key]['wfgl_ware_id'] = $find_sell->sell_ware_id; //仓库id
                $wfgl_data[$wfgl_lock_key]['wfgl_waon_class'] = $value['goo_waon_class']; //仓库类别
                $wfgl_data[$wfgl_lock_key]['wfgl_wago_id'] = $value['goo_wago_id']; //仓库商品主键id
                $wfgl_data[$wfgl_lock_key]['wfgl_wafr_id'] = $value['goo_wafr_id']; //仓位id
                $wfgl_data[$wfgl_lock_key]['wfgl_wafg_id'] = 0; //仓位商品主键id
                $wfgl_data[$wfgl_lock_key]['wfgl_original_correlation_id'] = $find_sell->sell_id; //关联id：订单id/发货单id/调拨单id
                $wfgl_data[$wfgl_lock_key]['wfgl_correlation_type'] = 4; //关联类型：1订单2发货单3调拨单
                $wfgl_data[$wfgl_lock_key]['wfgl_original_id'] = $find_sell->sell_id; //原始id：订单id/调拨单id
                $wfgl_data[$wfgl_lock_key]['wfgl_original_number'] = $find_sell->sell_number; //原始单号：订单号/调拨单号
                $wfgl_data[$wfgl_lock_key]['wfgl_type'] = 3; //原始单类型：1订单2调拨单
                $wfgl_data[$wfgl_lock_key]['wfgl_state'] = 1; //锁定状态：1下单锁定2出库解锁
                $wfgl_data[$wfgl_lock_key]['wfgl_lock_quantity'] = $value['goo_quantity']; //商品锁定数量
                $wfgl_data[$wfgl_lock_key]['wfgl_lock_type'] = $value['goo_inventory']; //商品锁定类型：1良品2优先
                $wfgl_lock_key++;
                // 仓库商品锁定表数据
                if (in_array($value['goo_wago_id'], $wagl_wago_id)) {
                    $array_key = array_search($value['goo_wago_id'], $wagl_wago_id);
                    $wagl_data[$array_key]['wagl_lock_quantity'] += $value['goo_quantity']; //商品锁定库存数量
                } else {
                    // 仓库商品锁定表
                    $wagl_data[$wagl_key]['wagl_shop_id'] = $user_info->adm_shop_id;
                    $wagl_data[$wagl_key]['wagl_ware_id'] = $find_sell->sell_ware_id;
                    $wagl_data[$wagl_key]['wagl_wago_id'] = $value['goo_wago_id']; //仓库商品id
                    $wagl_data[$wagl_key]['wagl_original_id'] = $find_sell->sell_id;
                    $wagl_data[$wagl_key]['wagl_original_number'] = $find_sell->sell_number; //原始单号：订单号/调拨单号
                    $wagl_data[$wagl_key]['wagl_original_correlation_id'] = $find_sell->sell_id; //关联id：订单id/发货单id/调拨单id
                    $wagl_data[$wagl_key]['wagl_correlation_type'] = 4; //关联类型：1订单2发货单3调拨单4.销售单
                    $wagl_data[$wagl_key]['wagl_type'] = 3; //  原始单类型：1订单2调拨单3.销售单
                    $wagl_data[$wagl_key]['wagl_state'] = 1; //锁定状态：1下单锁定2出库解锁
                    $wagl_data[$wagl_key]['wagl_lock_quantity'] = $value['goo_quantity']; //商品锁定库存数量

                    $wagl_wago_id[$wagl_key] = $value['goo_wago_id']; //仓库商品id
                    $wagl_key++;
                }
                // 销售出库记录商品表【新增21.07.21】
                $serg_data['serg_shop_id'] = $user_info->adm_shop_id;//门店id
                $serg_data['serg_sell_id'] = $find_sell->sell_id;//销售出库单id
                $serg_data['serg_sere_id'] = $sere_id;//销售出库单记录id
                $serg_data['serg_ware_id'] = $find_sell->sell_ware_id;//仓库id
                $serg_data['serg_wafr_id'] = $value['goo_wafr_id'];//仓位id
                $serg_data['serg_waon_class'] = $value['goo_waon_class'];//仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                $serg_data['serg_goo_id'] = $value['goo_id'];//商品id
                $serg_data['serg_goo_price'] = $sego_goods_id[$value['goo_id']]->sego_sell_price;//商品金额（4位小数）
                $serg_data['serg_goo_quantity'] = $value['goo_quantity'];//商品数量
                $serg_id = DB::table('sell_record_goods')->insert($serg_data);
                $sere_amount = $sego_goods_id[$value['goo_id']]->sego_sell_price * $value['goo_quantity'];//出库总金额
                $sere_edit_data['sere_amount'] = $sere_amount;//出库总金额
                $sere_edit_data['sere_total_quantity'] = $request_goo_amount;//出库总数量
                $sere_edit_data['sere_update_time'] = date('Y-m-d H:i:s');
                $sere_edit_res = DB::table('sell_record')
                    ->where('sere_id', $sere_id)
                    ->update($sere_edit_data);
                if (!$sere_id || !$serg_id || !$sere_edit_res) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'出库失败'];
                }
            }
            // 提交的商品数据有变化，更改发货商品的锁定库存;提交的商品数据没有变化不需要更改锁定库存
            if ($goods_change_sate) {
                foreach ($new_neaten_goods_data as $goo_ids => $goo_value) {
                    foreach ($find_sego_goods as $key => $value) {
                        if ($goo_value['goo_id'] == $value->sego_goo_id) {
                            if ($goo_value['goo_quantity'] != $value->sego_sell_number) {
                                return ['code'=>500, 'msg'=>'error', 'data'=>'出库数量错误'];
                            }
                            $find_sego_goods[$key]->goo_wago_id = $goo_value['goo_wago_id'];
                        }
                        if (!in_array($value->sego_goo_id, $goo_id)) {
                            return ['code'=>500, 'msg'=>'error', 'data'=>'出库商品错误'];
                        }
                        $find_sego_goods[$key]->goo_inventory = $goo_value['goo_inventory'];
                        $find_sego_goods[$key]->goo_quantity = $value->sego_sell_number;
                    }
                    if (!in_array($goo_value['goo_id'], $sego_goo_id)) {
                        return ['code'=>500, 'msg'=>'error', 'data'=>'出库商品错误'];
                    }
                }

                // 把原来仓库锁定库存还回去
                $ware_type = 1;
                $type = 3; //单据类型1订单2调拨单3销售单
                $change_lock_return = Dispatch::shipmentsChangeLock(
                    $user_info, //用户信息
                    $find_sell, //销售数据
                    $ware_type, //出库仓库类型
                    $find_sell->sell_id, //销售单id
                    $find_sell->sell_number, //销售单单号
                    $find_sego_goods, //查询调拨单商品数据
                    $find_wfgl_goods, //查询仓位锁定数据
                    $type
                );
                if ($change_lock_return['code'] == 500) {
                    return $change_lock_return;
                }
                // 添加新的锁定库存记录
                $wfgl_res = DB::table('warehouse_freight_goods_lock')->insert($wfgl_data);
                unset($wfgl_data);
                $wagl_res = DB::table('warehouse_goods_lock')->insert($wagl_data);
                unset($wfgl_data);
                if (!$wagl_res || !$wfgl_res) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'销售出库失败'];
                }

                // 仓库库存数量调整
                if (!empty($neaten_goods_data)) {
                    // 2.选中的固定仓加锁定库存
                    $warehouse_goods = DB::table('warehouse_goods')
                        ->where('wago_ware_id', $find_sell->sell_ware_id)
                        ->whereIn('wago_id', $neaten_wago_id)
                        ->select('wago_id', 'wago_ware_id', 'wago_class', 'wago_goo_id', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_freight_stock_number', 'wago_freight_lock_quantity', 'wago_freight_priority_stock_number', 'wago_freight_priority_lock_quantity', 'wago_stock_amount', 'wago_lock_amount', 'wago_priority_stock_amount', 'wago_priority_lock_amount')
                        ->get()->toArray();
                    $warehouse_goods = array_column($warehouse_goods, null, 'wago_id');
                    foreach ($neaten_goods_data as $wago_id => $wago_value) {
                        foreach ($wago_value as $goo_inventory => $goo_value) {
                            if (isset($warehouse_goods[$wago_id])) {
                                // 良品库存
                                if ($goo_inventory == 1) {
                                    $surplus_quantity = $warehouse_goods[$wago_id]->wago_stock_number - $goo_value['goo_quantity']; //总的库存(仓库+仓位)
                                    $wago_quantity = $warehouse_goods[$wago_id]->wago_stock_amount - $goo_value['wago_goo_quantity']; //仓库库存
                                    $wafr_quantity = $warehouse_goods[$wago_id]->wago_freight_stock_number - $goo_value['wafr_goo_quantity']; //仓位库存

                                    $surplus_lock_quantity = $warehouse_goods[$wago_id]->wago_lock_quantity + $goo_value['goo_quantity']; //总锁定的库存(仓库+仓位)
                                    $wago_lock_quantity = $warehouse_goods[$wago_id]->wago_lock_amount + $goo_value['wago_goo_quantity']; //仓库锁定库存
                                    $wafr_lock_quantity = $warehouse_goods[$wago_id]->wago_freight_lock_quantity + $goo_value['wafr_goo_quantity']; //仓位锁定库存
                                    $wago_edit_data['wago_stock_number'] = $surplus_quantity;
                                    $wago_edit_data['wago_stock_amount'] = $wago_quantity;
                                    $wago_edit_data['wago_freight_stock_number'] = $wafr_quantity;
                                    $wago_edit_data['wago_lock_quantity'] = $surplus_lock_quantity;
                                    $wago_edit_data['wago_lock_amount'] = $wago_lock_quantity;
                                    $wago_edit_data['wago_freight_lock_quantity'] = $wafr_lock_quantity;

                                    if ($surplus_quantity < 0 || $wago_quantity < 0 || $wafr_quantity < 0) {
                                        return ['code'=>500, 'msg'=>'error', 'data'=>'商品库存锁定数量不足！01-1'];
                                    }
                                    $wago_edit_res = DB::table('warehouse_goods')
                                        ->where('wago_id', $wago_id)
                                        ->update($wago_edit_data);
                                    unset($wago_edit_data);
                                    if (!$wago_edit_res) {
                                        return ['code'=>500, 'msg'=>'error', 'data'=>'商品库存锁定数量不足！02'];
                                    }
                                    // 查询良品总库存数量
                                    $find_waon_data = DB::table('warehouse_onhand')
                                        ->where('waon_ware_id', $find_sell->sell_ware_id)
                                        ->where('waon_class', $warehouse_goods[$wago_id]->wago_class)
                                        ->select('waon_id', 'waon_stock_fine_amount', 'waon_lock_fine_amount')
                                        ->first();
                                    $waon_edit_data['waon_stock_fine_amount'] = $find_waon_data->waon_stock_fine_amount - $goo_value['goo_quantity'];
                                    if ($waon_edit_data['waon_stock_fine_amount'] < 0) {
                                        return ['code'=>500, 'msg'=>'error', 'data'=>'仓位锁定库存数量不足！L110'];
                                    }
                                    $waon_edit_data['waon_lock_fine_amount'] = $find_waon_data->waon_lock_fine_amount + $goo_value['goo_quantity'];
                                    // 调整仓库总的良品库存数量
                                    $waon_res = DB::table('warehouse_onhand')
                                        ->where('waon_id', $find_waon_data->waon_id)
                                        ->update($waon_edit_data);
                                } else { //优先库存
                                    $surplus_quantity = $warehouse_goods[$wago_id]->wago_priority_stock_number - $goo_value['goo_quantity']; //总的库存
                                    $wago_quantity = $warehouse_goods[$wago_id]->wago_priority_stock_amount - $goo_value['wago_goo_quantity']; //仓库库存
                                    $wafr_quantity = $warehouse_goods[$wago_id]->wago_freight_priority_stock_number - $goo_value['wafr_goo_quantity']; //仓位库存

                                    $surplus_priority_lock_quantity = $warehouse_goods[$wago_id]->wago_priority_lock_quantity + $goo_value['goo_quantity']; //总锁定的库存
                                    $wago_priority_lock_amount = $warehouse_goods[$wago_id]->wago_priority_lock_amount + $goo_value['wago_goo_quantity']; //仓库库存
                                    $wago_freight_priority_lock_quantity = $warehouse_goods[$wago_id]->wago_freight_priority_lock_quantity + $goo_value['wafr_goo_quantity']; //仓位库存

                                    $wago_edit_data['wago_priority_stock_number'] = $surplus_quantity; //总的库存(仓库+仓位)
                                    $wago_edit_data['wago_priority_stock_amount'] = $wago_quantity; //仓库库存
                                    $wago_edit_data['wago_freight_priority_stock_number'] = $wafr_quantity; //仓位库存
                                    //锁定库存
                                    $wago_edit_data['wago_priority_lock_quantity'] = $surplus_priority_lock_quantity; //总的库存(仓库+仓位)
                                    $wago_edit_data['wago_priority_lock_amount'] = $wago_priority_lock_amount; //仓库库存
                                    $wago_edit_data['wago_freight_priority_lock_quantity'] = $wago_freight_priority_lock_quantity; //仓位库存
                                    if ($surplus_quantity < 0 || $wago_quantity < 0 || $wafr_quantity < 0) {
                                        return ['code'=>500, 'msg'=>'error', 'data'=>'商品库存锁定数量不足！031'];
                                    }
                                    // 更改商品库存数量
                                    $wago_edit_res = DB::table('warehouse_goods')
                                        ->where('wago_id', $wago_id)
                                        ->update($wago_edit_data);
                                    unset($wago_edit_data);
                                    if (!$wago_edit_res) {
                                        return ['code'=>500, 'msg'=>'error', 'data'=>'商品库存锁定数量不足！041'];
                                    }
                                    // 查询优先总库存数量
                                    $find_waon_data = DB::table('warehouse_onhand')
                                        ->where('waon_ware_id', $find_sell->sell_ware_id)
                                        ->where('waon_class', $warehouse_goods[$wago_id]->wago_class)
                                        ->select('waon_id', 'waon_stock_priority_amount', 'waon_lock_priority_amount')
                                        ->first();
                                    $waon_edit_data['waon_stock_priority_amount'] = $find_waon_data->waon_stock_priority_amount - $goo_value['goo_quantity'];
                                    if ($waon_edit_data['waon_stock_priority_amount'] < 0) {
                                        return ['code'=>500, 'msg'=>'error', 'data'=>'仓位锁定库存数量不足！L120'];
                                    }
                                    $waon_edit_data['waon_lock_priority_amount'] = $find_waon_data->waon_lock_priority_amount + $goo_value['goo_quantity'];
                                    // 调整仓库总的优先库存数量
                                    $waon_res = DB::table('warehouse_onhand')
                                        ->where('waon_id', $find_waon_data->waon_id)
                                        ->update($waon_edit_data);
                                }
                            } else {
                                return ['code'=>500, 'msg'=>'error', 'data'=>'仓库商品锁定数量不足！'];
                            }
                        }
                    }
                }

                // 仓位锁定库存数量调整
                if (!empty($freight_goods_data)) {
                    $freight_wafr_id = array_unique($freight_wafr_id); //仓位id
                    // 2.选中的固定仓减锁定库存
                    $warehouse_freight_goods = DB::table('warehouse_freight_goods')
                        ->where('wafg_ware_id', $find_sell->sell_ware_id)
                        ->whereIn('wafg_wafr_id', $freight_wafr_id)
                        ->whereIn('wafg_wago_id', $neaten_wago_id)
                        ->select('wafg_id', 'wafg_wafr_id', 'wafg_wago_id', 'wafg_class', 'wafg_goo_id', 'wafg_stock_number', 'wafg_lock_quantity', 'wafg_priority_stock_number', 'wafg_priority_lock_quantity')
                        ->get()->toArray();
                    foreach ($warehouse_freight_goods as $key => $value) {
                        $warehouse_class_goods[$value->wafg_wafr_id][$value->wafg_wago_id] = (array)$value;
                    }
                    // 仓位商品表锁定数量处理
                    foreach ($freight_goods_data as $wafg_id => $wafg_value) {
                        foreach ($wafg_value as $wago_id => $wago_value) {
                            foreach ($wago_value as $goo_inventory => $goo_value) {
                                if (isset($warehouse_class_goods[$wafg_id][$wago_id])) {
                                    if ($goo_inventory == 1) { // 良品库存
                                        // 商品发货数据有更改的情况，已经把原来的锁定库存数量还回去了
                                        $surplus_quantity = $warehouse_class_goods[$wafg_id][$wago_id]['wafg_stock_number'] - $goo_value['goo_quantity'];
                                        $wafg_lock_quantity = $warehouse_class_goods[$wafg_id][$wago_id]['wafg_lock_quantity'] + $goo_value['goo_quantity'];
                                        $wafg_edit_data['wafg_stock_number'] = $surplus_quantity;
                                        $wafg_edit_data['wafg_lock_quantity'] = $wafg_lock_quantity;
                                        $wafr_decrement_field = 'wafr_all_stock'; //仓位表良品总数量字段

                                        if ($surplus_quantity < 0) {
                                            return ['code'=>500, 'msg'=>'error', 'data'=>'仓位商品锁定数量不足！11'];
                                        }
                                        // 仓位商品表锁定库存调整
                                        $wafg_edit_res = DB::table('warehouse_freight_goods')
                                            ->where('wafg_id', $warehouse_class_goods[$wafg_id][$wago_id]['wafg_id']) //仓位商品id
                                            ->update($wafg_edit_data);

                                        // 仓位表-仓位良品库存调整
                                        $wafr_unlock_res = DB::table('warehouse_freight')
                                            ->where('wafr_id', $warehouse_class_goods[$wafg_id][$wago_id]['wafg_wafr_id']) //仓位id
                                            ->where('wafr_ware_id', $find_sell->sell_ware_id)
                                            ->decrement($wafr_decrement_field, $goo_value['goo_quantity']);
                                        // 仓位表-仓位良品锁定库存调整
                                        $wafr_lock_res = DB::table('warehouse_freight')
                                            ->where('wafr_id', $warehouse_class_goods[$wafg_id][$wago_id]['wafg_wafr_id']) //仓位id
                                            ->where('wafr_ware_id', $find_sell->sell_ware_id)
                                            ->increment('wafr_lock_quantity', $goo_value['goo_quantity']);
                                        if (!$wafg_edit_res || !$wafr_lock_res || !$wafr_unlock_res) {
                                            return ['code'=>500, 'msg'=>'error', 'data'=>'仓位商品锁定数量不足！12'];
                                        }
                                    } else {
                                        // 优先库存
                                        // 商品发货数据有更改的情况
                                        $surplus_quantity = $warehouse_class_goods[$wafg_id][$wago_id]['wafg_priority_stock_number'] - $goo_value['goo_quantity'];
                                        $wafg_priority_lock_quantity = $warehouse_class_goods[$wafg_id][$wago_id]['wafg_priority_lock_quantity'] + $goo_value['goo_quantity'];
                                        $wafg_edit_data['wafg_priority_stock_number'] = $surplus_quantity;
                                        $wafg_edit_data['wafg_priority_lock_quantity'] = $wafg_priority_lock_quantity;
                                        $wafr_decrement_field = 'wafr_priority_all_stock'; //仓位表优先总数量字段
                                        if ($surplus_quantity < 0) {
                                            return ['code'=>500, 'msg'=>'error', 'data'=>'仓位商品锁定数量不足！13'];
                                        }
                                        // 更改仓位商品表商品库存数量
                                        $wafg_edit_res = DB::table('warehouse_freight_goods')
                                            ->where('wafg_id', $warehouse_class_goods[$wafg_id][$wago_id]['wafg_id'])
                                            ->update($wafg_edit_data);
                                        // 仓位良品库存调整
                                        $wafr_unlock_res = DB::table('warehouse_freight')
                                            ->where('wafr_id', $warehouse_class_goods[$wafg_id][$wago_id]['wafg_wafr_id'])
                                            ->where('wafr_ware_id', $find_sell->sell_ware_id)
                                            ->decrement($wafr_decrement_field, $goo_value['goo_quantity']);
                                        // 仓位良品锁定库存调整
                                        $wafr_lock_res = DB::table('warehouse_freight')
                                            ->where('wafr_id', $warehouse_class_goods[$wafg_id][$wago_id]['wafg_wafr_id'])
                                            ->where('wafr_ware_id', $find_sell->sell_ware_id)
                                            ->increment('wafr_priority_lock_quantity', $goo_value['goo_quantity']);
                                        if (!$wafg_edit_res || !$wafr_lock_res || !$wafr_unlock_res) {
                                            return ['code'=>500, 'msg'=>'error', 'data'=>'仓位商品锁定数量不足！13'];
                                        }
                                    }
                                    unset($wafg_edit_data);
                                    // 更新仓位商品锁定表的数据
                                    $res = DB::table('warehouse_freight_goods_lock')
                                        ->where('wfgl_shop_id', $user_info->adm_shop_id)
                                        ->where('wfgl_ware_id', $find_sell->sell_ware_id)
                                        ->where('wfgl_wago_id', $wago_id)
                                        ->where('wfgl_wafr_id', $warehouse_class_goods[$wafg_id][$wago_id]['wafg_wafr_id'])
                                        ->where('wfgl_original_number', $find_sell->sell_number)
                                        ->where('wfgl_original_id', $find_sell->sell_id)
                                        ->where('wfgl_type', 3)
                                        ->update(['wfgl_wafg_id' => $warehouse_class_goods[$wafg_id][$wago_id]['wafg_id']]);
                                } else {
                                    return ['code'=>500, 'msg'=>'error', 'data'=>'仓位商品锁定数量不足！10'];
                                }
                            }
                        }
                    }
                }
            }

            // 原单入库只提交销售出库单id，没有提交出库商品id、出库商品数量的数组
            $goo_data['goo_id'] = array_column($find_sego_goods, 'sego_goo_id');
            // 这里把销售出库单的商品id、出库数量赋值给这两个数组，下面的代码就可以执行了
            $request['sell_actual_count'] = array_column($find_sego_goods, 'sego_sell_number');
        } else { // 部分出库、出库
            // 查询销售出库的商品数据
            $find_sego_goods = DB::table('sell_goods')
                ->where('sego_sell_id', $request['sell_id'])
                ->whereIn('sego_goo_id', $goo_data['goo_id'])
                ->select('sego_id', 'sego_goo_id', 'sego_sell_price', 'sego_sell_number', 'sego_actual_number')
                ->get()->toArray();
        }
        if (count($find_sego_goods) != count($goo_data['goo_id'])) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'存在不是销售出库单的商品，无法出库！'];
        }
        $goods_price = array_column($find_sego_goods, 'sego_sell_price', 'sego_goo_id'); //商品id对应的销售金额

        $sell_actual_count = 0; //实际入库总数量
        $price_sum = 0; //本次实际入库金额
        $i = 0; //序号
        foreach ($goo_data['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || !is_numeric($request['sell_actual_count'][$key]) || $request['sell_actual_count'][$key] < 0) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误'];
            }
            $sell_actual_count += $request['sell_actual_count'][$key]; //实际出库总数量
            $price_sum += $request['sell_actual_count'][$key] * (isset($goods_price[$value]) ? $goods_price[$value] : 0); //实际出库总金额

            $goo_actual_count[$value] = $request['sell_actual_count'][$key]; //商品id对应的实际出库的数量
            $purchase_goo_actual_count[$value] = $request['sell_actual_count'][$key]; //进销存-商品id对应的实际出库的数量
            $purchase_goo_actual_price[$value] = $goods_price[$value] / 100; //进销存-商品id对应的实际出库的金额
            $goo_actual_id[] = $value;
            $i++;
        }

        $update_data['sell_actual_count'] = $find_sell->sell_actual_count + $sell_actual_count; //实际出库数量
        $update_data['sell_actual_price'] = $find_sell->sell_actual_price + $price_sum; //实际出库金额
        $update_data['sell_remark'] = isset($request['sell_remark']) ? $request['sell_remark'] : ''; //出库备注
        $update_data['sell_update_time'] = date('Y-m-d H:i:s');

        if ($type == 1) { //部分出库
            if ($update_data['sell_actual_count'] != $find_sell->sell_count) {
                $update_data['sell_state'] = 4; //状态1保存/待提交2提交/待审核3通过/待出库4驳回5出库（6部分出库7异常出库 暂时不用）
                $oure_type = 8; //出入库记录类型7.部分入库
            } else {
                $update_data['sell_state'] = 3;
                $oure_type = 2; //出入库记录类型1.入库单
            }
        } elseif ($type == 2) { //出库
            if ($update_data['sell_actual_count'] != $find_sell->sell_count) {
                $update_data['sell_state'] = 5; //状态1保存/待提交2提交/待出库3出库4部分出库5异常出库
                $oure_type = 8; //出入库记录类型7.部分入库
            } else {
                $update_data['sell_state'] = 3;
                $oure_type = 2; //出入库记录类型1.入库单
            }
        } elseif ($type == 3) { //原单出库
            $update_data['sell_state'] = 5; //状态1保存/待提交2提交/待审核3通过/待出库4驳回5出库（6部分出库7异常出库 暂时不用）
            $oure_type = 2; //出入库记录类型1.入库单
        }

        if (isset($request['sell_data'])) {
            $update_data['sell_data'] = json_encode($request['sell_data']);
        } else {
            $update_data['sell_data'] = '';
        }
        $sell_res = DB::table('sell')
            ->where('sell_id', $request['sell_id'])
            ->update($update_data);

        // 查询仓位商品锁定表
        $find_wfgl_data = DB::table('warehouse_freight_goods_lock as w')
            ->leftJoin('warehouse_goods as wg', 'w.wfgl_wago_id', '=', 'wg.wago_id')
            ->where('wfgl_shop_id', $user_info->adm_shop_id)
            ->where('wfgl_type', 3)
            ->where('wfgl_state', 1)
            ->where('wfgl_original_id', $request['sell_id'])
            ->where('wfgl_original_number', $find_sell->sell_number)
            ->select('wfgl_id', 'wfgl_ware_id', 'wfgl_wago_id', 'wfgl_wafr_id', 'wfgl_wafg_id', 'wfgl_lock_quantity', 'wfgl_lock_type', 'wfgl_waon_class', 'wago_goo_id')
            ->get()->toArray();
        if (empty($find_wfgl_data)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'出库失败01'];
        }
        $find_wfgl_data = json_decode(json_encode($find_wfgl_data, true), true);
        $wago_class_goods = []; //良品出入库记录
        $ware_type = 1; //固定仓
        foreach ($find_wfgl_data as $key => $value) { //出库数据
            if ($value['wfgl_wafr_id'] == 0) { //从仓库出
                // 仓库商品表良品锁定数量减少
                $find_wago_data = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $find_sell->sell_ware_id)
                    ->where('wago_class', $value['wfgl_waon_class'])
                    ->where('wago_id', $value['wfgl_wago_id'])
                    ->select('wago_id', 'wago_lock_quantity', 'wago_lock_amount')
                    ->first();
                $wago_lock_quantity = $find_wago_data->wago_lock_quantity - $value['wfgl_lock_quantity'];
                if ($wago_lock_quantity < 0) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'仓库商品表锁定数量不足1-1'];
                }
                if ($ware_type == 1) {
                    // 固定仓，处理固定仓库字段数据
                    $wago_lock_amount = $find_wago_data->wago_lock_amount - $value['wfgl_lock_quantity'];
                    if ($wago_lock_amount < 0) {
                        return ['code'=>500, 'msg'=>'error', 'data'=>'仓库商品表锁定数量不足1-2'];
                    }
                    $wago_out_edit['wago_lock_amount'] = $wago_lock_amount;
                }
                $wago_out_edit['wago_lock_quantity'] = $wago_lock_quantity;

                $wago_edit_res = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $find_sell->sell_ware_id)
                    ->where('wago_class', $value['wfgl_waon_class'])
                    ->where('wago_id', $value['wfgl_wago_id'])
                    ->update($wago_out_edit);
                unset($wago_out_edit);
                if (!$wago_edit_res) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'销售单出库：失败1'];
                }
            } else { //从仓位出
                // 仓库商品表良品锁定数量减少
                $find_wago_data = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $find_sell->sell_ware_id)
                    ->where('wago_class', $value['wfgl_waon_class'])
                    ->where('wago_id', $value['wfgl_wago_id'])
                    ->select('wago_id', 'wago_lock_quantity', 'wago_freight_lock_quantity')
                    ->first();
                $wago_lock_quantity = $find_wago_data->wago_lock_quantity - $value['wfgl_lock_quantity'];
                $wago_freight_lock_quantity = $find_wago_data->wago_freight_lock_quantity - $value['wfgl_lock_quantity'];
                if ($wago_freight_lock_quantity < 0 || $wago_lock_quantity < 0) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'仓库商品表锁定数量不足3'];
                }
                $wago_out_edit['wago_lock_quantity'] = $wago_lock_quantity;
                $wago_out_edit['wago_freight_lock_quantity'] = $wago_freight_lock_quantity;
                $wago_edit_res = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $find_sell->sell_ware_id)
                    ->where('wago_class', $value['wfgl_waon_class'])
                    ->where('wago_id', $value['wfgl_wago_id'])
                    ->update($wago_out_edit);
                unset($wago_out_edit);

                // 仓位商品表减少锁定库存
                $wafg_lock_quantity = DB::table('warehouse_freight_goods')
                    ->where('wafg_ware_id', $find_sell->sell_ware_id)
                    ->where('wafg_class', $value['wfgl_waon_class'])
                    ->where('wafg_wago_id', $value['wfgl_wago_id'])
                    ->where('wafg_wafr_id', $value['wfgl_wafr_id'])
                    ->value('wafg_lock_quantity');
                $wafg_lock_quantity = $wafg_lock_quantity - $value['wfgl_lock_quantity'];
                if ($wafg_lock_quantity < 0) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'仓位商品表锁定数量不足'];
                }
                $wafg_lock_quantity_res = DB::table('warehouse_freight_goods')
                    ->where('wafg_ware_id', $find_sell->sell_ware_id)
                    ->where('wafg_class', $value['wfgl_waon_class'])
                    ->where('wafg_wago_id', $value['wfgl_wago_id'])
                    ->where('wafg_wafr_id', $value['wfgl_wafr_id'])
                    ->decrement('wafg_lock_quantity', $value['wfgl_lock_quantity']);
                // 仓位表良品减少锁定库存
                $wafr_lock_quantity = DB::table('warehouse_freight')
                    ->where('wafr_id', $value['wfgl_wafr_id'])
                    ->where('wafr_ware_id', $find_sell->sell_ware_id)
                    ->value('wafr_lock_quantity');
                $wafr_lock_quantity = $wafr_lock_quantity - $value['wfgl_lock_quantity'];
                if ($wafr_lock_quantity < 0) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'仓位表锁定数量不足'];
                }
                $wafr_lock_quantity_res = DB::table('warehouse_freight')
                    ->where('wafr_id', $value['wfgl_wafr_id'])
                    ->where('wafr_ware_id', $find_sell->sell_ware_id)
                    ->decrement('wafr_lock_quantity', $value['wfgl_lock_quantity']);
                if (!$wago_edit_res || !$wafg_lock_quantity_res || !$wafr_lock_quantity_res) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'销售单出库：失败2'];
                }
            }

            // 仓库良品锁定总库存减少
            $find_waon_data = DB::table('warehouse_onhand')
                ->where('waon_ware_id', $find_sell->sell_ware_id)
                ->where('waon_class', $value['wfgl_waon_class'])
                ->select('waon_id', 'waon_lock_fine_amount', 'waon_all_amount')
                ->first();
            $waon_lock_fine_amount = $find_waon_data->waon_lock_fine_amount - $value['wfgl_lock_quantity'];
            $waon_all_amount = $find_waon_data->waon_all_amount - $value['wfgl_lock_quantity'];
            if ($waon_lock_fine_amount < 0 || $waon_all_amount < 0) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'总库存良品锁定数量不足'];
            }
            $waon_edit_data['waon_lock_fine_amount'] = $waon_lock_fine_amount;
            $waon_edit_data['waon_all_amount'] = $waon_all_amount;
            // 仓库总库存数量调整
            $waon_edit_res = DB::table('warehouse_onhand')
                ->where('waon_id', $find_waon_data->waon_id)
                ->update($waon_edit_data);
            if (!$waon_edit_res) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'总库存锁定数量不足'];
            }

            // 出入库记录数据处理
            if (isset($wago_class_goods[$value['wfgl_waon_class']][$value['wago_goo_id']])) {
                $wago_class_goods[$value['wfgl_waon_class']][$value['wago_goo_id']]['wfgl_lock_quantity'] = $wago_class_goods[$value['wfgl_waon_class']][$value['wago_goo_id']]['wfgl_lock_quantity'] + $value['wfgl_lock_quantity']; //仓库类型对应的商品，出入库记录
            } else {
                $wago_class_goods[$value['wfgl_waon_class']][$value['wago_goo_id']] = $value; //仓库类型对应的商品，出入库记录
                unset($temp_data);
            }

            $primary_id = DB::table('sell_goods')
                ->where('sego_sell_id', $request['sell_id'])
                ->where('sego_goo_id', $value['wago_goo_id'])
                ->value('sego_id');
            // 仓位出库记录
            $outin_recore_res = Stocktake::junkaddition(
                $user_info,
                $find_sell->sell_ware_id, //仓库id
                $value['wfgl_waon_class'], //仓库类型
                $value['wfgl_wafr_id'], //仓位id
                9, //销售单出库
                $request['sell_id'], //原始单id
                $find_sell->sell_number, //原始单单号
                $primary_id, //关联商品表主键id
                $value['wago_goo_id'], //商品表主键id
                1, //出入库类型：1出库2入库
                $value['wfgl_lock_quantity'], //商品数量
                $value['wfgl_lock_type'] //出库类型1良品2优先3待检测
            );
            if ($outin_recore_res['code'] == 500) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'销售单出库：失败4'];
            }
        }

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

                    // 出入库记录需要
                    $oure_goods_id[$goo_id_key] = $value['wago_goo_id']; //出入库商品id
                    $oure_goods_quantity[$goo_id_key] = $value['wfgl_lock_quantity']; //出入库商品数量
                    $oure_goods_inventory[$goo_id_key] = $value['wfgl_lock_type']; //出入库商品类型，类型1良品2优先
                    // 出入库记录需要商品数据
                    $req_goo_data[$i]['goo_waon_class'] = $waon_class_key; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                    $req_goo_data[$i]['goo_id'] = $goo_id_key;
                    $req_goo_data[$i]['goo_number'] = $value['wfgl_lock_quantity']; //商品数量
                    $req_goo_data[$i]['goo_out_in_type'] = 1; //出入库类型：1出库2入库3锁定4取消锁定
                    $req_goo_data[$i]['goo_inventory'] = $value['wfgl_lock_type']; //类型1良品2优先3待检测
                    $find_wago_data = DB::table('warehouse_goods')
                        ->where('wago_ware_id', $find_sell->sell_ware_id)
                        ->where('wago_class', $waon_class_key)
                        ->where('wago_id', $value['wfgl_wago_id'])
                        ->select('wago_id', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                        ->first();
                    if ($value['wfgl_lock_type'] == 1) { //出入库商品类型，类型1良品2优先
                        $req_goo_data[$i]['old_stock_number'] = $find_wago_data->wago_stock_number + $value['wfgl_lock_quantity']; //旧的商品良品库存数量
                        $req_goo_data[$i]['old_stock_lock_number'] = $find_wago_data->wago_lock_quantity + $value['wfgl_lock_quantity']; //旧的商品良品库存锁定数量
                        $req_goo_data[$i]['old_priority_number'] = $find_wago_data->wago_priority_stock_number; //旧的商品优先库存数量
                        $req_goo_data[$i]['old_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //旧的商品优先库存锁定数量
                        $req_goo_data[$i]['old_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量

                        $req_goo_data[$i]['new_stock_number'] = $find_wago_data->wago_stock_number; //新的商品良品库存数量
                        $req_goo_data[$i]['new_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
                        $req_goo_data[$i]['new_priority_number'] = $find_wago_data->wago_priority_stock_number; //新的商品优先库存数量
                        $req_goo_data[$i]['new_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
                        $req_goo_data[$i]['new_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
                    } elseif ($value['wfgl_lock_type'] == 2) {
                        $req_goo_data[$i]['old_stock_number'] = $find_wago_data->wago_stock_number; //旧的商品良品库存数量
                        $req_goo_data[$i]['old_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //旧的商品良品库存锁定数量
                        $req_goo_data[$i]['old_priority_number'] = $find_wago_data->wago_priority_stock_number + $value['wfgl_lock_quantity']; //旧的商品优先库存数量
                        $req_goo_data[$i]['old_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity + $value['wfgl_lock_quantity']; //旧的商品优先库存锁定数量
                        $req_goo_data[$i]['old_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量

                        $req_goo_data[$i]['new_stock_number'] = $find_wago_data->wago_stock_number; //新的商品良品库存数量
                        $req_goo_data[$i]['new_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
                        $req_goo_data[$i]['new_priority_number'] = $find_wago_data->wago_priority_stock_number; //新的商品优先库存数量
                        $req_goo_data[$i]['new_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
                        $req_goo_data[$i]['new_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
                    }
                    $req_goo_data[$i] = (object)$req_goo_data[$i];
                    $i++;
                }
                $find_waon = DB::table('warehouse_onhand')
                    ->where('waon_ware_id', '=', $find_sell->sell_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();
                $oure_goods_data = $oure_goods_dataarray[$waon_class_key];
                $oure_class_goo_id = array_keys($oure_goods_data);
                // 3.生成出库记录
                $oure_res = OutinRecord::addition(
                    $user_info, //用户信息
                    $find_sell->sell_id, //原始单的关联id
                    $find_sell->sell_number, //原始单的关联单号
                    9, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后8.盘库单9.销售出库单
                    5, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                    $find_sell->sell_chun_id, //选择的客户id,会员id/单位id
                    $find_sell->sell_number, //原始单号，销售单单号
                    0, //入库仓库id
                    $find_sell->sell_ware_id, //出库仓库id
                    $actual_count, //出库商品总量
                    16, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单...16销售出库单
                    2, //操作类型：1锁定库存2出库3入库4调货5发货
                    $find_waon->waon_stock_fine_amount, //良品总库存
                    $find_waon->waon_lock_fine_amount, //良品锁定数量
                    $find_waon->waon_stock_priority_amount, //优先总库存
                    $find_waon->waon_lock_priority_amount, //优先锁定数量
                    $find_waon->waon_stock_unchecked_amount, //待检测总库存
                    1, //出入库类型：1出库，2入库
                    1, //仓库类别
                    $oure_goods_id, //商品id
                    $oure_goods_quantity, //商品数量
                    $oure_goods_inventory, //出库类型1良品2优先
                    [], //仓位id
                    $oure_class_goo_id //仓库类别下的商品id
                );
                // 4.商品的出入库记录，记录商品库存、锁定数据
                $outin_res = OutinStockLock::addition(
                    $user_info, //用户信息
                    $find_sell->sell_id, //原始单的关联id
                    $find_sell->sell_number, //原始单的关联单号
                    9, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后8.盘库单9.销售出库单
                    5, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单5.运营中心与门店来往
                    $find_sell->sell_chun_id, //选择的客户id,会员id/单位id/门店id
                    $find_sell->sell_number, //原始单号，销售单单号
                    $find_sell->sell_ware_id, //出库/入库的仓库id
                    $actual_count, //出库商品总量
                    18, //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库18销售出库单
                    $find_waon->waon_stock_fine_amount, //良品总库存
                    $find_waon->waon_lock_fine_amount, //良品锁定数量
                    $find_waon->waon_stock_priority_amount, //优先总库存
                    $find_waon->waon_lock_priority_amount, //优先锁定数量
                    $find_waon->waon_stock_unchecked_amount, //待检测总库存
                    1, //出入库类型：1出库2入库3锁定4取消锁定
                    $req_goo_data //商品数组，商品数据
                );
                unset($req_goo_data);
                if (!$oure_res || !$outin_res) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'出库失败02'];
                }
            }
            unset($wago_class_goods);
            unset($oure_goods_dataarray);
            unset($oure_goods_id);
            unset($oure_goods_quantity);
            unset($oure_goods_inventory);
            unset($oure_class_goo_id);
        }

        // 4. 在仓库商品表增加对应的商品
        // 4.1.2 更新采购入库单商品的实际入库数量
        $sql = 'UPDATE `faster_sell_goods` SET ';
        $actual_number_sql = '';
        $update_time_sql = '';
        $ids = '';
        $actual_goo_id  = []; //实际入库的商品id
        $actual_goo_price  = []; //实际入库的商品价格
        foreach ($find_sego_goods as $key => $value) {
            if (in_array($value->sego_goo_id, $goo_actual_id)) {
                $actual_goo_id[] = $value->sego_goo_id; //盘点实际入库的商品id
                $actual_goo_price[$value->sego_goo_id] = $value->sego_sell_price; //盘点实际入库的商品价格

                // 商品实际入库数量
                // 更改商品库存数量
                $actual_number_sql = $actual_number_sql . ' WHEN ' . $value->sego_id;
                $actual_number_sql = $actual_number_sql . ' THEN ' . ($value->sego_actual_number + $goo_actual_count[$value->sego_goo_id]);
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value->sego_id;
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $value->sego_id . ',';
            }
        }

        $sql = $sql . ' `sego_actual_number`=  CASE `sego_id` ' . $actual_number_sql . ' END,';
        $sql = $sql . ' `sego_update_time`=  CASE `sego_id` ' . $update_time_sql . ' END';
        $sql = $sql . ' WHERE `sego_id` IN (' . trim($ids, ',') . ')';
        $sego_res = DB::update($sql);

        $chun_unit_name = DB::table('shop')
            ->where('shop_id', $find_sell->sell_cg_shop_id)
            ->value('shop_store_name');
        // 销售出库单 生成应收
        $sell_bill = ReceivableBill::create(
            $user_info, //用户信息
            7, // 类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单  7.销售出库单
            0, // 应收账款id
            $find_sell->sell_id, //原始id(销售出库单)
            $find_sell->sell_number, //应收账款单号/原始号(销售出库单)
            5, //客户类型：1.门店零售 2.来往单位
            $find_sell->sell_chun_id, //会员id/来往单位id
            $chun_unit_name, //来往单位名称
            $price_sum, //结算金额
            '', //结款时间
            '', //会计科目id
            0, //实际金额
            0, //抹零金额
            1,  //状态：1.未核销 2.已核销
            1,  //应收账单id是否是自己 1.不是 2.是
            '',  //备注
            0,  //已收金额
            '', //截止时间
            1, //金额正负1正   2负值
            9, //显示类型：1订单收款  9销售出库单
            2, //是否合并代收：1是2否
            $find_sell->sell_create_time,
            0 //技师是否收钱：0未选择1是2否
        );
        // 生成凭证单据
        // $vore_data = WorkOrder::voucherReceipts($user_info, $user_info->adm_shop_id, 4, 0, '', $find_sell->sell_id, $find_sell->sell_number, $price_sum, 0, 0, '', '1', 5, $find_sell->sell_chun_id, $chun_unit_name);
        if ($find_sell->sell_system_type == 1) {
            $cg_data = DB::table('purchase_order')
                ->where('cg_number', $find_sell->sell_cg_number)
                ->select('cg_id', 'cg_number', 'cg_wareid', 'cg_waon_class', 'cg_remark', 'cg_supplyunit', 'cg_shop_id', 'cg_superior_shop_id', 'cg_paymentype', 'cg_amount')
                ->first();
            $goods_data = DB::table('storage_goods')
                ->where('relation_number', $find_sell->sell_cg_number)
                ->select('goods_num', 'univalence', 'goods_id', 'goods_number', 'goods_name', 'goods_type', 'tax_rate', 'currency', 'company_unit')
                ->get()->toArray();
            $goods_data = json_decode(json_encode($goods_data, true), true);
            $putinstorage_res = Self::putInStorage($user_info, $cg_data, $goods_data);
        }
        if ($sell_res && $sego_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'出库成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'出库失败'];
        }
    }

    // 门店入库处理
    public static function putInStorage(
        $user_info,
        $cg_data,
        $goods_data
    ) {
        $allData = json_decode(json_encode($cg_data, true), true);
        $total_value = 0;
        foreach ($goods_data as $key => $val) {
            $total_value = $total_value + ((int)$val['goods_num'] * (float)$val['univalence']);
        }
        $new_shop_data = DB::table('shop')
            ->where('shop_id', $allData['cg_shop_id'])
            ->select('shop_cid', 'shop_superior_id')
            ->first();
        $new_user_info['adm_cid'] = $new_shop_data->shop_cid;
        $new_user_info['adm_shop_id'] = $allData['cg_shop_id'];
        $new_user_info['shop_superior_id'] = $new_shop_data->shop_superior_id;
        $new_user_info['adm_id'] = $user_info->adm_id;
        $new_user_info['adm_name'] = $user_info->adm_name;
        $new_user_info['adm_phone'] = $user_info->adm_phone;
        $new_user_info['shop_versions'] = 1;
        $new_user_infos = (object)$new_user_info;

        $now_time = date('Y-m-d H:i:s');
        $cw_amount = 0;
        $actual_count = 0;
        // 生成合同单号
        $rk_number = 'RK' . rand(10, 99) . date('mdHis') . rand(100000, 999999); //单号
        $i = 0;
        foreach ($goods_data as $key => $val) {
            // 入库
            $stgo_data = [];
            $stgo_data['company_id'] = $new_user_infos->adm_cid; //公司id
            $stgo_data['stgo_superior_shop_id'] = $new_user_infos->shop_superior_id; //所属总店id或加盟店id
            $stgo_data['stgo_shop_id'] = $new_user_infos->adm_shop_id; //门店id
            $stgo_data['goods_id'] = $val['goods_id']; //商品id
            $stgo_data['relation_number'] = $rk_number; //入库单号
            $stgo_data['goods_number'] = $val['goods_number']; //商品编号
            $stgo_data['goods_name'] = $val['goods_name']; //商品名称
            $goods_name = $val['goods_name'] . $val['goods_number']; //商品名称
            $stgo_data['storehouse'] = $allData['cg_wareid']; //仓库id
            $stgo_data['goods_num'] = (int) $val['goods_num']; //商品采购入库数量
            $stgo_data['cg_goodsnum'] = $stgo_data['goods_num']; //采购数量,因为退货会减去采购数量,所以就有这个字短
            $stgo_data['univalence'] = (float) $val['univalence']; //采购单价
            $stgo_data['ruku_num'] = $val['goods_num']; //入库数量
            $stgo_data['goods_type'] = $val['goods_type']; //商品类型1正常商品2赠送商品3活动商品4旧货商品
            $stgo_data['edit_time'] = $now_time; //到货时间
            $stgo_data['tax_rate'] = $val['tax_rate']; //税率
            $stgo_data['currency'] = $val['currency']; //币种
            $stgo_data['money'] = ((float)$val['univalence'] * (int)$val['goods_num']); //金额
            // 提前将每个商品的分算平均后的价格计算完毕；如果采购单价或采购总价为0 则赋值为0
            if ($allData['cg_amount'] <= '0' || $stgo_data['univalence'] <= '0') {
                $stgo_data['old_univalence'] = 0;
            } else {
                $stgo_data['old_univalence'] = round($allData['cg_amount'] / $total_value * $stgo_data['univalence'], 2);
            }
            $cw_amount = $cw_amount + ((float)$val['univalence'] * (int)$val['goods_num']); //应收总额
            $stgo_data['company_unit'] = empty($val['company_unit']) ? '' : $val['company_unit']; //计量单位
            $stgo_data['creator'] = $user_info->adm_name; //创建人
            $stgo_data['create_time'] = $now_time; //创建时间

            // 变更入库数量 和到货时间，并将库存加上去
            $res1 = DB::table('storage_goods')
                ->where('relation_number', $allData['cg_number'])
                ->where('goods_id', $val['goods_id'])
                ->increment('ruku_num', $val['goods_num'], ['edit_time' => $now_time]);
            $goo_actual_count[$val['goods_id']] = $val['goods_num']; //商品id对应的实际入库的数量
            $goo_actual_id[] = $val['goods_id'];

            // 出入库记录
            $oure_goods_data[$val['goods_id']]['goo_quantity'] = $val['goods_num']; //出入库商品数量
            $oure_goods_data[$val['goods_id']]['goo_inventory'] = 1; //出入库商品类型，类型1良品2优先，页面没有用到这个，暂定1

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

            $actual_count += $val['goods_num']; //实际入库总数量

            if (!$res1) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'更新入库数量失败'];
            }
            $ruku_goods[] = $stgo_data;
            $goods_id[] = $val['goods_id'];
            // 出入库记录需要商品数据
            $req_goo_data[$i]['goo_waon_class'] = 1; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
            $req_goo_data[$i]['goo_id'] = $val['goods_id'];
            $req_goo_data[$i]['goo_number'] = $val['goods_num']; //出入库商品数量
            $req_goo_data[$i]['goo_out_in_type'] = 2; //出入库类型：1出库2入库3锁定4取消锁定
            $req_goo_data[$i]['goo_inventory'] = 1; //类型1良品2优先3待检测 页面没有用到这个，暂定1
            $find_wago_data = DB::table('warehouse_goods')
                ->where('wago_ware_id', $allData['cg_wareid'])
                ->where('wago_class', $allData['cg_waon_class'])
                ->where('wago_goo_id', $val['goods_id'])
                ->select('wago_id', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                ->first();
            if (empty($find_wago_data)) {
                $req_goo_data[$i]['old_stock_number'] = 0; //旧的商品良品库存数量
                $req_goo_data[$i]['old_stock_lock_number'] = 0; //旧的商品良品库存锁定数量
                $req_goo_data[$i]['old_priority_number'] = 0; //旧的商品优先库存数量
                $req_goo_data[$i]['old_priority_lock_number'] = 0; //旧的商品优先库存锁定数量
                $req_goo_data[$i]['old_unchecked_number'] = 0; //旧的商品待检测库存数量

                $req_goo_data[$i]['new_stock_number'] = $val['goods_num']; //新的商品良品库存数量
                $req_goo_data[$i]['new_stock_lock_number'] = 0; //新的商品良品库存锁定数量
                $req_goo_data[$i]['new_priority_number'] = 0; //新的商品优先库存数量
                $req_goo_data[$i]['new_priority_lock_number'] = 0; //新的商品优先库存锁定数量
                $req_goo_data[$i]['new_unchecked_number'] = 0; //新的商品待检测库存数量
            } else {
                $req_goo_data[$i]['old_stock_number'] = $find_wago_data->wago_stock_number; //旧的商品良品库存数量
                $req_goo_data[$i]['old_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //旧的商品良品库存锁定数量
                $req_goo_data[$i]['old_priority_number'] = $find_wago_data->wago_priority_stock_number; //旧的商品优先库存数量
                $req_goo_data[$i]['old_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //旧的商品优先库存锁定数量
                $req_goo_data[$i]['old_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量

                $req_goo_data[$i]['new_stock_number'] = $find_wago_data->wago_stock_number + $val['goods_num']; //新的商品良品库存数量
                $req_goo_data[$i]['new_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
                $req_goo_data[$i]['new_priority_number'] = $find_wago_data->wago_priority_stock_number; //新的商品优先库存数量
                $req_goo_data[$i]['new_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
                $req_goo_data[$i]['new_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
            }
            $req_goo_data[$i] = (object)$req_goo_data[$i];
            $i++;
        }
        $add_storage_goods_res = Db::table('storage_goods')->insert($ruku_goods);
        // 入库单数组
        $ruku_data['rk_number'] = $rk_number; //单号
        $ruku_data['cg_number'] = $allData['cg_number']; //采购单号
        $ruku_data['rk_wareid'] = $allData['cg_wareid']; //仓库id
        $ruku_data['rk_waon_class'] = $allData['cg_waon_class']; //仓库类别
        $ruku_data['rk_state'] = 5; //入库单状态，1 待入库 3 待审核 4 驳回5 已完成8 作废
        $ruku_data['rk_type']  = 1; //入库单类型  1普通采购  2采购退货  3采购换货  4代发采购
        $ruku_data['rk_creator'] = $new_user_infos->adm_name;
        $ruku_data['create_time'] = $now_time;
        $ruku_data['company_id'] = $new_user_infos->adm_cid;
        $ruku_data['rk_userid'] = $new_user_infos->adm_id;
        $ruku_data['rk_inputid'] = $new_user_infos->adm_id;
        $ruku_data['rk_remarks'] = $allData['cg_remark'];
        $ruku_data['supplyunit'] = $allData['cg_supplyunit'];
        $ruku_data['arrival_time'] = $now_time;
        $ruku_data['rk_waretype'] = 1;
        $ruku_data['rk_amount'] = $cw_amount;
        $ruku_data['rk_superior_shop_id'] = $allData['cg_superior_shop_id'];
        $ruku_data['rk_shop_id'] = $allData['cg_shop_id'];

        $state = 1;
        $edit_cgdata['cg_state'] = 12; //12.确认完成
        $edit_cgdata['dh_time']  = $now_time;
        $edit_cgdata['edit_time'] = $now_time;

        // 添加入库单，添加商品表
        $ware_inorder_res = DB::table('ware_inorder')->insertGetId($ruku_data);
        // 更新采购表
        $purchase_order_res = DB::table('purchase_order')
            ->where('cg_number', $allData['cg_number'])
            ->update($edit_cgdata);

        $acset_acti_id = ''; //科目
        $sjprice = $cw_amount * 100; //实际金额
        $jsprice = $cw_amount * 100; //结算金额

        $recr_ress = DB::table('receivable_credit')
            ->where('recr_cid', $new_user_infos->adm_cid)
            ->where('recr_shop_superior_id', $new_user_infos->shop_superior_id)
            ->where('recr_account_type', '20')
            ->where('recr_original_number', $allData['cg_number'])
            ->select('recr_settle_price', 'recr_yet_receipt', 'recr_id')->get();
        $yet_receipt = $sjprice;
        foreach ($recr_ress as $k => $v) {
            if ($yet_receipt > 0) {
                if ($yet_receipt + $v->recr_yet_receipt > $v->recr_settle_price) {
                    $receivable_creditsave['recr_yet_receipt'] = $v->recr_settle_price;
                    $yet_receipt = $yet_receipt - ($v->recr_settle_price - $v->recr_yet_receipt);
                } else {
                    $receivable_creditsave['recr_yet_receipt'] = $v->recr_yet_receipt + $yet_receipt;
                    $yet_receipt = 0;
                }
                $recr_ress = DB::table('receivable_credit')
                    ->where('recr_cid', $new_user_infos->adm_cid)
                    ->where('recr_shop_superior_id', $new_user_infos->shop_superior_id)
                    ->where('recr_id', $v->recr_id)
                    ->update($receivable_creditsave);
                if (!$recr_ress) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'出库失败001'];
                }
            }
        }
        if ($yet_receipt > 0) {
            $sjprice = $sjprice - $yet_receipt; //实际金额
        }
        // 2. 查询仓库的库存数量
        $find_waon = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $allData['cg_wareid'])
            ->where('waon_class', $allData['cg_waon_class'])
            ->select('waon_id', 'waon_all_amount', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount')
            ->first();
        // 更改仓库库存总数量
        $waon_data['waon_all_amount'] = $find_waon->waon_all_amount + $actual_count; //商品总库存
        $waon_data['waon_stock_fine_amount'] = $find_waon->waon_stock_fine_amount + $actual_count; //良品总库存
        $waon_res = DB::table('warehouse_onhand')
            ->where('waon_id', $find_waon->waon_id)
            ->update($waon_data);

        

        // 3.生成出入库记录
        $oure_res = OutinRecord::shopAddition(
            $new_user_infos, //用户信息
            $allData['cg_id'], //原始单的关联id
            $allData['cg_number'], //原始单的关联单号
            3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
            2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            $allData['cg_supplyunit'], //选择的客户id,会员id/单位id
            $rk_number, //原始单号，入库单号
            $allData['cg_wareid'], //入库仓库id
            0, //出库仓库id
            $actual_count, //出库的商品总数量
            $state, //类型 5.退换回收单 9发货单 11换货出库12换货入库13退货入库14退货出库
            3, //操作类型：1锁定库存2出库3入库4调货5发货
            $find_waon->waon_stock_fine_amount, //良品总库存
            $find_waon->waon_lock_fine_amount, //良品锁定数量
            $find_waon->waon_stock_priority_amount, //优先总库存
            $find_waon->waon_lock_priority_amount, //优先锁定数量
            $find_waon->waon_stock_unchecked_amount, //待检测总库存
            2, //出入库类型：1出库，2入库
            $allData['cg_waon_class'], //仓库类别
            $oure_goods_id, //商品id
            $oure_goods_quantity, //商品数量
            $oure_goods_inventory //出库类型1良品2优先
        );
        // 4.商品的出入库记录，记录商品库存、锁定数据
        $outin_res = OutinStockLock::addition(
            $new_user_infos, //用户信息
            $allData['cg_id'], //原始单的关联id
            $allData['cg_number'], //原始单的关联单号
            3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后8.盘库单9.销售出库单
            5, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单5.运营中心与门店来往
            $allData['cg_supplyunit'], //选择的客户id,会员id/单位id/门店id
            $rk_number, //原始单号，销售单单号
            $allData['cg_wareid'], //出库/入库的仓库id
            $actual_count, //出库商品总量
            16, //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库18销售出库单
            $find_waon->waon_stock_fine_amount, //良品总库存
            $find_waon->waon_lock_fine_amount, //良品锁定数量
            $find_waon->waon_stock_priority_amount, //优先总库存
            $find_waon->waon_lock_priority_amount, //优先锁定数量
            $find_waon->waon_stock_unchecked_amount, //待检测总库存
            2, //出入库类型：1出库2入库3锁定4取消锁定
            $req_goo_data //商品数组，商品数据
        );
        unset($req_goo_data);

        // 4.2 查询仓库商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $allData['cg_wareid'])
            ->where('wago_class', $allData['cg_waon_class'])
            ->whereIn('wago_goo_id', $goods_id)
            ->get(['wago_id', 'wago_stock_number', 'wago_goo_id']);
        $warehouse_goods = json_decode(json_encode($warehouse_goods), true);
        // 4.3 处理要入库的商品库存数量
        if (empty($warehouse_goods)) {
            $ware_edit_res = true;
        } else {
            // 4.4 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
            $sql = 'UPDATE `faster_warehouse_goods` SET ';
            $stock_number_sql = ''; //良品库存数量(仓库+仓位)
            $stock_amount_sql = ''; //仓库良品库存数量
            $update_time_sql = '';
            $ids = '';
            foreach ($warehouse_goods as $key => $value) {
                // 要更改的良品库存数量(仓库+仓位)
                $stock_number = $value['wago_stock_number'] + $goo_actual_count[$value['wago_goo_id']];
                // 更改良品库存数量(仓库+仓位)
                $stock_number_sql = $stock_number_sql . ' WHEN ' . $value['wago_id'];
                $stock_number_sql = $stock_number_sql . ' THEN ' . $stock_number;
                // 更改仓库良品库存数量
                $stock_amount_sql = $stock_amount_sql . ' WHEN ' . $value['wago_id'];
                $stock_amount_sql = $stock_amount_sql . ' THEN ' . $stock_number;
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value['wago_id'];
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $value['wago_id'] . ',';

                // 删除已更改的商品数据
                unset($goo_actual_count[$value['wago_goo_id']]);
            }

            if (!empty($stock_number_sql)) {
                $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $stock_number_sql . ' END,';
                $sql = $sql . ' `wago_stock_amount`=  CASE `wago_id` ' . $stock_amount_sql . ' END,';
                $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $update_time_sql . ' END';
                $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
                $ware_edit_res = DB::update($sql);
            } else {
                $ware_edit_res = true;
            }
        }

        if (empty($goo_actual_count)) {
            $ware_add_res = true;
        } else {
            // 4.5 仓库商品表中没有的商品，新增仓库商品
            foreach ($goo_actual_count as $key => $value) {
                $ware_add_data['wago_ware_id'] = $allData['cg_wareid'];
                $ware_add_data['wago_class'] = $allData['cg_waon_class'];
                $ware_add_data['wago_goo_id'] = $key;
                $ware_add_data['wago_stock_number'] = $value; //良品库存数量(仓库+仓位)
                $ware_add_data['wago_stock_amount'] = $value; //仓库良品库存数量
                $ware_add_res = DB::table('warehouse_goods')->insertGetId($ware_add_data);
                if (!$ware_add_res) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'仓库新增数据错误'];
                }
            }
        }
        // 根据供应商id,查找供应商名称
        $chun_unit_name = DB::table('shop')
            ->where('shop_id', $allData['cg_supplyunit'])
            ->value('shop_store_name');
        if ($allData['cg_paymentype'] != '4') { //结算方式4货到付款
            return ['code'=>500, 'msg'=>'error', 'data'=>'结款方式错误'];
        } else {
            // 生成应付
            $createBill = ReceivableBill::create(
                $new_user_infos, //用户信息
                15, //类型：15采购单
                0, //应收账款id
                $allData['cg_id'], //原始id(采购单单id)
                $allData['cg_number'], //应收账款单号/原始号(订单编号)
                5, //客户类型：1.门店零售 2.来往单位
                $allData['cg_supplyunit'], //会员id/来往单位id/门店id
                $chun_unit_name, //来往单位名称
                $jsprice, //结算金额
                date('Y-m-d H:i:s'), //结款时间
                $acset_acti_id, //会计科目id
                $jsprice, //实际金额
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                $sjprice, //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                18, //显示类型：18采购单
                2, //是否合并代收：1是2否
                $now_time,
                0 //技师是否收钱：0未选择1是2否
            );
        }
        if ($ware_inorder_res && $purchase_order_res && $waon_res && $oure_res && $ware_edit_res && $ware_add_res && $createBill && $add_storage_goods_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'入库成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败'];
        }
    }

    // 销售单结算
    public static function sellSettlement(
        $user_info,
        $request
    ) {
        if ($request['type'] == 2) {//提交结算
            $sell_data_result = DB::table('sell as a')
                ->leftJoin('channel_unit as b', 'b.chun_id', '=', 'a.sell_chun_id')
                ->where('sell_number', $request['sell_number'])
                ->where('sell_settlement_state', 1) //结算状态结算状态1未结算2已结算
                ->select('sell_id', 'sell_price', 'sell_moling', 'sell_chun_id', 'sell_number', 'sell_create_time', 'chun_unit_name', 'sell_adm_id', 'sell_system_type', 'sell_yfmoney', 'sell_actual_price', 'sell_cg_shop_id')
                ->first();
            if (empty($sell_data_result)) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'当前销售单已结算'];
            }
            $sell_data['sell_actual_price'] = $request['sell_actual_price'] * 100;
            if ($request['moling_type'] == '1') { //是否抹零 1是2否
                if ($sell_data['sell_actual_price'] + $request['sell_moling']*100  == $sell_data_result->sell_price) {
                    $sell_data['sell_settlement_state'] = '2'; //已结算
                } else {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'结算金额错误'];
                }
                $sell_data['sell_moling'] = $sell_data_result->sell_moling + $request['sell_moling'] * 100;
            }

            if ($request['moling_type'] == '2') { //2不抹零
                $request['sell_moling'] = 0;
                if ($sell_data['sell_actual_price'] == $sell_data_result->sell_price) {
                    $sell_data['sell_settlement_state'] = '2'; //结算中
                } else {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'结算金额错误'];
                }
            }


            if ($request['moling_type'] == '1') {//多收
                $jsje = $request['sell_actual_price'] + $request['sell_moling'];
            } elseif ($request['moling_type'] == '2') {//少收,抹零
                $jsje = $request['sell_actual_price'] + $request['sell_moling'];
            } else {
                $jsje = $request['sell_actual_price'];
            }
            $moling_price = abs($request['sell_moling']);
            $sell_save = DB::table('sell')
                ->where('sell_number', $request['sell_number'])
                ->update($sell_data);
            // 添加结款明细记录
            if ($request['content'] == '') {
                $request['content'] = ' ';
            }
            if ($sell_data_result->sell_system_type == 1) { //供货方类型1自营2系统（自己的销售单）
                $sell_data_result->chun_unit_name = DB::table('shop')
                    ->where('shop_id', $sell_data_result->sell_cg_shop_id)
                    ->value('shop_store_name');
            }
            $acset_res = AccountingSettlement::add(
                $user_info,                 // [用户信息]
                21,                          // 单据类型21销售出库单
                $sell_data_result->sell_id,          // [与单据类型对应的id]
                $sell_data_result->sell_number, // [与单据类型对应的单号]
                5,                     // [买家类型：1会员零售2客户单位3.外派门店（加盟店或总店） 4会员零售(工单代收）5接单门店（总店或加盟店）6 速电派单]
                $sell_data_result->sell_chun_id,       // [会员/客户id]
                $sell_data_result->chun_unit_name,     // [来往单位名称]
                $request['ac_id'],         // [会计科目id]
                1,                                // [类型1收入2支出]
                $request['sell_actual_price'] * 100,                 // [实际金额](此次的实收金额)
                $sell_data_result->sell_price,                 // [合计金额](此次的应收金额)
                0,                                // [欠收金额](此次结款后还应收金额)
                $moling_price * 100,                                // [抹零金额]
                $request['content']                                // [备注]
            );

            // 添加结款明细业务凭证
            // 根据银行账户id，查询对应的名称
            $find_acti_data = DB::table('account_title')
                ->where('acti_id', $request['ac_id'])
                ->where('acti_shop_id', $user_info->adm_shop_id)
                ->select('acti_subject_code', 'acti_course_title')
                ->first();
            // 判断是否有抹零金额
            if ($request['sell_moling'] == '0') {
                $volo_data[0]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                $volo_data[0]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                $volo_data[0]['acsl_type'] = 1; //类型1借方2贷方
                $volo_data[0]['acsl_borrow_subject'] = '220201'; //借方科目
                $volo_data[0]['acsl_borrow_subject_name'] = '应付账款'; //借方科目名称
                $volo_data[0]['acsl_borrow_price'] = $request['sell_actual_price']; //借方金额
                $volo_data[0]['acsl_loan_subject'] = $find_acti_data->acti_subject_code; //贷方科目
                $volo_data[0]['acsl_loan_subject_name'] = $find_acti_data->acti_course_title; //贷方科目名称
                $volo_data[0]['acsl_loan_price'] = $request['sell_actual_price']; //贷方金额
                $volo_data[1]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                $volo_data[1]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                $volo_data[1]['acsl_type'] = 1; //类型1借方2贷方
                $volo_data[1]['acsl_borrow_subject'] = ''; //借方科目
                $volo_data[1]['acsl_borrow_subject_name'] = ''; //借方科目名称
                $volo_data[1]['acsl_borrow_price'] = 0; //借方金额
                $volo_data[1]['acsl_loan_subject'] = ''; //贷方科目
                $volo_data[1]['acsl_loan_subject_name'] = ''; //贷方科目名称
                $volo_data[1]['acsl_loan_price'] = 0; //贷方金额
            } else {
                if ($request['sell_moling'] > 0) {//少收
                    $volo_data[0]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                    $volo_data[0]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                    $volo_data[0]['acsl_type'] = 1; //类型1借方2贷方
                    $volo_data[0]['acsl_borrow_subject'] = '220201'; //借方科目
                    $volo_data[0]['acsl_borrow_subject_name'] = '应付账款'; //借方科目名称
                    $volo_data[0]['acsl_borrow_price'] = $request['sell_actual_price']; //借方金额
                    $volo_data[0]['acsl_loan_subject'] = $find_acti_data->acti_subject_code; //贷方科目
                    $volo_data[0]['acsl_loan_subject_name'] = $find_acti_data->acti_course_title; //贷方科目名称
                    $volo_data[0]['acsl_loan_price'] = $jsje; //贷方金额
                    $volo_data[1]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                    $volo_data[1]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                    $volo_data[1]['acsl_type'] = 1; //类型1借方2贷方
                    $volo_data[1]['acsl_borrow_subject'] = '640101'; //借方科目
                    $volo_data[1]['acsl_borrow_subject_name'] = '主营业务成本'; //借方科目名称
                    $volo_data[1]['acsl_borrow_price'] = $request['sell_moling']; //借方金额
                    $volo_data[1]['acsl_loan_subject'] = ''; //贷方科目
                    $volo_data[1]['acsl_loan_subject_name'] = ''; //贷方科目名称
                    $volo_data[1]['acsl_loan_price'] = 0; //贷方金额
                } else {//多收
                    $volo_data[0]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                    $volo_data[0]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                    $volo_data[0]['acsl_type'] = 1; //类型1借方2贷方
                    $volo_data[0]['acsl_borrow_subject'] = '220201'; //借方科目
                    $volo_data[0]['acsl_borrow_subject_name'] = '应付账款'; //借方科目名称
                    $volo_data[0]['acsl_borrow_price'] = $request['sell_actual_price']; //借方金额
                    $volo_data[0]['acsl_loan_subject'] = $find_acti_data->acti_subject_code; //贷方科目
                    $volo_data[0]['acsl_loan_subject_name'] = $find_acti_data->acti_course_title; //贷方科目名称
                    $volo_data[0]['acsl_loan_price'] = $jsje; //贷方金额

                    $volo_data[1]['acsl_acset_id'] = $acset_res; //结款明细凭证id
                    $volo_data[1]['acsl_shop_id'] = $user_info->adm_shop_id; //门店id
                    $volo_data[1]['acsl_type'] = 1; //类型1借方2贷方
                    $volo_data[1]['acsl_borrow_subject'] = ''; //借方科目
                    $volo_data[1]['acsl_borrow_subject_name'] = ''; //借方科目名称
                    $volo_data[1]['acsl_borrow_price'] = 0; //借方金额
                    $volo_data[1]['acsl_loan_subject'] = '600101'; //贷方科目
                    $volo_data[1]['acsl_loan_subject_name'] = '主营业务收入'; //贷方科目名称
                    $volo_data[1]['acsl_loan_price'] = $request['sell_moling']; //贷方金额
                }
            }
            $volo_id = DB::table('accounting_settlement_loan')->insert($volo_data);
            if ($sell_save && $volo_id && $acset_res) {
                return ['code'=>200, 'msg'=>'success', 'data'=>'结算成功'];
            } else {
                return ['code'=>500, 'msg'=>'error', 'data'=>'结算失败'];
            }
        }
    }

    // 销售出库记录
    public static function sellRecord(
        $request,
        $user_info
    ) {
        // 销售出库单数据
        $sell_data = DB::table('sell_record as sere')
            ->leftjoin('sell', 'sell_id', '=', 'sere.sere_sell_id')
            ->where('sell_id', $request['sell_id'])
            ->where('sere_cid', $user_info->adm_cid)
            ->where('sere_shop_id', $user_info->adm_shop_id)
            ->select('sere_id', 'sere_number', 'sere_sell_id', 'sere_sell_number', 'sere_ware_id', 'sere_waon_class', 'sere_create_name', 'sere_remark', 'sere_amount', 'sere_total_quantity', 'sere_type')
            ->first();
        $sell_data = json_decode(json_encode($sell_data, true), true);
        if (empty($sell_data)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前销售出库记录不存在！'];
        }
        $sell_data['ware_name'] = DB::table('warehouse')
            ->where('ware_id', $sell_data['sere_ware_id'])
            ->where('ware_shop_id', $user_info->adm_shop_id)
            ->value('ware_name');
        // 获取销售商品数据
        $find_goods = DB::table('sell_record_goods as serg')
            ->leftJoin('goods as goo', 'serg.serg_shop_id', '=', 'goo.goo_id')
            ->where('serg_sell_id', $request['sell_id'])
            ->where('serg_sere_id', $sell_data['sere_id'])
            ->where('serg_shop_id', $user_info->adm_shop_id)
            ->where('goo_delete', 1)
            ->where('goo_type', 1) //商品类型 1正常商品2赠品商品3活动商品4旧货商品
            ->select('serg_id', 'serg_wafr_id', 'serg_waon_class', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_id', 'goo_brse_id', 'goo_bra_name', 'goo_class', 'serg_goo_price', 'serg_goo_quantity')
            ->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();
        $serg_wafr_id = array_column($find_goods, 'serg_wafr_id');
        $wafr_data = DB::table('warehouse_freight')
            ->where('wafr_id', $serg_wafr_id)
            ->where('wafr_shop_id', $user_info->adm_shop_id)
            ->where('wafr_delete', 1)
            ->pluck('wafr_name', 'wafr_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;
                    }
                }
            }
            if (isset($wafr_data[$value->serg_wafr_id])) {
                $find_goods[$key]->wafr_name = $wafr_data[$value->serg_wafr_id];
            } else {
                $find_goods[$key]->wafr_name = '';
            }
            unset($find_goods[$key]->goo_class);
            unset($find_goods[$key]->goo_brse_id);
        }
        $data['sell_data'] = $sell_data;
        $data['goods_data'] = $find_goods;
        if ($sell_data) {
            return ['code'=>200, 'msg'=>'success', 'data'=>$data];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'查无数据'];
        }
    }
}
