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

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class Stocktake extends Model
{
    /**
     * [warehouseAddition 盘库单仓库商品]
     * @param  [type]  $ware_id                 [仓库id]
     * @param  [type]  $waon_class              [仓库类别]
     * @param  [type]  $goods_id                [商品id]
     * @param  [type]  $goo_stock_number        [良品库存数量]
     * @param  [type]  $goo_priority_number     [优先库存数量]
     * @param  [type]  $goo_unchecked_number    [待检测库存数量]
     * @return [type]                           [description]
     */
    public static function stocktakeWarehouseAddition(
        $ware_id,
        $waon_class,
        $goods_id,
        $goo_stock_number,
        $goo_priority_number,
        $goo_unchecked_number
    ) {
        // 4.2 查询仓库商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $ware_id)
            ->where('wago_class', $waon_class)
            ->whereIn('wago_goo_id', $goods_id)
            ->select('wago_id', 'wago_goo_id', 'wago_freight_stock_number', 'wago_freight_priority_stock_number', 'wago_freight_unchecked_stock_number', 'wago_stock_number', 'wago_priority_stock_number', 'wago_unchecked_stock_number')
            ->get()->toArray();
        $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 = '';//仓位良品库存数量
            $priority_stock_number_sql = '';//仓位优先库存数量
            $unchecked_stock_number_sql = '';//仓位待检测库存数量
            $wago_stock_number_sql = '';//仓库良品库存总数量（仓库+仓位）
            $priority_stock_amount_sql = '';//仓库优先锁定总数量（仓库+仓位）
            $unchecked_stock_amount_sql = '';//仓库待检测库存总数量（仓库+仓位）
            $update_time_sql = '';
            $ids = '';
            foreach ($warehouse_goods as $key => $value) {
                // 要更改仓位商品库存数量
                $stock_number = $value['wago_freight_stock_number'] + $goo_stock_number[$value['wago_goo_id']];//仓位良品库存数量
                $priority_stock_number = $value['wago_freight_priority_stock_number'] + $goo_priority_number[$value['wago_goo_id']];//仓位优先库存数量
                $unchecked_stock_number = $value['wago_freight_unchecked_stock_number'] + $goo_unchecked_number[$value['wago_goo_id']];//仓位待检测库存数量

                // 要更改仓库商品总的库存数量
                $wago_stock_number = $value['wago_stock_number'] + $goo_stock_number[$value['wago_goo_id']];//良品库存数量（仓库+仓位）
                $priority_stock_amount = $value['wago_priority_stock_number'] + $goo_priority_number[$value['wago_goo_id']];//优先库存数量（仓库+仓位）
                $unchecked_stock_amount = $value['wago_unchecked_stock_number'] + $goo_unchecked_number[$value['wago_goo_id']];//待检测数量（仓库+仓位）
                if ($stock_number < 0) {
                    $stock_number = 0;
                }
                if ($priority_stock_number < 0) {
                    $priority_stock_number = 0;
                }
                if ($unchecked_stock_number < 0) {
                    $unchecked_stock_number = 0;
                }
                // 更改仓位商品库存数量
                $stock_number_sql = $stock_number_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $stock_number;
                // 更改优先库存数量
                $priority_stock_number_sql = $priority_stock_number_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $priority_stock_number;
                // 更改待检测库存数量
                $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $unchecked_stock_number;

                // 更改良品库存数量（仓库+仓位）
                $wago_stock_number_sql = $wago_stock_number_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $wago_stock_number;
                // 更改优先库存数量（仓库+仓位）
                $priority_stock_amount_sql = $priority_stock_amount_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $priority_stock_amount;
                // 更改待检测数量（仓库+仓位）
                $unchecked_stock_amount_sql = $unchecked_stock_amount_sql . ' WHEN ' . $value['wago_id'] . ' THEN ' . $unchecked_stock_amount;
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value['wago_id'] . ' THEN "' . date('Y-m-d H:i:s') . '"';

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

                $wago_id[] = $value['wago_id'];//仓库商品主键id

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

            $sql = $sql . ' `wago_freight_stock_number`=  CASE `wago_id` ' . $stock_number_sql . ' END,';
            $sql = $sql . ' `wago_freight_priority_stock_number`=  CASE `wago_id` ' . $priority_stock_number_sql . ' END,';
            $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $wago_stock_number_sql . ' END,';
            $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $priority_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);
        }
        if (empty($goo_stock_number)) {
            $ware_add_res = true;
        } else {
            // 4.5 仓库商品表中没有的商品，提示
            foreach ($goo_stock_number as $key => $value) {
                $find_goods_encode = DB::table('goods')
                    ->where('goo_id', $key)
                    ->where('goo_state', 1)
                    ->where('goo_delete', 1)
                    ->value('goo_goods_encode');
                return ['code'=>500, 'msg'=>'error', 'data'=>'检索编码：（'.$find_goods_encode.'）不在我的仓库--库存列表，只能进行采购或调拨！！！'];
            }
        }
        if ($ware_edit_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'操作成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'操作失败'];
        }
    }

    /**
     * [warehouseAddition 盘库单仓位商品]
     * @param  [type]  $ware_id                 [仓库id]
     * @param  [type]  $waon_class              [仓库类别]
     * @param  [type]  $goods_id                [商品id]
     * @param  [type]  $goo_stock_number        [良品库存数量]
     * @param  [type]  $goo_priority_number     [优先库存数量]
     * @param  [type]  $goo_unchecked_number    [待检测库存数量]
     * @param  [type]  $wafr_id                 [仓位id]
     * @return [type]                           [description]
     */
    public static function stocktakeWarehouseFreight(
        $ware_id,
        $waon_class,
        $goods_id,
        $goo_stock_number,
        $goo_priority_number,
        $goo_unchecked_number,
        $wafr_id
    ) {
        // 4.2 查询仓库商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $ware_id)
            ->where('wago_class', $waon_class)
            ->whereIn('wago_goo_id', $goods_id)
            ->select('wago_id', 'wago_goo_id', 'wago_freight_stock_number', 'wago_freight_priority_stock_number', 'wago_freight_unchecked_stock_number', 'wago_stock_number', 'wago_priority_stock_number', 'wago_unchecked_stock_number')
            ->get()->toArray();
        $warehouse_goods = json_decode(json_encode($warehouse_goods), true);
        $wago_id = array_column($warehouse_goods, 'wago_id');
        // 判断仓位是否存在
        $find_wafr_id = DB::table('warehouse_freight')
            ->where('wafr_id', $wafr_id)
            ->where('wafr_delete', 1)
            ->value('wafr_id');
        if (empty($find_wafr_id)) {
            return ['code'=>'500', 'msg'=>'error', 'data'=>'当前仓位不存在！！！'];
        }
        // 查询仓位商品库存数量
        $warehouse_freight_goods = DB::table('warehouse_freight_goods')
            ->where('wafg_wafr_id', $wafr_id)
            ->whereIn('wafg_wago_id', $wago_id)
            ->where('wafg_ware_id', $ware_id)
            ->where('wafg_class', $waon_class)
            ->whereIn('wafg_goo_id', $goods_id)
            ->select('wafg_id', 'wafg_wafr_id', 'wafg_wago_id', 'wafg_goo_id', 'wafg_stock_number', 'wafg_priority_stock_number', 'wafg_unchecked_stock_number')
            ->get()->toArray();
        $warehouse_freight_goods = json_decode(json_encode($warehouse_freight_goods), true);
        // 4.3 处理要入库的商品库存数量
        if (empty($warehouse_freight_goods)) {
            $wafg_edit_res = true;
        } else {
            // 4.4 仓位商品表中已存在的商品，更改库存数量，整理更改SQL语句
            $sql = 'UPDATE `faster_warehouse_freight_goods` SET ';
            $stock_number_sql = '';//仓位良品库存数量
            $priority_stock_number_sql = '';
            $unchecked_stock_number_sql = '';
            $update_time_sql = '';
            $ids = '';
            foreach ($warehouse_freight_goods as $key => $value) {
                // 要更改的商品库存数量
                $stock_number = $value['wafg_stock_number'] + $goo_stock_number[$value['wafg_goo_id']];
                $priority_stock_number = $value['wafg_priority_stock_number'] + $goo_priority_number[$value['wafg_goo_id']];
                $unchecked_stock_number = $value['wafg_unchecked_stock_number'] + $goo_unchecked_number[$value['wafg_goo_id']];
                if ($stock_number < 0) {
                    $stock_number = 0;
                }
                if ($priority_stock_number < 0) {
                    $priority_stock_number = 0;
                }
                if ($unchecked_stock_number < 0) {
                    $unchecked_stock_number = 0;
                }
                // 更改仓位商品库存数量
                $stock_number_sql = $stock_number_sql . ' WHEN ' . $value['wafg_id'];
                $stock_number_sql = $stock_number_sql . ' THEN ' . $stock_number;
                // 更改优先库存数量
                $priority_stock_number_sql = $priority_stock_number_sql . ' WHEN ' . $value['wafg_id'];
                $priority_stock_number_sql = $priority_stock_number_sql . ' THEN ' . $priority_stock_number;
                // 更改待检测库存数量
                $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' WHEN ' . $value['wafg_id'];
                $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' THEN ' . $unchecked_stock_number;
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value['wafg_id'];
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

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

                // 更改仓位良品库存数量
                $stock_wafr_res = DB::table('warehouse_freight')
                    ->where('wafr_id', $wafr_id)
                    ->increment('wafr_all_stock', $goo_stock_number[$value['wafg_goo_id']]);
                // 更改仓位优先库存数量
                $priority_wafr_res = DB::table('warehouse_freight')
                    ->where('wafr_id', $wafr_id)
                    ->increment('wafr_priority_all_stock', $goo_priority_number[$value['wafg_goo_id']]);
                // 删除已更改的商品数据
                unset($goo_stock_number[$value['wafg_goo_id']]);
            }

            $sql = $sql . ' `wafg_stock_number`=  CASE `wafg_id` ' . $stock_number_sql . ' END,';
            $sql = $sql . ' `wafg_priority_stock_number`=  CASE `wafg_id` ' . $priority_stock_number_sql . ' END,';
            $sql = $sql . ' `wafg_unchecked_stock_number`=  CASE `wafg_id` ' . $unchecked_stock_number_sql . ' END,';
            $sql = $sql . ' `wafg_update_time`=  CASE `wafg_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `wafg_id` IN (' . trim($ids, ',') . ')';
            $wafg_edit_res = DB::update($sql);
        }
        if (empty($goo_stock_number)) {
            $wafg_edit_res = true;
        } else {
            // 4.5 仓库商品表中没有的商品，提示
            foreach ($goo_stock_number as $key => $value) {
                $find_goods_encode = DB::table('goods')
                    ->where('goo_id', $key)
                    ->where('goo_state', 1)
                    ->where('goo_delete', 1)
                    ->value('goo_goods_encode');
                return ['code'=>500, 'msg'=>'error', 'data'=>'检索编码：（'.$find_goods_encode.'）不在我的仓库--库存列表，只能进行采购或调拨！！！'];
            }
        }
        if ($wafg_edit_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'操作成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'操作失败'];
        }
    }

    /**
     * [addition 添加仓位出入库记录]
     * @param  [type] $user_info            [用户信息]
     * @param  [type] $ware_id              [仓库id]
     * @param  [type] $waon_class           [仓库类别]
     * @param  [type] $wafr_id              [仓位id]
     * @param  [type] $type                 [关联类型：1采购入库2采购退货出库3调拨入库4调拨出库5旧货回收6退货入库7盘库8发货]
     * @param  [type] $original_id          [原始单id]
     * @param  [type] $original_number      [原始单号]
     * @param  [type] $primary_id           [关联商品表主键id]
     * @param  [type] $goo_id               [商品id]
     * @param  [type] $outin_type           [出入库类型：1出库2入库]
     * @param  [type] $stock_amount         [商品数量]
     * @param  [type] $inventory            [库存类型1良品2优先]
     * @return [type]                       [description]
     */
    public static function addition(
        $user_info,
        $ware_id,
        $waon_class,
        $wafr_id,
        $type,
        $original_id,
        $original_number,
        $primary_id,
        $goo_id,
        $outin_type,
        $stock_amount,
        $inventory
    ) {
        $n = 0;
        foreach ($goo_id as $key => $value) {
            $wfog_add_data[$n]['wfog_shop_id'] = $user_info->adm_shop_id;//门店id
            $wfog_add_data[$n]['wfog_ware_id'] = $ware_id;//仓库id
            // 根据仓库id,仓库类别和商品id查询对应的仓库商品主键id
            $wago_id = DB::table('warehouse_goods')
                ->where('wago_ware_id', $ware_id)
                ->where('wago_class', $waon_class)
                ->where('wago_goo_id', $value)
                ->value('wago_id');
            $wfog_add_data[$n]['wfog_wago_id'] = $wago_id;//仓库商品主键id
            $wfog_add_data[$n]['wfog_wafr_id'] = $wafr_id;//仓位id
            // 根据仓位id,仓库商品主键id,仓库id,仓库类别和商品id查询仓位商品id
            $wafg_id = DB::table('warehouse_freight_goods')
                ->where('wafg_wafr_id', $wafr_id)
                ->where('wafg_wago_id', $wago_id)
                ->where('wafg_ware_id', $ware_id)
                ->where('wafg_class', $waon_class)
                ->where('wafg_goo_id', $value)
                ->value('wafg_id');
            $wfog_add_data[$n]['wfog_wafg_id'] = $wafg_id;//仓位商品主键id
            $wfog_add_data[$n]['wfog_type'] = $type;//关联类型：1采购入库
            $wfog_add_data[$n]['wfog_original_id'] = $original_id;//原始单id
            $wfog_add_data[$n]['wfog_original_number'] = $original_number;//原始单号
            $wfog_add_data[$n]['wfog_primary_id'] = $primary_id[$key];//关联商品表主键id
            $wfog_add_data[$n]['wfog_goo_id'] = $value;//关联商品表主键id
            $wfog_add_data[$n]['wfog_outin_type'] = $outin_type;//出入库类型：1出库2入库
            $wfog_add_data[$n]['wfog_stock_amount'] = $stock_amount[$key];//商品数量
            $wfog_add_data[$n]['wfog_stock_type'] = $inventory[$key];//库存类型1良品2优先
            $wfog_add_data[$n]['wfog_adm_id'] = $user_info->adm_id;//操作人id
            $n++;
        }
        $wfog_id = DB::table('warehouse_freight_outin_goods')->insert($wfog_add_data);

        if ($wfog_id) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'操作成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'操作失败'];
        }
    }

    /**
     * [junkaddition 添加仓位出入库记录]
     * @param  [type] $user_info            [用户信息]
     * @param  [type] $ware_id              [仓库id]
     * @param  [type] $waon_class           [仓库类别]
     * @param  [type] $wafr_id              [仓位id]
     * @param  [type] $type                 [关联类型：1采购入库2采购退货出库3调拨入库4调拨出库5旧货回收6退货入库7盘库8发货]
     * @param  [type] $original_id          [原始单id]
     * @param  [type] $original_number      [原始单号]
     * @param  [type] $primary_id           [关联商品表主键id]
     * @param  [type] $goo_id               [商品id]
     * @param  [type] $outin_type           [出入库类型：1出库2入库]
     * @param  [type] $stock_amount         [商品数量]
     * @param  [type] $inventory            [库存类型1良品2优先]
     * @return [type]                       [description]
     */
    public static function junkaddition(
        $user_info,
        $ware_id,
        $waon_class,
        $wafr_id,
        $type,
        $original_id,
        $original_number,
        $primary_id,
        $goo_id,
        $outin_type,
        $stock_amount,
        $inventory
    ) { 

        $wfog_add_data['wfog_shop_id'] = $user_info->adm_shop_id;//门店id
        $wfog_add_data['wfog_ware_id'] = $ware_id;//仓库id
        // 根据仓库id,仓库类别和商品id查询对应的仓库商品主键id
        $wago_id = DB::table('warehouse_goods')
            ->where('wago_ware_id', $ware_id)
            ->where('wago_class', $waon_class)
            ->where('wago_goo_id', $goo_id)
            ->value('wago_id');
        $wfog_add_data['wfog_wago_id'] = $wago_id;//仓库商品主键id
        $wfog_add_data['wfog_wafr_id'] = $wafr_id;//仓位id
        // 根据仓位id,仓库商品主键id,仓库id,仓库类别和商品id查询仓位商品id
        $wafg_id = DB::table('warehouse_freight_goods')
            ->where('wafg_wafr_id', $wafr_id)
            ->where('wafg_wago_id', $wago_id)
            ->where('wafg_ware_id', $ware_id)
            ->where('wafg_class', $waon_class)
            ->where('wafg_goo_id', $goo_id)
            ->value('wafg_id');
        $wfog_add_data['wfog_wafg_id'] = $wafg_id ?: 0;//仓位商品主键id
        $wfog_add_data['wfog_type'] = $type;//关联类型：1采购入库
        $wfog_add_data['wfog_original_id'] = $original_id;//原始单id
        $wfog_add_data['wfog_original_number'] = $original_number;//原始单号
        $wfog_add_data['wfog_primary_id'] = $primary_id;//关联商品表主键id
        $wfog_add_data['wfog_goo_id'] = $goo_id;//关联商品表主键id
        $wfog_add_data['wfog_outin_type'] = $outin_type;//出入库类型：1出库2入库
        $wfog_add_data['wfog_stock_amount'] = $stock_amount;//商品数量
        $wfog_add_data['wfog_stock_type'] = $inventory;//库存类型1良品2优先
        $wfog_add_data['wfog_adm_id'] = $user_info->adm_id;//操作人id
        $wfog_id = DB::table('warehouse_freight_outin_goods')->insert($wfog_add_data);
        if ($wfog_id) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'操作成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'操作失败'];
        }
    }
}
