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

use App\Services\CommonService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\WarehouseFreight;
use App\Http\Models\Api\WorkOrder;
use App\Http\Models\Services\WarehouseManage\OutinStockLock;
use App\Services\Business\WashOrderBasicService;

class WareInorder extends Model
{
    /**
     * warehousing 采购单入库
     *
     * @param [type] $user_info     用户信息
     * @param [type] $shop_id       门店id
     * @param [type] $request       提交的数据
     * @param [type] $goods_data    提交的商品数据
     * @param [type] $storage_goods 采购单商品数据
     * @param [type] $goods_id      前端提交入库数据的商品id
     * @param [type] $cg_data       采购单数据
     * @param [type] $rk_number     入库单号
     * @return void
     */
    public static function oldwarehousing(
        $user_info,
        $shop_id,
        $request,
        $goods_data,
        $storage_goods,
        $goods_id,
        $cg_data,
        $rk_number
    ) {
        $return['rk_number'] = $rk_number;
        $goods_name = '';
        $cw_amount = 0; //当前提交入库商品的总金额(应收总额)
        $actual_count = 0; //当前入库提交商品的实际入库总数量
        $actual_counts = 0;//当前入库提交商品的实际入库总数量(单位转换后)
        $storage_goods_total = 0; //采购单商品入库总数量
        $freight_goods_data = []; //仓位入库数据
        $ware_goods_data = []; //仓库入库数据
        $osld_in_key = 0;
        foreach ($goods_data as $key => $value) {
            if (!isset($storage_goods[$value['goods_id']])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'不是当前采购单商品，无法入库！'];
            }
            $temp_storage_goods = $storage_goods[$value['goods_id']];
            if ($temp_storage_goods['stgo_stop'] == '2') {
                return ['code'=>500, 'msg'=>'error', 'data'=>'当前商品已终止,不能进行入库操作'];
            }
            // 判断入库商品数量是否大于采购单商品采购数量
            if ($value['num'] + $temp_storage_goods['ruku_num'] > $temp_storage_goods['goods_num']) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'入库数量不可超过采购数量'];
            }
            $goo_data = DB::table('goods')
                ->where('goo_id', $value['goods_id'])
                ->select('goo_id', 'goo_name', 'goo_unit', 'goo_unta_id', 'goo_unit_conversion')
                ->first();

            // 新的入库单商品数据
            $temp_storage_goods['company_id'] = $user_info->adm_cid;
            $temp_storage_goods['stgo_superior_shop_id'] = $shop_id;
            $temp_storage_goods['stgo_shop_id'] = $user_info->adm_shop_id;
            $temp_storage_goods['relation_number'] = $rk_number; //入库单号
            $temp_storage_goods['creator'] = $user_info->adm_name; //创建人
            $temp_storage_goods['create_time'] = date('Y-m-d H:i:s'); //创建时间
            $temp_storage_goods['ruku_num'] = $value['num']; //入库数量
            $temp_storage_goods['edit_time'] = date('Y-m-d H:i:s'); //到货时间
            $temp_storage_goods['money'] = ((float)$temp_storage_goods['univalence'] * (int)$value['num']); //当前入库商品的采购总额
            // 添加入库商品数据
            $stgo_id = Db::table('storage_goods')->insertGetId($temp_storage_goods);

            $edit_storage_goods['ruku_num'] = $storage_goods[$value['goods_id']]['ruku_num'] + $value['num']; //采购商品总的入库数量
            $edit_storage_goods['edit_time'] = $temp_storage_goods['edit_time']; //到货时间
            // 更新采购单关联商品的入库数量、到货时间
            $storage_g_r = DB::table('storage_goods')
                ->where('relation_number', $request['cg_number'])
                ->where('goods_id', $value['goods_id'])
                ->select('goods_num','ruku_num')
                ->first();
            $storage_g_r = CommonService::dataToArray($storage_g_r);
            $ruku_num = $storage_g_r['ruku_num'] + $value['num'];
            if($ruku_num > $storage_g_r['goods_num']){
                return ['code'=>500, 'msg'=>'入库数量异常请刷新', 'data'=>'入库失败！001'];
            }
            $edit_res = DB::table('storage_goods')
                ->where('relation_number', $request['cg_number'])
                ->where('goods_id', $value['goods_id'])
                ->increment('ruku_num', $value['num'], ['edit_time' => $value['estimate_time']]);
            // 更改仓位的库存数量
            if ($goo_data) {
                $new_num = $value['num']; //当前入库提交商品的实际入库总数量
            }
            $wafr_res = DB::table('warehouse_freight')
                ->where('wafr_shop_id', $user_info->adm_shop_id)
                ->where('wafr_id', $value['wafr_id'])
                ->increment('wafr_all_stock', $new_num, ['wafr_update_time' => date('Y-m-d H:i:s')]);
            if (!$edit_res || !$stgo_id || !$wafr_res) {
                return ['code'=>500, 'msg'=>'商品入库失败1', 'data'=>'商品入库失败'];
            }

            $goods_name = $goods_name . $temp_storage_goods['goods_name'] . $temp_storage_goods['goods_number'];
            $cw_amount = $cw_amount + $temp_storage_goods['money']; //当前提交入库商品的总金额(应收总额)
            if ($goo_data) {
                $actual_counts += $value['num']; //当前入库提交商品的实际入库总数量
            }
            // $actual_count += $value['num']; //当前入库提交商品的实际入库总数量
            $storage_goods_total += $edit_storage_goods['ruku_num']; //采购单商品入库总数量

            $goo_actual_count[$value['goods_id']] = $value['num']; //商品id对应的实际入库的数量
            $goo_actual_id[] = $value['goods_id'];
            $goo_inventory[] = 1;

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

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

        // 入库单数据
        $ruku_data['company_id']            = $user_info->adm_cid;
        $ruku_data['rk_superior_shop_id']   = $shop_id;
        $ruku_data['rk_shop_id']            = $user_info->adm_shop_id;
        $ruku_data['rk_number']             = $rk_number; //入库单号
        $ruku_data['cg_number']             = $cg_data['cg_number']; //采购单号
        $ruku_data['rk_wareid']             = $cg_data['cg_wareid']; //仓库id
        $ruku_data['rk_waon_class']         = $cg_data['cg_waon_class']; //仓库类别
        $ruku_data['rk_state']              = 5; //入库单状态，1待入库3待审核4驳回5已完成8作废
        $ruku_data['rk_type']               = 1; //入库单类型 1普通采购 2采购退货 3采购换货 4代发采购
        if ($request['rk_image']) {
            $ruku_data['rk_image'] = uploadBase64ImgFolder($user_info->adm_shop_id, $request['rk_image']);
        }
        $ruku_data['rk_creator']            = $user_info->adm_name; //创建人
        $ruku_data['create_time']           = date('Y-m-d H:i:s');
        $ruku_data['rk_userid']             = $user_info->adm_id; //创建人id
        $ruku_data['rk_inputid']            = $user_info->adm_id; //入库人id
        $ruku_data['rk_remarks']            = (string) isset($request['rk_remark']) ? $request['rk_remark'] : ''; //入库备注
        $ruku_data['supplyunit']            = $cg_data['cg_supplyunit']; //供应商
        $ruku_data['arrival_time']          = date('Y-m-d H:i:s');
        $ruku_data['rk_waretype']           = 1; //入库类型1入库2退货3代发4换货
        $ruku_data['rk_amount']             = $cw_amount; //入库金额
        // 添加入库单
        $wain_id = Db::table('ware_inorder')->insertGetId($ruku_data);
        $cg_goods = DB::table('storage_goods')
            ->where('relation_number', $request['cg_number'])
            ->whereRaw('ruku_num < goods_num')
            ->select('id')
            ->first();
        $cg_goods = json_decode(json_encode($cg_goods), true);
        if (empty($cg_goods)) {
            // cg_state 采购单状态：1.审核中 2.财务审核 3.驳回编辑5.未入库 6.未出库 8.部分入库 11.完成 ( 9.待结算10.待审核) 12.确认完成 14.已封账 15.申请终止17.终止 18.代发采购19.修正中
            if ($user_info->shop_versions == 1) { //门店基础版
                $edit_cgdata['cg_state'] = 12;
            } else {
                $edit_cgdata['cg_state'] = 11;
            }
            $state = 1; //出入库记录类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
            $oslr_type = 16; //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库
        } else {
            $edit_cgdata['cg_state'] = 8;
            $state = 7; //出入库记录类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
            $oslr_type = 7; //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库
        }
        $edit_cgdata['dh_time']  = date('Y-m-d H:i:s');
        $edit_cgdata['edit_time'] = date('Y-m-d H:i:s');
        // 更新采购表
        $purchase_res = DB::table('purchase_order')
            ->where('cg_id', $cg_data['cg_id'])
            ->update($edit_cgdata);

        $money_end = 1;
        $acset_acti_id = ''; //科目
        $actual_price = $cw_amount * 100; //实际金额
        $settlement_price = $cw_amount * 100; //结算金额
        if ($cg_data['cg_settlementype'] == '3') { //结算状态1正常 待生成账单2待结算3已结算
            $inorderresult = DB::table('accounting_settlement')
                ->where('acset_original_number', $cg_data['cg_number'])
                ->where('acset_state', '1')//状态：1未确认2已确认3部分确认
                ->select('acset_id')
                ->first();
            if (!$inorderresult) {
                $inorderresult = DB::table('accounting_settlement')
                    ->where('acset_original_number', $cg_data['cg_number'])
                    ->where('acset_state', '2')
                    ->orderBy('acset_id', 'desc')
                    ->select('acset_id', 'acset_acti_id')
                    ->first();
                if ($inorderresult) {
                    if ($edit_cgdata['cg_state'] == '11') {//11.完成
                        $money_end = '2';
                    }
                }
            }
        }
        
        if ($money_end == '2') {//已完成，并且有已确认的结款明细
            // 更新预付记录状态
            $recr_ress = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                ->where('recr_original_number', $cg_data['cg_number'])
                ->select('recr_settle_price', 'recr_id')->get();
            foreach ($recr_ress as $k => $v) {
                $edit_data['recr_state'] = 2;//状态：1未确认2已确认3已收款4已付款
                $edit_data['recr_yet_receipt'] = $v->recr_settle_price;
                $recr_ress = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                    ->where('recr_id', $v->recr_id)
                    ->update($edit_data);
            }
        } else {
            $recr_ress = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                ->where('recr_account_type', '20')
                ->where('recr_original_number', $cg_data['cg_number'])
                ->select('recr_settle_price', 'recr_yet_receipt', 'recr_id')->get();
            $yet_receipt = $actual_price;
            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', $user_info->adm_cid)
                        ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                        ->where('recr_id', $v->recr_id)
                        ->update($receivable_creditsave);
                }
            }
            if ($yet_receipt > 0) {
                $actual_price = $actual_price - $yet_receipt; //实际金额
            }
        }
        // 仓库库存调整
        $stgo_retrun = WarehouseFreight::warehouseAddition(
            $cg_data,
            $goods_id,
            $freight_goods_data,
            $ware_goods_data,
            $wafr_id //数组，仓位id
        );
        if (!$stgo_retrun) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！01'];
        }
        // 生成仓位商品出入库
        $oure_res = WarehouseFreight::addition(
            $user_info, //用户信息
            $cg_data,
            $wain_id,
            $rk_number,
            $freight_goods_data
        );
        if (!$oure_res) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！02'];
        }

        // 2. 查询仓库的库存数量
        $find_waon = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $cg_data['cg_wareid'])
            ->where('waon_class', $cg_data['cg_waon_class'])
            ->select('waon_id', 'waon_all_amount', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount')
            ->first();
        // 更改仓库库存总数量
        $waon_data['waon_all_amount'] = $find_waon->waon_all_amount + $actual_counts; //商品总库存
        $waon_data['waon_stock_fine_amount'] = $find_waon->waon_stock_fine_amount + $actual_counts; //良品总库存
        $waon_res = DB::table('warehouse_onhand')
            ->where('waon_id', $find_waon->waon_id)
            ->update($waon_data);
        // 3.生成出入库记录
        $oure_res = OutinRecord::addition(
            $user_info, //用户信息
            $cg_data['cg_id'], //原始单的关联id
            $cg_data['cg_number'], //原始单的关联单号
            3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
            2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            $cg_data['cg_supplyunit'], //选择的客户id,会员id/单位id
            $rk_number, //原始单号，旧货回收单单号
            $cg_data['cg_wareid'], //入库仓库id
            0, //出库仓库id
            $actual_counts, //出库的商品总数量
            $state, //出入库记录类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
            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入库
            $cg_data['cg_waon_class'], //仓库类别
            $oure_goods_id, //商品id
            $oure_goods_quantity, //商品数量
            $oure_goods_inventory //出库类型1良品2优先
        );
        // $osld_in_key = 0;
        // foreach ($goods_data as $key => $value) {
        //     // 库存锁定-出入库记录表【新增21.06.25】
        //     $osld_goo_datas[$osld_in_key]['goo_waon_class'] = $cg_data['cg_waon_class']; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
        //     $osld_goo_datas[$osld_in_key]['goo_id'] = $value['goods_id']; //商品id
        //     $osld_goo_datas[$osld_in_key]['goo_number'] = $value['num']; //商品数量
        //     $osld_goo_datas[$osld_in_key]['goo_out_in_type'] = 2; //出入库类型：1出库2入库3锁定4取消锁定
        //     $osld_goo_datas[$osld_in_key]['goo_inventory'] = 1; //类型1良品2优先3待检测
        //     // 查询仓库商品库存数量
        //     $find_in_wago_data = DB::table('warehouse_goods')
        //         ->where('wago_ware_id', $cg_data['cg_wareid'])
        //         ->where('wago_class', $cg_data['cg_waon_class'])
        //         ->where('wago_goo_id', $value['goods_id'])
        //         ->select('wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
        //         ->first();
        //     $osld_goo_datas[$osld_in_key]['old_stock_number'] = $find_in_wago_data->wago_stock_number - $value['num'] ; //旧的商品良品库存数量
        //     $osld_goo_datas[$osld_in_key]['old_stock_lock_number'] = $find_in_wago_data->wago_lock_quantity; //旧的商品良品库存锁定数量
        //     $osld_goo_datas[$osld_in_key]['old_priority_number'] = $find_in_wago_data->wago_priority_stock_number; //旧的商品优先库存数量
        //     $osld_goo_datas[$osld_in_key]['old_priority_lock_number'] = $find_in_wago_data->wago_priority_lock_quantity; //旧的商品优先库存锁定数量
        //     $osld_goo_datas[$osld_in_key]['old_unchecked_number'] = $find_in_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量
        //     $osld_goo_datas[$osld_in_key]['new_stock_number'] = $find_in_wago_data->wago_stock_number; //新的商品良品库存数量
        //     $osld_goo_datas[$osld_in_key]['new_stock_lock_number'] = $find_in_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
        //     $osld_goo_datas[$osld_in_key]['new_priority_number'] = $find_in_wago_data->wago_priority_stock_number; //新的商品优先库存数量
        //     $osld_goo_datas[$osld_in_key]['new_priority_lock_number'] = $find_in_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
        //     $osld_goo_datas[$osld_in_key]['new_unchecked_number'] = $find_in_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
        //     $osld_goo_datas[$osld_in_key]['osld_update_time'] = date('Y-m-d H:i:s'); //更新时间
        //     $osld_goo_datas[$osld_in_key] = (Object)$osld_goo_datas[$osld_in_key];
        //     $osld_in_key++;
        // }
        // // 库存锁定-出入库记录
        // $oslr_in_res = OutinStockLock::addition(
        //     $user_info, //用户信息
        //     $cg_data['cg_id'], //原始单的关联id
        //     $cg_data['cg_number'], //原始单的关联单号
        //     3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
        //     2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
        //     $cg_data['cg_supplyunit'], //选择的客户id,会员id/单位id
        //     $rk_number, //原始单号
        //     $cg_data['cg_wareid'], //入库的仓库id
        //     $actual_count, //入库总数量
        //     $oslr_type, //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库
        //     ($find_waon->waon_stock_fine_amount + $actual_count), //良品总库存
        //     $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入库
        //     $osld_goo_datas
        // );
        // unset($osld_goo_datas);
        if (!$oure_res) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'商品流水记录更新失败'];
        }

        // 根据供应商id,查找供应商名称
        $chun_unit_name = DB::table('channel_unit')
            ->where('chun_id', $cg_data['cg_supplyunit'])
            ->value('chun_unit_name');
        if ($cg_data['cg_paymentype'] != '3') {
            // 应付
            $createBill = ReceivableBill::create(
                $user_info, //用户信息
                15, //recr_type类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单 7.销售出库单 8非实物开单 9.账单冲红 10订单冲单 11.加盟店订单收款 12.加盟店订单代收13.旧货回收14售后单15采购单16采购退货单17采购款到发货(预付款)18期初账单
                0, //recr_number_id账单的应收账款id
                $cg_data['cg_id'], //recr_original_id与类型所对应的id
                $cg_data['cg_number'], //recr_original_number与类型所对应的单号
                2, //客户类型：1.会员零售 2.来往单位 3.外派门店（加盟店或总店） 4会员零售(工单代收）5接单门店（总店或加盟店）6速电派单7虚拟加盟店
                $cg_data['cg_supplyunit'], //会员id/来往单位id/加盟店id/虚拟加盟店
                $chun_unit_name, //会员姓名/来往单位名称/加盟店名称/虚拟加盟店
                $settlement_price, //结算金额
                '', //结款时间
                $acset_acti_id, //会计科目id
                $settlement_price, //实际金额
                0, //抹零金额
                $money_end,  //状态：1.未核销 2.已核销 3已收款
                1,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                $actual_price, //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                18, //recr_account_type显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单 10订单退款(退货单) 11发票 12价外费 13折扣金额抵货款 14.账单冲红 15.订单冲单16.旧货回收 17售后单18采购单19采购退货单20采购款到发货（预付款）21期初账单22.采购账单
                2, //是否合并代收：1是2否
                $cg_data['create_time'],
                0 //技师是否收钱：0未选择1是2否
            );

            // 生成凭证单据
            $vore_data = WorkOrder::voucherReceipts($user_info, $user_info->adm_shop_id, 3, 0, '', $cg_data['cg_id'], $cg_data['cg_number'], $settlement_price, 0, 0, '', '1', 2, $cg_data['cg_supplyunit'], $chun_unit_name);
            if (!$createBill || !$vore_data) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！03'];
            }
        } else {
            // 生成应付
            $createBill = ReceivableBill::create(
                $user_info, //用户信息
                17, //recr_type类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单 7.销售出库单 8非实物开单 9.账单冲红 10订单冲单 11.加盟店订单收款 12.加盟店订单代收13.旧货回收14售后单15采购单16采购退货单17采购款到发货(预付款)18期初账单
                0, //recr_number_id账单的应收账款id
                $cg_data['cg_id'], //recr_original_id与类型所对应的id
                $cg_data['cg_number'], //recr_original_number与类型所对应的单号
                2, //客户类型：1.会员零售 2.来往单位 3.外派门店（加盟店或总店） 4会员零售(工单代收）5接单门店（总店或加盟店）6速电派单7虚拟加盟店
                $cg_data['cg_supplyunit'], //会员id/来往单位id/加盟店id/虚拟加盟店
                $chun_unit_name, //会员姓名/来往单位名称/加盟店名称/虚拟加盟店
                $settlement_price, //结算金额
                '', //结款时间
                $acset_acti_id, //会计科目id
                $settlement_price, //实际金额
                0, //抹零金额
                $money_end,  //状态：1.未核销 2.已核销 3已收款
                1,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                $actual_price, //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                20, //recr_account_type显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单 10订单退款(退货单) 11发票 12价外费 13折扣金额抵货款 14.账单冲红 15.订单冲单16.旧货回收 17售后单18采购单19采购退货单20采购款到发货（预付款）21期初账单22.采购账单
                2, //是否合并代收：1是2否
                $cg_data['create_time'],
                0 //技师是否收钱：0未选择1是2否
            );

            // 生成凭证单据
            $vore_data = WorkOrder::voucherReceipts($user_info, $user_info->adm_shop_id, 3, 0, '', $cg_data['cg_id'], $cg_data['cg_number'], $settlement_price, 0, 0, '', '1', 2, $cg_data['cg_supplyunit'], $chun_unit_name);
            if (!$createBill || !$vore_data) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！04'];
            }
        }
        if (!$wain_id || !$purchase_res || !$waon_res) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！05'];
        } else {
            return ['code'=>200, 'msg'=>'入库成功', 'data'=>$return];
        }
    }

    public static function warehousing(
        $user_info,
        $shop_id,
        $request,
        $goods_data,
        $storage_goods,
        $goods_id,
        $cg_data,
        $rk_number
    ) {
        $return['rk_number'] = $rk_number;
        $goods_name = '';
        $cw_amount = 0; //当前提交入库商品的总金额(应收总额)
        $actual_count = 0; //当前入库提交商品的实际入库总数量
        $actual_counts = 0;//当前入库提交商品的实际入库总数量(单位转换后)
        $storage_goods_total = 0; //采购单商品入库总数量
        $freight_goods_data = []; //仓位入库数据
        $ware_goods_data = []; //仓库入库数据
        $osld_in_key = 0;
        $new_goods_data = [];
        foreach ($goods_data as $key => $value) {
            if (!isset($storage_goods[$value['goods_id']])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'不是当前采购单商品，无法入库！'];
            }
            $temp_storage_goods = $storage_goods[$value['goods_id']];
            if ($temp_storage_goods['stgo_stop'] == '2') {
                return ['code'=>500, 'msg'=>'error', 'data'=>'当前商品已终止,不能进行入库操作'];
            }
            // 判断入库商品数量是否大于采购单商品采购数量
            if ($value['num'] + $temp_storage_goods['ruku_num'] > $temp_storage_goods['goods_num']) {
                $return['num'] = $value['num'];
                $return['ruku_num'] = $temp_storage_goods['ruku_num'];
                $return['goods_num'] = $temp_storage_goods['goods_num'];
                return ['code'=>500, 'msg'=>'入库数量不可超过采购数量', 'data'=>$return];
            }
            $goo_data = DB::table('goods')
                ->where('goo_id', $value['goods_id'])
                ->select('goo_id', 'goo_name', 'goo_unit', 'goo_unta_id', 'goo_unit_conversion')
                ->first();
            $new_goods_data[$key]['goo_id'] = $value['goods_id'];
            // 新的入库单商品数据
            $temp_storage_goods['company_id'] = $user_info->adm_cid;
            $temp_storage_goods['stgo_superior_shop_id'] = $shop_id;
            $temp_storage_goods['stgo_shop_id'] = $user_info->adm_shop_id;
            $temp_storage_goods['relation_number'] = $rk_number; //入库单号
            $temp_storage_goods['creator'] = $user_info->adm_name; //创建人
            $temp_storage_goods['create_time'] = date('Y-m-d H:i:s'); //创建时间
            $temp_storage_goods['ruku_num'] = $value['num']; //入库数量
            $temp_storage_goods['edit_time'] = date('Y-m-d H:i:s'); //到货时间
            $temp_storage_goods['money'] = ((float)$temp_storage_goods['univalence'] * (int)$value['num']); //当前入库商品的采购总额
            // 添加入库商品数据
            $stgo_id = Db::table('storage_goods')->insertGetId($temp_storage_goods);

            $edit_storage_goods['ruku_num'] = $storage_goods[$value['goods_id']]['ruku_num'] + $value['num']; //采购商品总的入库数量
            $edit_storage_goods['edit_time'] = $temp_storage_goods['edit_time']; //到货时间
            // 更新采购单关联商品的入库数量、到货时间
            $storage_g_r = DB::table('storage_goods')
                ->where('relation_number', $request['cg_number'])
                ->where('goods_id', $value['goods_id'])
                ->select('goods_num','ruku_num')
                ->first();
            $storage_g_r = CommonService::dataToArray($storage_g_r);
            $ruku_num = $storage_g_r['ruku_num'] + $value['num'];
            if($ruku_num > $storage_g_r['goods_num']){
                return ['code'=>500, 'msg'=>'入库数量异常请刷新', 'data'=>'入库失败！001'];
            }
            $edit_res = DB::table('storage_goods')
                ->where('relation_number', $request['cg_number'])
                ->where('goods_id', $value['goods_id'])
                ->increment('ruku_num', $value['num'], ['edit_time' => $value['estimate_time']]);
            // 更改仓位的库存数量
            if ($goo_data) {
                $new_num = $value['num']; //当前入库提交商品的实际入库总数量
            }
            $wafr_res = DB::table('warehouse_freight')
                ->where('wafr_shop_id', $user_info->adm_shop_id)
                ->where('wafr_id', $value['wafr_id'])
                ->increment('wafr_all_stock', $new_num, ['wafr_update_time' => date('Y-m-d H:i:s')]);
            if (!$edit_res || !$stgo_id || !$wafr_res) {
                return ['code'=>500, 'msg'=>'商品入库失败1', 'data'=>'商品入库失败'];
            }

            $goods_name = $goods_name . $temp_storage_goods['goods_name'] . $temp_storage_goods['goods_number'];
            $cw_amount = $cw_amount + $temp_storage_goods['money']; //当前提交入库商品的总金额(应收总额)
            if ($goo_data) {
                $actual_counts += $value['num']; //当前入库提交商品的实际入库总数量
            }
            // $actual_count += $value['num']; //当前入库提交商品的实际入库总数量
            $storage_goods_total += $edit_storage_goods['ruku_num']; //采购单商品入库总数量

            $goo_actual_count[$value['goods_id']] = $value['num']; //商品id对应的实际入库的数量
            $goo_actual_id[] = $value['goods_id'];
            $goo_inventory[] = 1;

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

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

        // 入库单数据
        $ruku_data['company_id']            = $user_info->adm_cid;
        $ruku_data['rk_superior_shop_id']   = $shop_id;
        $ruku_data['rk_shop_id']            = $user_info->adm_shop_id;
        $ruku_data['rk_number']             = $rk_number; //入库单号
        $ruku_data['cg_number']             = $cg_data['cg_number']; //采购单号
        $ruku_data['rk_wareid']             = $cg_data['cg_wareid']; //仓库id
        $ruku_data['rk_waon_class']         = $cg_data['cg_waon_class']; //仓库类别
        $ruku_data['rk_state']              = 5; //入库单状态，1待入库3待审核4驳回5已完成8作废
        $ruku_data['rk_type']               = 1; //入库单类型 1普通采购 2采购退货 3采购换货 4代发采购
        if ($request['rk_image']) {
            $ruku_data['rk_image'] = uploadBase64ImgFolder($user_info->adm_shop_id, $request['rk_image']);
        }
        $ruku_data['rk_creator']            = $user_info->adm_name; //创建人
        $ruku_data['create_time']           = date('Y-m-d H:i:s');
        $ruku_data['rk_userid']             = $user_info->adm_id; //创建人id
        $ruku_data['rk_inputid']            = $user_info->adm_id; //入库人id
        $ruku_data['rk_remarks']            = (string) isset($request['rk_remark']) ? $request['rk_remark'] : ''; //入库备注
        $ruku_data['supplyunit']            = $cg_data['cg_supplyunit']; //供应商
        $ruku_data['arrival_time']          = date('Y-m-d H:i:s');
        $ruku_data['rk_waretype']           = 1; //入库类型1入库2退货3代发4换货
        $ruku_data['rk_amount']             = $cw_amount; //入库金额
        // 添加入库单
        $wain_id = Db::table('ware_inorder')->insertGetId($ruku_data);
        $cg_goods = DB::table('storage_goods')
            ->where('relation_number', $request['cg_number'])
            ->whereRaw('ruku_num < goods_num')
            ->select('id')
            ->first();
        $cg_goods = json_decode(json_encode($cg_goods), true);
        if (empty($cg_goods)) {
            // cg_state 采购单状态：1.审核中 2.财务审核 3.驳回编辑5.未入库 6.未出库 8.部分入库 11.完成 ( 9.待结算10.待审核) 12.确认完成 14.已封账 15.申请终止17.终止 18.代发采购19.修正中
            if ($user_info->shop_versions == 1) { //门店基础版
                $edit_cgdata['cg_state'] = 12;
            } else {
                $edit_cgdata['cg_state'] = 11;
            }
            $state = 1; //出入库记录类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
            $oslr_type = 16; //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库
        } else {
            $edit_cgdata['cg_state'] = 8;
            $state = 7; //出入库记录类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
            $oslr_type = 7; //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库
        }
        $edit_cgdata['dh_time']  = date('Y-m-d H:i:s');
        $edit_cgdata['edit_time'] = date('Y-m-d H:i:s');
        // 更新采购表
        $purchase_res = DB::table('purchase_order')
            ->where('cg_id', $cg_data['cg_id'])
            ->update($edit_cgdata);

        $money_end = 1;
        $acset_acti_id = ''; //科目
        $actual_price = $cw_amount * 100; //实际金额
        $settlement_price = $cw_amount * 100; //结算金额
        if ($cg_data['cg_settlementype'] == '3') { //结算状态1正常 待生成账单2待结算3已结算
            $inorderresult = DB::table('accounting_settlement')
                ->where('acset_original_number', $cg_data['cg_number'])
                ->where('acset_state', '1')//状态：1未确认2已确认3部分确认
                ->select('acset_id')
                ->first();
            if (!$inorderresult) {
                $inorderresult = DB::table('accounting_settlement')
                    ->where('acset_original_number', $cg_data['cg_number'])
                    ->where('acset_state', '2')
                    ->orderBy('acset_id', 'desc')
                    ->select('acset_id', 'acset_acti_id')
                    ->first();
                if ($inorderresult) {
                    if ($edit_cgdata['cg_state'] == '11') {//11.完成
                        $money_end = '2';
                    }
                }
            }
        }
        
        if ($money_end == '2') {//已完成，并且有已确认的结款明细
            // 更新预付记录状态
            $recr_ress = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                ->where('recr_original_number', $cg_data['cg_number'])
                ->select('recr_settle_price', 'recr_id')->get();
            foreach ($recr_ress as $k => $v) {
                $edit_data['recr_state'] = 2;//状态：1未确认2已确认3已收款4已付款
                $edit_data['recr_yet_receipt'] = $v->recr_settle_price;
                $recr_ress = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                    ->where('recr_id', $v->recr_id)
                    ->update($edit_data);
            }
        } else {
            $recr_ress = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                ->where('recr_account_type', '20')
                ->where('recr_original_number', $cg_data['cg_number'])
                ->select('recr_settle_price', 'recr_yet_receipt', 'recr_id')->get();
            $yet_receipt = $actual_price;
            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', $user_info->adm_cid)
                        ->where('recr_shop_superior_id', $user_info->adm_shop_id)
                        ->where('recr_id', $v->recr_id)
                        ->update($receivable_creditsave);
                }
            }
            if ($yet_receipt > 0) {
                $actual_price = $actual_price - $yet_receipt; //实际金额
            }
        }
        // 仓库库存调整
        $stgo_retrun = WarehouseFreight::warehouseAddition(
            $cg_data,
            $goods_id,
            $freight_goods_data,
            $ware_goods_data,
            $wafr_id //数组，仓位id
        );
        if (!$stgo_retrun) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！01'];
        }
        // 生成仓位商品出入库
        $oure_res = WarehouseFreight::addition(
            $user_info, //用户信息
            $cg_data,
            $wain_id,
            $rk_number,
            $freight_goods_data
        );
        if (!$oure_res) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！02'];
        }

        // 2. 查询仓库的库存数量
        $find_waon = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $cg_data['cg_wareid'])
            ->where('waon_class', $cg_data['cg_waon_class'])
            ->select('waon_id', 'waon_all_amount', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount')
            ->first();
        // 更改仓库库存总数量
        $waon_data['waon_all_amount'] = $find_waon->waon_all_amount + $actual_counts; //商品总库存
        $waon_data['waon_stock_fine_amount'] = $find_waon->waon_stock_fine_amount + $actual_counts; //良品总库存
        $waon_res = DB::table('warehouse_onhand')
            ->where('waon_id', $find_waon->waon_id)
            ->update($waon_data);
        // 3.生成出入库记录
        $oure_res = OutinRecord::addition(
            $user_info, //用户信息
            $cg_data['cg_id'], //原始单的关联id
            $cg_data['cg_number'], //原始单的关联单号
            3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
            2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            $cg_data['cg_supplyunit'], //选择的客户id,会员id/单位id
            $rk_number, //原始单号，旧货回收单单号
            $cg_data['cg_wareid'], //入库仓库id
            0, //出库仓库id
            $actual_counts, //出库的商品总数量
            $state, //出入库记录类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
            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入库
            $cg_data['cg_waon_class'], //仓库类别
            $oure_goods_id, //商品id
            $oure_goods_quantity, //商品数量
            $oure_goods_inventory //出库类型1良品2优先
        );
        // $osld_in_key = 0;
        // foreach ($goods_data as $key => $value) {
        //     // 库存锁定-出入库记录表【新增21.06.25】
        //     $osld_goo_datas[$osld_in_key]['goo_waon_class'] = $cg_data['cg_waon_class']; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
        //     $osld_goo_datas[$osld_in_key]['goo_id'] = $value['goods_id']; //商品id
        //     $osld_goo_datas[$osld_in_key]['goo_number'] = $value['num']; //商品数量
        //     $osld_goo_datas[$osld_in_key]['goo_out_in_type'] = 2; //出入库类型：1出库2入库3锁定4取消锁定
        //     $osld_goo_datas[$osld_in_key]['goo_inventory'] = 1; //类型1良品2优先3待检测
        //     // 查询仓库商品库存数量
        //     $find_in_wago_data = DB::table('warehouse_goods')
        //         ->where('wago_ware_id', $cg_data['cg_wareid'])
        //         ->where('wago_class', $cg_data['cg_waon_class'])
        //         ->where('wago_goo_id', $value['goods_id'])
        //         ->select('wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
        //         ->first();
        //     $osld_goo_datas[$osld_in_key]['old_stock_number'] = $find_in_wago_data->wago_stock_number - $value['num'] ; //旧的商品良品库存数量
        //     $osld_goo_datas[$osld_in_key]['old_stock_lock_number'] = $find_in_wago_data->wago_lock_quantity; //旧的商品良品库存锁定数量
        //     $osld_goo_datas[$osld_in_key]['old_priority_number'] = $find_in_wago_data->wago_priority_stock_number; //旧的商品优先库存数量
        //     $osld_goo_datas[$osld_in_key]['old_priority_lock_number'] = $find_in_wago_data->wago_priority_lock_quantity; //旧的商品优先库存锁定数量
        //     $osld_goo_datas[$osld_in_key]['old_unchecked_number'] = $find_in_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量
        //     $osld_goo_datas[$osld_in_key]['new_stock_number'] = $find_in_wago_data->wago_stock_number; //新的商品良品库存数量
        //     $osld_goo_datas[$osld_in_key]['new_stock_lock_number'] = $find_in_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
        //     $osld_goo_datas[$osld_in_key]['new_priority_number'] = $find_in_wago_data->wago_priority_stock_number; //新的商品优先库存数量
        //     $osld_goo_datas[$osld_in_key]['new_priority_lock_number'] = $find_in_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
        //     $osld_goo_datas[$osld_in_key]['new_unchecked_number'] = $find_in_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
        //     $osld_goo_datas[$osld_in_key]['osld_update_time'] = date('Y-m-d H:i:s'); //更新时间
        //     $osld_goo_datas[$osld_in_key] = (Object)$osld_goo_datas[$osld_in_key];
        //     $osld_in_key++;
        // }
        // // 库存锁定-出入库记录
        // $oslr_in_res = OutinStockLock::addition(
        //     $user_info, //用户信息
        //     $cg_data['cg_id'], //原始单的关联id
        //     $cg_data['cg_number'], //原始单的关联单号
        //     3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
        //     2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
        //     $cg_data['cg_supplyunit'], //选择的客户id,会员id/单位id
        //     $rk_number, //原始单号
        //     $cg_data['cg_wareid'], //入库的仓库id
        //     $actual_count, //入库总数量
        //     $oslr_type, //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库
        //     ($find_waon->waon_stock_fine_amount + $actual_count), //良品总库存
        //     $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入库
        //     $osld_goo_datas
        // );
        // unset($osld_goo_datas);
        if (!$oure_res) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'商品流水记录更新失败'];
        }

        // 根据供应商id,查找供应商名称
        $chun_unit_name = DB::table('channel_unit')
            ->where('chun_id', $cg_data['cg_supplyunit'])
            ->value('chun_unit_name');
        if ($cg_data['cg_paymentype'] != '3') {
            // 应付
            $createBill = ReceivableBill::create(
                $user_info, //用户信息
                15, //recr_type类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单 7.销售出库单 8非实物开单 9.账单冲红 10订单冲单 11.加盟店订单收款 12.加盟店订单代收13.旧货回收14售后单15采购单16采购退货单17采购款到发货(预付款)18期初账单
                0, //recr_number_id账单的应收账款id
                $cg_data['cg_id'], //recr_original_id与类型所对应的id
                $cg_data['cg_number'], //recr_original_number与类型所对应的单号
                2, //客户类型：1.会员零售 2.来往单位 3.外派门店（加盟店或总店） 4会员零售(工单代收）5接单门店（总店或加盟店）6速电派单7虚拟加盟店
                $cg_data['cg_supplyunit'], //会员id/来往单位id/加盟店id/虚拟加盟店
                $chun_unit_name, //会员姓名/来往单位名称/加盟店名称/虚拟加盟店
                $settlement_price, //结算金额
                '', //结款时间
                $acset_acti_id, //会计科目id
                $settlement_price, //实际金额
                0, //抹零金额
                $money_end,  //状态：1.未核销 2.已核销 3已收款
                1,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                $actual_price, //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                18, //recr_account_type显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单 10订单退款(退货单) 11发票 12价外费 13折扣金额抵货款 14.账单冲红 15.订单冲单16.旧货回收 17售后单18采购单19采购退货单20采购款到发货（预付款）21期初账单22.采购账单
                2, //是否合并代收：1是2否
                $cg_data['create_time'],
                0 //技师是否收钱：0未选择1是2否
            );

            // 生成凭证单据
            $vore_data = WorkOrder::voucherReceipts($user_info, $user_info->adm_shop_id, 3, 0, '', $cg_data['cg_id'], $cg_data['cg_number'], $settlement_price, 0, 0, '', '1', 2, $cg_data['cg_supplyunit'], $chun_unit_name);
            if (!$createBill || !$vore_data) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！03'];
            }
        } else {
            // 生成应付
            $createBill = ReceivableBill::create(
                $user_info, //用户信息
                17, //recr_type类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单 7.销售出库单 8非实物开单 9.账单冲红 10订单冲单 11.加盟店订单收款 12.加盟店订单代收13.旧货回收14售后单15采购单16采购退货单17采购款到发货(预付款)18期初账单
                0, //recr_number_id账单的应收账款id
                $cg_data['cg_id'], //recr_original_id与类型所对应的id
                $cg_data['cg_number'], //recr_original_number与类型所对应的单号
                2, //客户类型：1.会员零售 2.来往单位 3.外派门店（加盟店或总店） 4会员零售(工单代收）5接单门店（总店或加盟店）6速电派单7虚拟加盟店
                $cg_data['cg_supplyunit'], //会员id/来往单位id/加盟店id/虚拟加盟店
                $chun_unit_name, //会员姓名/来往单位名称/加盟店名称/虚拟加盟店
                $settlement_price, //结算金额
                '', //结款时间
                $acset_acti_id, //会计科目id
                $settlement_price, //实际金额
                0, //抹零金额
                $money_end,  //状态：1.未核销 2.已核销 3已收款
                1,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                $actual_price, //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                20, //recr_account_type显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单 10订单退款(退货单) 11发票 12价外费 13折扣金额抵货款 14.账单冲红 15.订单冲单16.旧货回收 17售后单18采购单19采购退货单20采购款到发货（预付款）21期初账单22.采购账单
                2, //是否合并代收：1是2否
                $cg_data['create_time'],
                0 //技师是否收钱：0未选择1是2否
            );

            // 生成凭证单据
            $vore_data = WorkOrder::voucherReceipts($user_info, $user_info->adm_shop_id, 3, 0, '', $cg_data['cg_id'], $cg_data['cg_number'], $settlement_price, 0, 0, '', '1', 2, $cg_data['cg_supplyunit'], $chun_unit_name);
            if (!$createBill || !$vore_data) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！04'];
            }
        }
        $post_data['ware_id'] = $cg_data['cg_wareid'];
        $post_data['new_goods_data'] = $new_goods_data;
        $res = WashOrderBasicService::addGoodPlan($user_info, $post_data);
        if (!$wain_id || !$purchase_res || !$waon_res) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败！05'];
        } else {
            return ['code'=>200, 'msg'=>'入库成功', 'data'=>$return];
        }
    }

    /**
     * delivery 采购退货单出库
     *
     * @param [type] $user_info     用户信息
     * @param [type] $shop_id       门店id
     * @param [type] $request       提交的数据
     * @param [type] $goods_data    提交的商品数据
     * @param [type] $storage_goods 采购退货单商品数据
     * @param [type] $cg_data       采购退货单数据
     * @param [type] $rk_number     入库单号
     * @return void
     */
    public static function delivery(
        $user_info,
        $shop_id,
        $request,
        $goods_data,
        $storage_goods,
        $cg_data,
        $rk_number
    ) {
        $goods_name = '';
        $cw_amount = 0;  //应收总额
        $actual_count = 0; //实际出库总数量
        $osld_out_key = 0;
        foreach ($goods_data as $key => $value) {
            if (!isset($storage_goods[$value['goods_id']])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'无法出库非本退货单商品'];
            }

            $temp_storage_goods = $storage_goods[$value['goods_id']];

            if ($value['num'] + $temp_storage_goods['ruku_num'] > $temp_storage_goods['goods_num']) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'出库数量不可超过入库数量'];
            }

            $temp_storage_goods['company_id']               = $user_info->adm_cid;
            $temp_storage_goods['stgo_superior_shop_id']    = $shop_id;
            $temp_storage_goods['stgo_shop_id']             = $user_info->adm_shop_id;
            $temp_storage_goods['relation_number']          = $rk_number;               //单号
            $temp_storage_goods['creator']                  = $user_info->adm_name;     //创建人
            $temp_storage_goods['create_time']              = date('Y-m-d H:i:s');      //创建时间
            $temp_storage_goods['ruku_num']                 = 0 - $value['num'];        //数量
            // 添加商品表
            $stgo_id = Db::table('storage_goods')->insertGetId($temp_storage_goods);
            // 变更出库数量 和到货时间，并将库存减上去
            $edit_res = DB::table('storage_goods')
                ->where('relation_number', $request['cg_number'])
                ->where('goods_id', $value['goods_id'])
                ->decrement('ruku_num', $value['num']);
            // 更改仓位库存数量
            // 判断当前仓位库存数量是否够减
            $find_wafr_all_stock = DB::table('warehouse_freight')
                ->where('wafr_shop_id', $user_info->adm_shop_id)
                ->where('wafr_id', $value['wafr_id'])
                ->value('wafr_all_stock');
            $wafr_all_stock = $find_wafr_all_stock - $value['num'];
            if ($wafr_all_stock < 0) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'当前商品库存数量不足！'];
            }
            $wafr_res = DB::table('warehouse_freight')
                ->where('wafr_shop_id', $user_info->adm_shop_id)
                ->where('wafr_id', $value['wafr_id'])
                ->decrement('wafr_all_stock', $value['num'], ['wafr_update_time' => date('Y-m-d H:i:s')]);
            if (!$edit_res || !$stgo_id || !$wafr_res) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'商品出库失败'];
            }

            $goods_name = $goods_name . $temp_storage_goods['goods_name'] . $temp_storage_goods['goods_number'];
            $cw_amount = $cw_amount + ((float)$temp_storage_goods['univalence'] * (int)$value['num']); //总金额
            $actual_count -= $value['num']; //实际出库总数量

            $goo_actual_count[$value['goods_id']] = $value['num']; //商品id对应的实际出库的数量
            $goo_actual_id[] = $value['goods_id'];
            $goo_inventory[] = 1;

            // 出入库记录需要
            $oure_goods_id[$value['goods_id']] = $value['goods_id']; //出入库商品id
            if (isset($oure_goods_quantity[$value['goods_id']])) {
                $oure_goods_quantity[$value['goods_id']] += $value['num']; //出入库商品数量
            } else {
                $oure_goods_quantity[$value['goods_id']] = $value['num']; //出入库商品数量
            }
            $oure_goods_inventory[$value['goods_id']] = 1; //出入库商品类型，类型1良品2优先

            // 库存锁定-出入库记录表【新增21.06.25】
            $osld_goo_datas[$osld_out_key]['goo_waon_class'] = $cg_data['cg_waon_class']; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
            $osld_goo_datas[$osld_out_key]['goo_id'] = $value['goods_id']; //商品id
            $osld_goo_datas[$osld_out_key]['goo_number'] = $value['num']; //商品数量
            $osld_goo_datas[$osld_out_key]['goo_out_in_type'] = 1; //出入库类型：1出库2入库3锁定4取消锁定
            $osld_goo_datas[$osld_out_key]['goo_inventory'] = 1; //类型1良品2优先3待检测
            // 查询仓库商品库存数量
            $find_in_wago_data = DB::table('warehouse_goods')
                ->where('wago_ware_id', $cg_data['cg_wareid'])
                ->where('wago_class', $cg_data['cg_waon_class'])
                ->where('wago_goo_id', $value['goods_id'])
                ->select('wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                ->first();
            $osld_goo_datas[$osld_out_key]['old_stock_number'] = $find_in_wago_data->wago_stock_number; //旧的商品良品库存数量
            $osld_goo_datas[$osld_out_key]['old_stock_lock_number'] = $find_in_wago_data->wago_lock_quantity; //旧的商品良品库存锁定数量
            $osld_goo_datas[$osld_out_key]['old_priority_number'] = $find_in_wago_data->wago_priority_stock_number; //旧的商品优先库存数量
            $osld_goo_datas[$osld_out_key]['old_priority_lock_number'] = $find_in_wago_data->wago_priority_lock_quantity; //旧的商品优先库存锁定数量
            $osld_goo_datas[$osld_out_key]['old_unchecked_number'] = $find_in_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量
            $osld_goo_datas[$osld_out_key]['new_stock_number'] = $find_in_wago_data->wago_stock_number - $value['num']; //新的商品良品库存数量
            $osld_goo_datas[$osld_out_key]['new_stock_lock_number'] = $find_in_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
            $osld_goo_datas[$osld_out_key]['new_priority_number'] = $find_in_wago_data->wago_priority_stock_number; //新的商品优先库存数量
            $osld_goo_datas[$osld_out_key]['new_priority_lock_number'] = $find_in_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
            $osld_goo_datas[$osld_out_key]['new_unchecked_number'] = $find_in_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
            $osld_goo_datas[$osld_out_key]['osld_update_time'] = date('Y-m-d H:i:s'); //更新时间
            $osld_goo_datas[$osld_out_key] = (Object)$osld_goo_datas[$osld_out_key];
            $osld_out_key++;

            // 仓位商品出入库表
            $value['wfog_primary_id'] = $stgo_id; //关联商品表主键id
            $value['wfog_type'] = 2; //关联类型：1采购入库
            $value['wfog_outin_type'] = 1; //出入库类型：1出库2入库
            // [仓位id]，用于判断仓位是否有库存同一商品选择多次
            if (isset($freight_goods_data[$value['wafg_id']][$value['goods_id']])) {
                $freight_goods_data[$value['wafg_id']][$value['goods_id']]['num'] += $value['num'];
            } else {
                $freight_goods_data[$value['wafg_id']][$value['goods_id']] = (array)$value;
            }
            $wafr_id[] = $value['wafr_id'];
        }
        // 出库单数组
        $ruku_data['company_id'] = $user_info->adm_cid;             //公司id
        $ruku_data['rk_superior_shop_id'] = $shop_id;               //所属总店id
        $ruku_data['rk_shop_id'] = $user_info->adm_shop_id;         //所属门店id
        $ruku_data['rk_number'] = $rk_number;                       //入库单号
        $ruku_data['cg_number'] = $cg_data['cg_number'];            //采购单号
        $ruku_data['rk_wareid'] = $cg_data['cg_wareid'];            //仓库id
        $ruku_data['rk_waon_class'] = $cg_data['cg_waon_class'];    //仓库类别
        $ruku_data['rk_state'] = 5;                                 //入库单状态，1 待入库   3 待审核  4 驳回  5 已完成  8 作废
        $ruku_data['rk_type']  = 2;                                 //采购退货
        $ruku_data['rk_creator'] = $user_info->adm_name;            //创建人
        $ruku_data['create_time'] = date('Y-m-d H:i:s');            //创建时间
        $ruku_data['rk_userid'] = $user_info->adm_id;               //创建人id
        $ruku_data['rk_inputid'] = $user_info->adm_id;              //入库人id
        $ruku_data['rk_remarks'] = (string) $request['rk_remark'];            //入库备注
        $ruku_data['supplyunit'] = $cg_data['cg_supplyunit'];       //供应商
        $ruku_data['arrival_time'] = date('Y-m-d H:i:s');           //到货时间
        $ruku_data['rk_waretype'] = 1;                              //入库类型 1 入库 2 退货 3 代发 4 换货
        $ruku_data['rk_amount'] = $cw_amount;                       //入库金额
        // 添加出库单
        $wain_id = Db::table('ware_inorder')->insertGetId($ruku_data);

        $edit_cgdata['cg_state'] = 11; //采购单状态：1.审核中 2.财务审核 3.驳回编辑5.未入库 6.未出库 8.部分入库 11.完成 ( 9.待结算10.待审核) 12.确认完成 14.已封账 15.申请终止17.终止 18.代发采购19.修正中
        $edit_cgdata['dh_time']  = date('Y-m-d H:i:s');
        $edit_cgdata['edit_time'] = date('Y-m-d H:i:s');
        // 更新采购表
        $purchase_res = DB::table('purchase_order')
            ->where('cg_number', $request['cg_number'])
            ->update($edit_cgdata);

        // 2. 查询仓库的库存数量
        $find_waon = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $cg_data['cg_wareid'])
            ->where('waon_class', $cg_data['cg_waon_class'])
            ->select('waon_id', 'waon_all_amount', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount')
            ->first();
        // 更改仓库库存总数量
        $waon_data['waon_all_amount'] = $find_waon->waon_all_amount + $actual_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::addition(
            $user_info, //用户信息
            $cg_data['cg_id'], //原始单的关联id
            $cg_data['cg_number'], //原始单的关联单号
            3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
            2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            $cg_data['cg_supplyunit'], //选择的客户id,会员id/单位id
            $rk_number, //原始单号，旧货回收单单号
            0, //入库仓库id
            $cg_data['cg_wareid'], //出库仓库id
            abs($actual_count), //出库的商品总数量
            2, //类型 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, //待检测总库存
            1, //出入库类型：1出库，2入库
            $cg_data['cg_waon_class'], //仓库类别
            $oure_goods_id, //商品id
            $oure_goods_quantity, //商品数量
            $oure_goods_inventory //出库类型1良品2优先
        );
        // 库存锁定-出入库记录
        $oslr_out_res = OutinStockLock::addition(
            $user_info, //用户信息
            $cg_data['cg_id'], //原始单的关联id
            $cg_data['cg_number'], //原始单的关联单号
            3, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
            2, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            $cg_data['cg_supplyunit'], //选择的客户id,会员id/单位id
            $rk_number, //原始单号
            $cg_data['cg_wareid'], //入库的仓库id
            abs($actual_count), //入库总数量
            17, //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单16采购入库17采购退货出库
            ($find_waon->waon_stock_fine_amount + $actual_count), //良品总库存
            $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入库
            $osld_goo_datas
        );
        unset($osld_goo_datas);
        if (!$oure_res || !$oslr_out_res) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'商品流水记录更新失败'];
        }
        // 仓库库存调整
        foreach ($freight_goods_data as $wafg_id => $wafg_id_value) {
            foreach ($wafg_id_value as $goo_inventory => $goo_value) {
                $ware_id[$wafg_id] = $cg_data['cg_wareid'];
                $wafg_goo_id[$wafg_id] = $goo_value['goods_id'];
                $wafg_goo_quantity[$wafg_id] = $goo_value['num'];
                $wafg_goo_class[$wafg_id] = $cg_data['cg_waon_class'];
                $wafg_wago_id[$wafg_id] = $goo_value['wago_id']; //仓库商品id
                $wafg_wafr_id[$wafg_id] = $goo_value['wafr_id']; //仓位id
                $neaten_wafg_id[] = $wafg_id;
            }
        }
        $wafg_id = array_unique($neaten_wafg_id);
        // 生成订单时锁定库存,锁定商品的良品库存
        $stgo_retrun = WarehouseFreight::outWarehouseAddition(
            $user_info, //用户信息
            $ware_id, //数组，仓库商品id=>仓库id
            $wafg_goo_id, //数组，仓库商品id=>商品id
            $wafg_goo_quantity, //数组，仓库商品id=>商品数量
            $wafg_goo_class, //数组，仓库商品id=>仓库类别
            $wafg_wago_id, //数组，仓位商品id
            $wafg_wafr_id, //数组，仓位商品id=>仓库商品id
            $wafg_id //数组，仓库商品id
        );
        if (!$stgo_retrun) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'出库失败！01'];
        }
        // 生成仓位商品出入库
        $oure_res = WarehouseFreight::outAddition(
            $user_info, //用户信息
            $cg_data,
            $wain_id,
            $rk_number,
            $freight_goods_data
        );
        if (!$oure_res) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'出库失败！02'];
        }

        // 根据供应商id,查找供应商名称
        $chun_unit_name = DB::table('channel_unit')
            ->where('chun_id', $cg_data['cg_supplyunit'])
            ->value('chun_unit_name');

        // 应收应付
        $createBill = ReceivableBill::create(
            $user_info, //用户信息
            16, //recr_type类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单 7.销售出库单 8非实物开单 9.账单冲红 10订单冲单 11.加盟店订单收款 12.加盟店订单代收13.旧货回收14售后单15采购单16采购退货单17采购款到发货(预付款)18期初账单
            0, //recr_number_id账单的应收账款id
            $cg_data['cg_id'], //recr_original_id与类型所对应的id
            $cg_data['cg_number'], //recr_original_number与类型所对应的单号
            2, //客户类型：1.会员零售 2.来往单位 3.外派门店（加盟店或总店） 4会员零售(工单代收）5接单门店（总店或加盟店）6速电派单7虚拟加盟店
            $cg_data['cg_supplyunit'], //会员id/来往单位id/加盟店id/虚拟加盟店
            $chun_unit_name, //会员姓名/来往单位名称/加盟店名称/虚拟加盟店
            $cw_amount * 100, //结算金额
            '', //结款时间
            '', //会计科目id
            0, //实际金额
            0, //抹零金额
            1, //状态：1.未核销 2.已核销 3已收款
            1, //应收账单id是否是自己 1.不是 2.是
            '', //备注
            0, //已收金额
            '', //截止时间
            1, //金额正负1正   2负值
            19, //recr_account_type显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单 10订单退款(退货单) 11发票 12价外费 13折扣金额抵货款 14.账单冲红 15.订单冲单16.旧货回收 17售后单18采购单19采购退货单20采购款到发货（预付款）21期初账单22.采购账单
            2, //是否合并代收：1是2否
            $cg_data['create_time'],
            0 //技师是否收钱：0未选择1是2否
        );

        // 生成凭证单据
        $vore_data = WorkOrder::voucherReceipts($user_info, $user_info->adm_shop_id, 5, 0, '', $cg_data['cg_id'], $cg_data['cg_number'], $cg_data['cg_amount'] * 100, 0, 0, '', '1', 2, $cg_data['cg_supplyunit'], $chun_unit_name);

        if (!$wain_id || !$purchase_res || !$waon_res || !$createBill || !$vore_data) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'出库失败3'];
        } else {
            return ['code'=>200, 'msg'=>'success', 'data'=>'出库成功'];
        }
    }

    /**
     * wareRecord 库房记录
     *
     * @param [type] $user_info     用户信息
     * @param [type] $request       提交的数据
     * @param [type] $select_field  查询字段，字符串多个字段用,分开
     * @return void
     */
    public static function wareRecord(
        $user_info,
        $request,
        $select_field
    ) {
        // 查询采购单数据
        $puor_data = DB::table('purchase_order')
            ->where('cg_number', $request['cg_number'])
            ->where('cg_shop_id', $user_info->adm_shop_id)
            ->where('is_del', 1)
            ->select(DB::raw($select_field))
            ->first();
        $puor_data = json_decode(json_encode($puor_data), true);
        if (empty($puor_data)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前采购单不存在'];
        }

        // 查询供货商名称
        $puor_data['supplyunit_name'] = Db::table('channel_unit')
            ->where('chun_id', $puor_data['cg_supplyunit'])
            ->value('chun_unit_name');
        // 获取采购仓库名称
        $puor_data['ware_name'] = DB::table('warehouse')
            ->where('ware_id', $puor_data['cg_wareid'])
            ->value('ware_name');

        // 查询采购的商品
        $storage_goods = DB::table('storage_goods as stgo')
            ->leftjoin('goods as goo', 'goo.goo_id', '=', 'stgo.goods_id')
            ->where('relation_number', $request['cg_number'])
            ->select('goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type as goo_type', 'stgo_stop', 'goo_brse_id', 'goo_class')
            ->get()->toArray();
        $storage_goods = json_decode(json_encode($storage_goods), true);
        // 查询系列数据
        $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        $goods_num = 0;
        foreach ($storage_goods as $key => $value) {
            $goods_num = $value['goods_num'] + $goods_num;
            // 判断系列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) {
                        $storage_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'))) {
                            $storage_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) {
                    $storage_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $storage_goods[$key]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $storage_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $storage_goods[$key]['goo_name'];
                    }
                }
            }
            unset($storage_goods[$key]['goo_class']);
            unset($storage_goods[$key]['goo_brse_id']);
        }
        $puor_data['goods_count'] = $goods_num;

        $puor_number[] = $puor_data['cg_number']; //单号

        // 获取入库单列表
        $wain_data = Db::table('ware_inorder')
            ->where('cg_number', $puor_data['cg_number'])
            ->select('rk_number', 'rk_waretype', 'rk_inputid', 'arrival_time', 'rk_remarks', 'rk_image', 'rk_amount')
            ->get()->toArray();
        $wain_data = json_decode(json_encode($wain_data), true);
        $rk_num = 0;  //采购总数
        // 查询入库单的数据
        foreach ($wain_data as $key => $value) {
            $puor_number[] = $value['rk_number']; //单号
            // 入库人
            $wain_data[$key]['storage_operator'] = Db::table('admin')
                ->where('adm_id', $value['rk_inputid'])
                ->value('adm_name');

            // 获取入库单商品数据
            $ware_goods = DB::table('storage_goods as stgo')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'stgo.goods_id')
                ->where('relation_number', $value['rk_number'])
                ->where('ruku_num', '!=', 0)
                ->select('id as stgo_id', 'goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'edit_time as dh_time', 'company_unit', 'goods_type', 'stgo_stop', 'goo_brse_id', 'goo_class')
                ->get()->toArray();
            $ware_goods = json_decode(json_encode($ware_goods), true);
            $stgo_id = array_column($ware_goods, 'stgo_id');
            // 查询仓位商品出入库表
            $find_wfog_data = DB::table('warehouse_freight_outin_goods as wfog')
                ->leftjoin('warehouse_freight as wafr', 'wafr.wafr_id', '=', 'wfog.wfog_wafr_id')
                ->where('wfog_shop_id', $user_info->adm_shop_id)
                ->whereIn('wfog_primary_id', $stgo_id)
                ->select('wfog_id', 'wfog_wafr_id', 'wfog_primary_id', 'wafr_name')
                ->get()->toArray();
            $find_wfog_data = array_column($find_wfog_data, null, 'wfog_primary_id');
            // 查询系列数据
            $goo_brse_id = array_column($ware_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            $ware_num = 0;
            foreach ($ware_goods as $k => $v) {
                if ($value['rk_waretype'] == 1) {
                    $rk_num = $rk_num + $v['ruku_num'];
                }
                $ware_num = $ware_num + $v['ruku_num'];

                if ($v['dh_time'] != '0000-00-00 00:00:00') {
                    $ware_goods[$k]['dh_time'] = date("Y-m-d", strtotime($v['dh_time']));
                } else {
                    $ware_goods[$k]['dh_time'] = '0000-00-00';
                }
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($v['goo_brse_id'])) {
                        if ($v['goo_class'] == 2) {
                            $ware_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $ware_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($v['goo_class'] == 2) {
                        $ware_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $ware_goods[$k]['goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $ware_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $ware_goods[$k]['goo_name'];
                        }
                    }
                }
                if (isset($find_wfog_data[$v['stgo_id']])) {
                    $ware_goods[$k]['wafr_name'] = $find_wfog_data[$v['stgo_id']]->wafr_name;
                } else {
                    $ware_goods[$k]['wafr_name'] = '';
                }
                unset($ware_goods[$k]['goo_class']);
                unset($ware_goods[$k]['goo_brse_id']);
            }
            $wain_data[$key]['ware_num'] = $ware_num;
            $wain_data[$key]['ware_goods'] = $ware_goods;
        }
        $puor_data['rk_num'] = $rk_num;

        // 获取操作备注
        $note = DB::table('note')
            ->whereIn('note_number', $puor_number)
            ->select('note_number', 'note_content', 'note_time', 'note_type')
            ->orderBy('note_id', 'desc')
            ->get()->toArray();

        return ['code'=>200, 'msg'=>'success', 'data'=>['puor_data'=>$puor_data, 'storage_goods'=>$storage_goods, 'wain_data'=>$wain_data, 'note'=>$note]];
    }

    /**
     * info 查看详情
     *
     * @param [type] $user_info     用户信息
     * @param [type] $request       提交的数据
     * @param [type] $select_field  查询字段，字符串多个字段用,分开
     * @return void
     */
    public static function info(
        $user_info,
        $request,
        $select_field
    ) {
        // 查询采购单数据
        $puor_data = DB::table('purchase_order')
            ->where('cg_number', $request['cg_number'])
            ->where('cg_shop_id', $user_info->adm_shop_id)
            ->where('is_del', 1)
            ->select(DB::raw($select_field))
            ->first();
        $puor_data = json_decode(json_encode($puor_data), true);
        if (empty($puor_data)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前采购单不存在'];
        }

        // 查询供货商名称
        $puor_data['supplyunit_name'] = Db::table('channel_unit')
            ->where('chun_id', $puor_data['cg_supplyunit'])
            ->value('chun_unit_name');
        // 获取采购仓库名称
        $puor_data['ware_name'] = DB::table('warehouse')
            ->where('ware_id', $puor_data['cg_wareid'])
            ->value('ware_name');

        // 查询采购的商品
        $storage_goods = DB::table('storage_goods as stgo')
            ->leftjoin('goods as goo', 'goo.goo_id', '=', 'stgo.goods_id')
            ->where('relation_number', $request['cg_number'])
            ->select('goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type as goo_type', 'stgo_stop', 'goo_brse_id', 'goo_class')
            ->get()->toArray();
        $storage_goods = json_decode(json_encode($storage_goods), true);
        // 查询系列数据
        $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        $goods_num = 0;
        $ruku_num = 0;
        foreach ($storage_goods as $key => $value) {
            $goods_num = $value['goods_num'] + $goods_num;
            $ruku_num = $value['ruku_num'] + $ruku_num;
            // 判断系列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) {
                        $storage_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'))) {
                            $storage_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) {
                    $storage_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $storage_goods[$key]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $storage_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $storage_goods[$key]['goo_name'];
                    }
                }
            }
            unset($storage_goods[$key]['goo_class']);
            unset($storage_goods[$key]['goo_brse_id']);
        }
        $puor_data['goods_count'] = $goods_num;
        // 计算入库数量
        $ruku_data = Db::table('ware_inorder')
            ->where('cg_number', $request['cg_number'])
            ->where('rk_type', 1)
            ->select('rk_number')
            ->get()->toArray();
        $ruku_data = json_decode(json_encode($ruku_data), true);

        unset($ruku_data);
        $puor_data['ruku_num'] = $ruku_num;
        $puor_number[] = $puor_data['cg_number']; //单号

        // 获取操作备注
        $note = DB::table('note')
            ->whereIn('note_number', $puor_number)
            ->select('note_number', 'note_content', 'note_time', 'note_type')
            ->orderBy('note_id', 'desc')
            ->get()->toArray();

        return ['code'=>200, 'msg'=>'success', 'data'=>['puor_data'=>$puor_data, 'storage_goods'=>$storage_goods, 'note'=>$note]];
    }
}
