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

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\Push\PushMessageController;
use App\Http\Models\Api\Warehouse;
use App\Http\Models\Services\ImageUpload;

class WarehouseFreight extends Model
{
    /**
     * [warehouseAddition 仓库商品]
     * @param  [type]  $user_info           [用户信息]
     * @param  [type]  $cg_data             [采购单相关数据]
     * @param  [type]  $goods_id            [商品id]
     * @param  [type]  $freight_goods_data  [仓位商品出入库数据]
     * @param  [type]  $ware_goods_data  [仓库商品入库数据]
     * @param  [type]  $wafr_id             [仓位id]
     * @return [type]                       [description]
     */
    public static function warehouseAddition(
        $cg_data,
        $goods_id,
        $freight_goods_data,
        $ware_goods_data,
        $wafr_id
    ) {
        // 4.2 查询仓库商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $cg_data['cg_wareid'])
            ->where('wago_class', $cg_data['cg_waon_class'])
            ->whereIn('wago_goo_id', $goods_id)
            ->select('wago_id', 'wago_goo_id', 'wago_freight_stock_number', 'wago_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 = '';//仓位良品库存数量
            $wago_stock_number_sql = '';//仓库良品库存总数量（仓库+仓位）
            $update_time_sql = '';
            $ids = '';
            foreach ($warehouse_goods as $key => $value) {
                // 要更改的商品库存数量
                $stock_number = $value['wago_freight_stock_number'] + $ware_goods_data[$value['wago_goo_id']];
                $wago_stock_number = $value['wago_stock_number'] + $ware_goods_data[$value['wago_goo_id']];
                // 更改仓位商品库存数量
                $stock_number_sql = $stock_number_sql . ' WHEN ' . $value['wago_id'];
                $stock_number_sql = $stock_number_sql . ' THEN ' . $stock_number;
                // 更改仓库商品库存数量
                $wago_stock_number_sql = $wago_stock_number_sql . ' WHEN ' . $value['wago_id'];
                $wago_stock_number_sql = $wago_stock_number_sql . ' THEN ' . $wago_stock_number;
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value['wago_id'];
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

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

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

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

            if (!empty($stock_number_sql)) {
                $sql = $sql . ' `wago_freight_stock_number`=  CASE `wago_id` ' . $stock_number_sql . ' END,';
                $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $wago_stock_number_sql . ' END,';
                $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $update_time_sql . ' END';
                $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
                $ware_edit_res = DB::update($sql);
            } else {
                $ware_edit_res = true;
            }
        }
        if (empty($ware_goods_data)) {
            $ware_add_res = true;
        } else {
            // 4.5 仓库商品表中没有的商品，新增仓库商品
            foreach ($ware_goods_data as $key => $value) {
                $ware_add_data['wago_ware_id'] = $cg_data['cg_wareid'];
                $ware_add_data['wago_class'] = $cg_data['cg_waon_class'];
                $ware_add_data['wago_goo_id'] = $key;
                $ware_add_data['wago_freight_stock_number'] = $value;
                $ware_add_data['wago_stock_number'] = $value;
                $ware_add_res = DB::table('warehouse_goods')->insertGetId($ware_add_data);
                $wago_id[] = $ware_add_res;//仓库商品主键id
            }
        }
        if (!$ware_add_res || !$ware_edit_res) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败'];
        }

        $wafr_id = array_unique($wafr_id);
        // 判断仓位是否存在
        $find_wafr_data = DB::table('warehouse_freight')
            ->whereIn('wafr_id', $wafr_id)
            ->where('wafr_delete', 1)
            ->select('wafr_id', 'wafr_name')
            ->get()->toArray();
        foreach ($find_wafr_data as $key => $value) {
            if (empty($value->wafr_id)) {
                return ['code'=>'500', 'msg'=>'error', 'data'=>'当前仓位不存在！！！'];
            }
        }
        // 查询仓位商品库存数量
        $warehouse_freight_goods = DB::table('warehouse_freight_goods')
            ->whereIn('wafg_wafr_id', $wafr_id)
            ->whereIn('wafg_wago_id', $wago_id)
            ->where('wafg_ware_id', $cg_data['cg_wareid'])
            ->where('wafg_class', $cg_data['cg_waon_class'])
            ->whereIn('wafg_goo_id', $goods_id)
            ->select('wafg_id', 'wafg_wafr_id', 'wafg_wago_id', 'wafg_goo_id', 'wafg_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 {
            $new_freight_goods = [];//仓位商品数据
            foreach ($warehouse_freight_goods as $key => $value) {
                $new_freight_goods[$value['wafg_wafr_id']][$value['wafg_goo_id']] = $value;
            }
            // 4.4 仓位商品表中已存在的商品，更改库存数量，整理更改SQL语句
            $sql = 'UPDATE `faster_warehouse_freight_goods` SET ';
            $stock_number_sql = '';//仓位良品库存数量
            $update_time_sql = '';
            $ids = '';
            foreach ($freight_goods_data as $wafr_id => $wafr_id_value) {
                foreach ($wafr_id_value as $goo_id => $goo_value) {
                    if (isset($new_freight_goods[$wafr_id][$goo_id])) {
                        $temp_data = $new_freight_goods[$wafr_id][$goo_id];
                        // 要更改的商品库存数量
                        $stock_number = $goo_value['num'] + $temp_data['wafg_stock_number'];
                        // 更改仓位商品库存数量
                        $stock_number_sql = $stock_number_sql . ' WHEN ' . $temp_data['wafg_id'];
                        $stock_number_sql = $stock_number_sql . ' THEN ' . $stock_number;
                        // 更改时间
                        $update_time_sql = $update_time_sql . ' WHEN ' . $temp_data['wafg_id'];
                        $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';
    
                        $ids = $ids . $temp_data['wafg_id'] . ',';
    
                        // 删除已更改的商品数据
                        unset($freight_goods_data[$wafr_id][$goo_id]);
                    }
                }
                if (empty($freight_goods_data[$wafr_id])) {
                    unset($freight_goods_data[$wafr_id]);//删除空数组
                }
            }

            if (!empty($stock_number_sql)) {
                $sql = $sql . ' `wafg_stock_number`=  CASE `wafg_id` ' . $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);
            } else {
                $wafg_edit_res = true;
            }
        }
        if (empty($freight_goods_data)) {
            $wafg_add_res = true;
        } else {
            foreach ($freight_goods_data as $wafr_id => $wafr_id_value) {
                foreach ($wafr_id_value as $goo_id => $goo_value) {
                    $wafg_data['wafg_wafr_id'] = $goo_value['wafr_id'];
                    // 根据仓库id,仓库类别和商品id,查询对应的仓库商品主键id
                    $wago_id = DB::table('warehouse_goods')
                        ->where('wago_ware_id', $cg_data['cg_wareid'])
                        ->where('wago_class', $cg_data['cg_waon_class'])
                        ->where('wago_goo_id', $goo_value['goods_id'])
                        ->value('wago_id');
                    $wafg_data['wafg_wago_id'] = $wago_id;
                    $wafg_data['wafg_ware_id'] = $cg_data['cg_wareid'];
                    $wafg_data['wafg_class'] = $cg_data['cg_waon_class'];
                    $wafg_data['wafg_goo_id'] = $goo_value['goods_id'];
                    $wafg_data['wafg_stock_number'] = $goo_value['num'];
                    $wafg_add_res = DB::table('warehouse_freight_goods')->insertGetId($wafg_data);
                }
            }
        }
        if ($wafg_add_res && $wafg_edit_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'操作成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'操作失败'];
        }
    }

    /**
     * [addition 仓位商品出入库]
     * @param  [type]  $user_info           [用户信息]
     * @param  [type]  $cg_data             [采购单相关数据]
     * @param  [type]  $rk_id               [入库id]
     * @param  [type]  $rk_number           [入库单号]
     * @param  [type]  $freight_goods_data  [仓位商品出入库数据]
     * @return [type]                       [description]
     */
    public static function addition(
        $user_info,
        $cg_data,
        $rk_id,
        $rk_number,
        $freight_goods_data
    ) {
        $n = 0;
        foreach ($freight_goods_data as $wafr_id => $wafr_id_value) {
            foreach ($wafr_id_value as $key => $value) {
                $wfog_add_data[$n]['wfog_shop_id'] = $user_info->adm_shop_id;//门店id
                $wfog_add_data[$n]['wfog_ware_id'] = $cg_data['cg_wareid'];//仓库id
                // 根据仓库id,仓库类别和商品id查询对应的仓库商品主键id
                $wago_id = 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'])
                    ->value('wago_id');
                $wfog_add_data[$n]['wfog_wago_id'] = $wago_id;//仓库商品主键id
                $wfog_add_data[$n]['wfog_wafr_id'] = $value['wafr_id'];//仓位id
                // 根据仓位id,仓库商品主键id,仓库id,仓库类别和商品id查询仓位商品id
                $wafg_id = DB::table('warehouse_freight_goods')
                    ->where('wafg_wafr_id', $value['wafr_id'])
                    ->where('wafg_wago_id', $wago_id)
                    ->where('wafg_ware_id', $cg_data['cg_wareid'])
                    ->where('wafg_class', $cg_data['cg_waon_class'])
                    ->where('wafg_goo_id', $value['goods_id'])
                    ->value('wafg_id');
                $wfog_add_data[$n]['wfog_wafg_id'] = $wafg_id;//仓位商品主键id
                $wfog_add_data[$n]['wfog_type'] = $value['wfog_type'];//关联类型：1采购入库
                $wfog_add_data[$n]['wfog_original_id'] = $rk_id;//原始单id
                $wfog_add_data[$n]['wfog_original_number'] = $rk_number;//原始单号
                $wfog_add_data[$n]['wfog_primary_id'] = $value['wfog_primary_id'];//关联商品表主键id
                $wfog_add_data[$n]['wfog_goo_id'] = $value['goods_id'];//关联商品表主键id
                $wfog_add_data[$n]['wfog_outin_type'] = $value['wfog_outin_type'];//出入库类型：1出库2入库
                $wfog_add_data[$n]['wfog_stock_amount'] = $value['num'];//商品数量
                $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'=>'操作失败'];
        }
    }

    /**
     * [warehouseAddition 仓库商品]
     * @param  [type]  $user_info           [用户信息]
     * @param  [type]  $cg_data             [采购单相关数据]
     * @param  [type]  $goods_id            [商品id]
     * @param  [type]  $freight_goods_data  [仓位商品出入库数据]
     * @param  [type]  $wafr_id             [仓位id]
     * @return [type]                       [description]
     */
    public static function outWarehouseAddition(
        $user_info,
        $ware_id,
        $wafg_goo_id,
        $wafg_goo_quantity,
        $wafg_goo_class,
        $wafg_wago_id,
        $wafg_wafr_id,
        $wafg_id
    ) {
        $warehouse_freight_goods = DB::table('warehouse_freight_goods')
            ->whereIn('wafg_id', $wafg_id)
            ->get(['wafg_id', 'wafg_wafr_id', 'wafg_wago_id', 'wafg_ware_id', 'wafg_class', 'wafg_goo_id', 'wafg_stock_number', 'wafg_priority_stock_number'])
            ->toArray();
        $warehouse_freight_goods_wago = array_column($warehouse_freight_goods, null, 'wafg_id');
        $wafg_id_quantity = [];
        foreach ($wafg_id as $key => $value) {
            $data['goo_quantity'] = $wafg_goo_quantity[$value];//商品数量
            $data['wago_class'] = $wafg_goo_class[$value];//仓库类别
            $data['ware_id'] = $ware_id[$value];//仓库id
            $data['wafg_wago_id'] = $wafg_wago_id[$value];//仓库商品id
            $data['wafg_wafr_id'] = $wafg_wafr_id[$value];//仓位id
            $data['wafg_id'] = $value;//仓位商品id
            $wafg_id_quantity[] = $data;
            unset($data);
        }
        $sql = 'UPDATE `faster_warehouse_freight_goods` SET ';
        $stock_number_sql = '';
        $update_time_sql = '';
        $ids = '';
        foreach ($wafg_id_quantity as $goo_id => $value) {
            // 查询仓库商品表仓位的库存数量
            $find_wogo_data = DB::table('warehouse_goods')
                ->where('wago_id', $value['wafg_wago_id'])
                ->select('wago_freight_stock_number', 'wago_stock_number')
                ->first();
            // 判断库存数量
            $surplus_quantity = $warehouse_freight_goods_wago[$value['wafg_id']]->wafg_stock_number - $value['goo_quantity'];
            if ($surplus_quantity < 0) {
                return ['code'=> 500, 'msg'=>'error', 'data'=>'仓位内库存数量不足'];
            }
            // 库存数量减少
            $stock_number_sql = $stock_number_sql.' WHEN '.$value['wafg_id'].' THEN `wafg_stock_number` - '.$value['goo_quantity'];
            $update_time_sql = $update_time_sql.' WHEN '.$value['wafg_id'].' THEN "'.date('Y-m-d H:i:s').'"'; // 更改时间

            // 仓位的良品库存数量减少
            $edit_data['wago_freight_stock_number'] = $find_wogo_data->wago_freight_stock_number - $value['goo_quantity'];
            $edit_data['wago_stock_number'] = $find_wogo_data->wago_stock_number - $value['goo_quantity'];
            $edit_data['wago_update_time'] = date('Y-m-d H:i:s');
            // 更改仓库商品表的仓位数量
            $update_wago_res = DB::table('warehouse_goods')
                ->where('wago_id', $value['wafg_wago_id'])
                ->update($edit_data);
            if (!$update_wago_res) {
                return ['code'=>500, 'msg'=>'success', 'data'=>'操作失败'];
            }
            $ids = $ids . $value['wafg_id'] . ',';
        }

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

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

    /**
     * [addition 仓位商品出入库]
     * @param  [type]  $user_info           [用户信息]
     * @param  [type]  $cg_data             [采购单相关数据]
     * @param  [type]  $rk_id               [入库id]
     * @param  [type]  $rk_number           [入库单号]
     * @param  [type]  $freight_goods_data  [仓位商品出入库数据]
     * @return [type]                       [description]
     */
    public static function outAddition(
        $user_info,
        $cg_data,
        $rk_id,
        $rk_number,
        $freight_goods_data
    ) {
        $n = 0;
        foreach ($freight_goods_data as $wafg_id => $wafg_id_value) {
            foreach ($wafg_id_value as $key => $value) {
                $wfog_add_data[$n]['wfog_shop_id'] = $user_info->adm_shop_id;//门店id
                $wfog_add_data[$n]['wfog_ware_id'] = $cg_data['cg_wareid'];//仓库id
                $wfog_add_data[$n]['wfog_wago_id'] = $value['wago_id'];//仓库商品主键id
                $wfog_add_data[$n]['wfog_wafr_id'] = $value['wafr_id'];//仓位id
                $wfog_add_data[$n]['wfog_wafg_id'] = $value['wafg_id'];//仓位商品主键id
                $wfog_add_data[$n]['wfog_type'] = $value['wfog_type'];//关联类型：1采购入库
                $wfog_add_data[$n]['wfog_original_id'] = $rk_id;//原始单id
                $wfog_add_data[$n]['wfog_original_number'] = $rk_number;//原始单号
                $wfog_add_data[$n]['wfog_primary_id'] = $value['wfog_primary_id'];//关联商品表主键id
                $wfog_add_data[$n]['wfog_goo_id'] = $value['goods_id'];//关联商品表主键id
                $wfog_add_data[$n]['wfog_outin_type'] = $value['wfog_outin_type'];//出入库类型：1出库2入库
                $wfog_add_data[$n]['wfog_stock_amount'] = $value['num'];//商品数量
                $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'=>'操作失败'];
        }
    }
}
