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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;

// 仓储系统 -- 库存锁定出入库记录
class lockGoodsRecordController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        $search_data = $request->all();

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $list_data = DB::table('outin_stock_lock_details as osld')
            ->leftJoin('outin_stock_lock_record as oslr', 'osld.osld_oure_id', '=', 'oslr.oslr_id')
            ->leftJoin('goods as goo', 'goo.goo_id', '=', 'osld.osld_goo_id')
            ->where('oslr_cid', $user_info->adm_cid)
            ->where('oslr_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($request) { //仓库id
                if (!empty($request['ware_id'])) {
                    $query->where('oslr_ware_id', $request['ware_id']);
                }
            })
            ->where(function ($query) use ($request) { //品牌id
                if (!empty($request['goo_bra_id'])) {
                    $query->where('goo_bra_id', $request['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //出入库类型：1出库2入库3锁定4取消锁定
                if (!empty($search_data['oslr_out_in_type'])) {
                    $query->where('oslr_out_in_type', $search_data['oslr_out_in_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('oslr_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('oslr_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('oslr_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                if (!empty($search_data['osld_waon_class'])) {
                    $query->where('osld_waon_class', $search_data['osld_waon_class']);
                }
            })
            ->where(function ($query) use ($search_data) { //单号
                if (!empty($search_data['oslr_number'])) {
                    $query->where('oslr_number', 'like', '%' . $search_data['oslr_number'] . '%')
                        ->orwhere('oslr_original_correlation_number', 'like', '%' . $search_data['oslr_number'] . '%')
                        ->orwhere('oslr_original_number', 'like', '%' . $search_data['oslr_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //商品名称
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //检索编码
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('goo_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                if (!empty($search_data['oslr_client_type'])) {
                    $query->where('oslr_client_type', $search_data['oslr_client_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //选择的客户id,会员id/单位id
                if (!empty($search_data['oslr_client_id'])) {
                    $query->where('oslr_client_id', $search_data['oslr_client_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //品牌系列id
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            })
            ->select('oslr_number', 'oslr_original_correlation_number', 'oslr_original_number', 'oslr_client_type', 'oslr_client_id', 'oslr_type', 'oslr_ware_id', 'oslr_adm_id', 'oslr_out_in_type', 'goo_name', 'goo_goods_encode', 'goo_id', 'osld_waon_class', 'osld_goo_number', 'osld_out_in_type', 'goo_type', 'osld_type', 'osld_old_stock_number', 'osld_old_stock_lock_number', 'osld_old_priority_number', 'osld_old_priority_lock_number', 'osld_old_unchecked_number', 'osld_new_stock_number', 'osld_new_stock_lock_number', 'osld_new_priority_number', 'osld_new_priority_lock_number', 'osld_new_unchecked_number', 'goo_brse_id', 'goo_bra_name', 'goo_class', 'oslr_create_time')
            ->orderBy('oslr_create_time', 'desc')
            // ->orderBy('oude_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        $list_items = json_decode(json_encode($list_items), true);

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;        //一页显示多少个
        $data_info['data'] = $list_items;                        //返回数据
        $data_info['brse_data'] = []; //品牌系列数据

        if ($data_info['data']) {
            $goo_id = array_column($data_info['data'], 'goo_id');
            $oslr_client_id = array_unique(array_column($data_info['data'], 'oslr_client_id'));
            // 查询商品附属表信息
            $goaf_data = DB::table('goods_affiliate')
                ->where('goaf_shop_id', $user_info->adm_shop_id)
                ->whereIn('goaf_goo_id', $goo_id)
                ->pluck('goaf_another_name', 'goaf_goo_id')
                ->toArray();
            // 查询系统商品属性表信息
            $gosa_data = DB::table('goods_system_affiliate')
                ->where('gosa_shop_id', $user_info->adm_shop_id)
                ->whereIn('gosa_goo_id', $goo_id)
                ->pluck('gosa_another_name', 'gosa_goo_id')
                ->toArray();

            // 查询来往单位
            $channel_data = DB::table('channel_unit')
                ->where('chun_shop_id', $user_info->adm_shop_id)
                ->where('chun_state', '1')
                ->whereIn('chun_id', $oslr_client_id)
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();

            // 查询品牌系列数据
            $goo_brse_id = array_filter(array_unique(array_column($data_info['data'], 'goo_brse_id')));
            if ($goo_brse_id) {
                $data_info['brse_data'] = DB::table('brand_serie')
                    ->whereIn('brse_id', $goo_brse_id)
                    ->select('brse_id', 'brse_name')
                    ->get();
            }

            // 获取出入库记录的仓库id
            $ware_id = array_unique(array_column($data_info['data'], 'oslr_ware_id'));
            // 查询仓库信息
            $find_ware = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->whereIn('ware_id', $ware_id)
                ->pluck('ware_name', 'ware_id')->toArray();
            foreach ($data_info['data'] as $key => $value) {
                if ($value['goo_class'] == 2 && isset($gosa_data[$value['goo_id']]) && !empty($goaf_data[$value['goo_id']])) {
                    $data_info['data'][$key]['goo_name'] = $gosa_data[$value['goo_id']];
                }
                if (isset($goaf_data[$value['goo_id']]) && !empty($goaf_data[$value['goo_id']])) { // 商品别名
                    $data_info['data'][$key]['goo_name'] = $goaf_data[$value['goo_id']];
                }
                if ($value['oslr_client_type'] == 5) { //5运营中心与基础门店
                    $data_info['data'][$key]["oure_client_name"] = DB::table('shop')
                        ->where('shop_id', $value['oslr_client_id'])
                        ->value('shop_store_name');
                } else {
                    if (isset($channel_data[$value['oslr_client_id']])) {
                        $data_info['data'][$key]["oure_client_name"] = $channel_data[$value['oslr_client_id']];
                    } else {
                        $data_info['data'][$key]["oure_client_name"] = '';
                    }
                }
                if ($value['oslr_ware_id']) {
                    $data_info['data'][$key]['oslr_ware_id'] = isset($find_ware[$value['oslr_ware_id']]) ? $find_ware[$value['oslr_ware_id']] : '';
                } else {
                    $data_info['data'][$key]['oslr_ware_id'] = '';
                }
                unset($data_info['data'][$key]['goo_id']);
                unset($data_info['data'][$key]['goo_class']);
                unset($data_info['data'][$key]['oslr_client_id']);
                unset($data_info['data'][$key]['oslr_adm_id']);
                unset($data_info['data'][$key]['oslr_client_id']);
            }
        }

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 导出
    public function export(Request $request)
    {
        $search_data = $request->all();

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $data = DB::table('outin_stock_lock_details as osld')
            ->leftJoin('outin_stock_lock_record as oslr', 'osld.osld_oure_id', '=', 'oslr.oslr_id')
            ->leftJoin('goods as goo', 'goo.goo_id', '=', 'osld.osld_goo_id')
            ->where('oslr_cid', $user_info->adm_cid)
            ->where('oslr_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($request) { //仓库id
                if (!empty($request['ware_id'])) {
                    $query->where('oslr_ware_id', $request['ware_id']);
                }
            })
            ->where(function ($query) use ($request) { //品牌id
                if (!empty($request['goo_bra_id'])) {
                    $query->where('goo_bra_id', $request['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //出入库类型：1出库2入库3锁定4取消锁定
                if (!empty($search_data['oslr_out_in_type'])) {
                    $query->where('oslr_out_in_type', $search_data['oslr_out_in_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('oslr_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('oslr_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('oslr_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                if (!empty($search_data['osld_waon_class'])) {
                    $query->where('osld_waon_class', $search_data['osld_waon_class']);
                }
            })
            ->where(function ($query) use ($search_data) { //单号
                if (!empty($search_data['oslr_number'])) {
                    $query->where('oslr_number', 'like', '%' . $search_data['oslr_number'] . '%')
                        ->orwhere('oslr_original_correlation_number', 'like', '%' . $search_data['oslr_number'] . '%')
                        ->orwhere('oslr_original_number', 'like', '%' . $search_data['oslr_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //商品名称
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //检索编码
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('goo_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                if (!empty($search_data['oslr_client_type'])) {
                    $query->where('oslr_client_type', $search_data['oslr_client_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //选择的客户id,会员id/单位id
                if (!empty($search_data['oslr_client_id'])) {
                    $query->where('oslr_client_id', $search_data['oslr_client_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //品牌系列id
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            })
            ->select('oslr_number', 'oslr_original_correlation_number', 'oslr_original_number', 'oslr_client_type', 'oslr_client_id', 'oslr_type', 'oslr_ware_id', 'oslr_adm_id', 'oslr_out_in_type', 'goo_name', 'goo_goods_encode', 'goo_id', 'osld_waon_class', 'osld_goo_number', 'osld_out_in_type', 'goo_type', 'osld_type', 'osld_old_stock_number', 'osld_old_stock_lock_number', 'osld_old_priority_number', 'osld_old_priority_lock_number', 'osld_old_unchecked_number', 'osld_new_stock_number', 'osld_new_stock_lock_number', 'osld_new_priority_number', 'osld_new_priority_lock_number', 'osld_new_unchecked_number', 'goo_brse_id', 'goo_bra_name', 'goo_class', 'oslr_create_time')
            ->orderBy('oslr_create_time', 'desc')
            // ->orderBy('oude_id', 'desc')
            ->get()->toArray();
        
        if (!empty($data)) {
            // 将对象转化为数组
            $data = json_decode(json_encode($data), true);
            $oslr_client_id = array_unique(array_column($data, 'oslr_client_id'));
            // 查询系列数据
            $goo_brse_id = array_column($data, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            // 查询来往单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $oslr_client_id)
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            $goo_id = array_column($data, 'goo_id');
            // 查询商品附属表信息
            $goaf_data = DB::table('goods_affiliate')
                ->where('goaf_shop_id', $user_info->adm_shop_id)
                ->whereIn('goaf_goo_id', $goo_id)
                ->pluck('goaf_another_name', 'goaf_goo_id')
                ->toArray();
            // 查询系统商品属性表信息
            $gosa_data = DB::table('goods_system_affiliate')
                ->where('gosa_shop_id', $user_info->adm_shop_id)
                ->whereIn('gosa_goo_id', $goo_id)
                ->pluck('gosa_another_name', 'gosa_goo_id')
                ->toArray();
            // 获取出入库记录的仓库id
            $ware_id = array_unique(array_column($data, 'oslr_ware_id'));
            // 查询仓库信息
            $find_ware = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->whereIn('ware_id', $ware_id)
                ->pluck('ware_name', 'ware_id')->toArray();
            $dataarray = array();
            foreach ($data as $key => $value) {
                $dataarray[$key]['oslr_number'] = $value['oslr_number'];
                $dataarray[$key]['oslr_original_correlation_number'] = $value['oslr_original_correlation_number'];
                $dataarray[$key]['oslr_original_number'] = $value['oslr_original_number'];
                if (isset($channel[$value['oslr_client_id']])) {
                    $dataarray[$key]["oure_client_name"] = $channel[$value['oslr_client_id']];
                } else {
                    $dataarray[$key]["oure_client_name"] = '';
                }
                // 检索编码
                $dataarray[$key]['goo_goods_encode'] = "\t" . $value['goo_goods_encode'];
                $dataarray[$key]['goo_name'] = $value['goo_name'];
                if ($value['goo_class'] == 2 && isset($gosa_data[$value['goo_id']]) && !empty($gosa_data[$value['goo_id']])) {
                    $dataarray[$key]['goo_name'] = $gosa_data[$value['goo_id']];
                }
                if (isset($goaf_data[$value['goo_id']]) && !empty($goaf_data[$value['goo_id']])) { // 商品别名
                    $dataarray[$key]['goo_name'] = $goaf_data[$value['goo_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) {
                            $dataarray[$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'))) {
                                $dataarray[$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) {
                        $dataarray[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $dataarray[$key]['goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $dataarray[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $dataarray[$key]['goo_name'];
                        }
                    }
                }
                // 出入库类型：1出库，2入库
                if ($value['osld_out_in_type'] == 1) {
                    $dataarray[$key]['osld_out_in_type'] = '出库';
                } elseif ($value['osld_out_in_type'] == 2) {
                    $dataarray[$key]['osld_out_in_type'] = '入库';
                } elseif ($value['osld_out_in_type'] == 3) {
                    $dataarray[$key]['osld_out_in_type'] = '锁定';
                } else {
                    $dataarray[$key]['osld_out_in_type'] = '取消锁定';
                }
                // 类型1良品2优先
                if ($value['osld_type'] == 1) {
                    $dataarray[$key]['osld_type'] = '良品';
                } elseif ($value['osld_type'] == 2) {
                    $dataarray[$key]['osld_type'] = '优先';
                } else {
                    $dataarray[$key]['osld_type'] = '待检测';
                }
                // 商品数量
                if ($value['osld_out_in_type'] == 1) {
                    $dataarray[$key]['osld_goo_number'] = '-' . $value['osld_goo_number'];
                } elseif ($value['osld_out_in_type'] == 2) {
                    $dataarray[$key]['osld_goo_number'] = $value['osld_goo_number'];
                } elseif ($value['osld_out_in_type'] == 3) {
                    $dataarray[$key]['osld_goo_number'] = '-' . $value['osld_goo_number'];
                } else {
                    $dataarray[$key]['osld_goo_number'] = $value['osld_goo_number'];
                }
                
                $dataarray[$key]['osld_old_stock_number'] = "\t" . $value['osld_old_stock_number'];//旧的商品良品库存数量
                $dataarray[$key]['osld_old_stock_lock_number'] = "\t" . $value['osld_old_stock_lock_number'];//旧的商品良品库存锁定数量
                $dataarray[$key]['osld_old_priority_number'] = "\t" . $value['osld_old_priority_number'];//旧的商品优先库存数量
                $dataarray[$key]['osld_old_priority_lock_number'] = "\t" . $value['osld_old_priority_lock_number'];//旧的商品优先库存锁定数量
                $dataarray[$key]['osld_new_stock_number'] = "\t" . $value['osld_new_stock_number'];//新的商品良品库存数量
                $dataarray[$key]['osld_new_stock_lock_number'] = "\t" . $value['osld_new_stock_lock_number'];//新的商品良品库存锁定数量
                $dataarray[$key]['osld_new_priority_number'] = "\t" . $value['osld_new_priority_number'];//新的商品优先库存数量
                $dataarray[$key]['osld_new_priority_lock_number'] = "\t" . $value['osld_new_priority_lock_number'];//新的商品优先库存锁定数量
                // 商品类型
                if ($value['goo_type'] == 1) {
                    $dataarray[$key]['goo_type'] = '正常';
                } elseif ($value['goo_type'] == 2) {
                    $dataarray[$key]['goo_type'] = '赠品';
                } elseif ($value['goo_type'] == 4) {
                    $dataarray[$key]['goo_type'] = '旧货';
                }
                // 仓库名称
                $dataarray[$key]['osld_ware_name'] = $find_ware[$value['oslr_ware_id']];;
                // 仓库类别
                if ($value['osld_waon_class'] == 1) {
                    $dataarray[$key]['osld_waon_class'] = '货物仓';
                } elseif ($value['osld_waon_class'] == 2) {
                    $dataarray[$key]['osld_waon_class'] = '非商品仓';
                } elseif ($value['osld_waon_class'] == 3) {
                    $dataarray[$key]['osld_waon_class'] = '旧货仓';
                } elseif ($value['osld_waon_class'] == 4) {
                    $dataarray[$key]['osld_waon_class'] = '临时仓';
                }
                $dataarray[$key]['oslr_create_time'] = $value['oslr_create_time'];
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'没有符合条件的数据']);
        }
        // dump($dataarray);
        // exit;
        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }

        $streamFileRand = '库存锁定流水记录' . time() . rand(100, 999) . '.xls';
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' . $streamFileRand;

        $where['action_name'] = '库存锁定流水记录';
        $where['field_name'] = ['流水单号', '原始单号', '关联单号', '单位名称', '检索编码', '商品名称', '记录类型', '出库类型', '商品数量', '原来良品库存', '原来良品锁定', '原来优先库存', '原来优先锁定', '新的良品库存', '新的良品锁定', '新的优先库存', '新的优先锁定', '商品类型', '仓库名称', '仓库类别', '操作时间'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $dataarray      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($streamFilename)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }
}
