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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\WarehouseManage\VerifyOutinRecordController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOutinRecordController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $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;

        $search_data = $request->all();
        $list_data = DB::table('outin_record as o')
            ->leftJoin('admin as a', 'a.adm_id', '=', 'o.oure_adm_id')
            ->where('oure_cid', $user_info->adm_cid)
            ->where('oure_superior_shop_id', $shop_id)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['adm_name'])) {
                    $query->where('a.adm_name', 'like', '%' . $search_data['adm_name'].'%' );
                }
            })//操作人
            ->where(function($query) use($search_data) {
                if (!empty($search_data['oure_out_ware_id'])) {
                    $query->where('o.oure_out_ware_id',$search_data['oure_out_ware_id']);
                }
            })//出库仓库
            ->where(function($query) use($search_data) {
                if (!empty($search_data['oure_in_ware_id'])) {
                    $query->where('o.oure_in_ware_id',$search_data['oure_in_ware_id']);
                }
            })//入库仓库
            ->where(function($query) use($search_data) {
                if (!empty($search_data['oure_create_time'])) {
                    $query->where('o.oure_create_time', 'like', '%' . $search_data['oure_create_time'].'%' );
                }
            })//操作时间
            ->where(function($query) use($search_data) {
                if (!empty($search_data['oure_number'])) {
                    $query->where('o.oure_number', 'like', '%' . $search_data['oure_number'].'%' );
                }
            })//单号
            ->where(function($query) use($search_data) {
                if (!empty($search_data['oure_original_number'])) {
                    $query->where('o.oure_original_number', 'like', '%' . $search_data['oure_original_number'].'%' )
                    ->orWhere('oure_original_correlation_number', 'like', '%' . $search_data['oure_original_number'].'%' );
                }
            })//原始单号
            ->where(function ($query) use ($search_data) {//状态：1.未核销 2.已核销
                if (!empty($search_data['oure_client_type'])) {
                    $query->where('oure_client_type', $search_data['oure_client_type']);
                }
            })//买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            ->where(function ($query) use ($search_data) {//状态：1.未核销 2.已核销
                if (!empty($search_data['oure_client_id'])) {
                    $query->where('oure_client_id', $search_data['oure_client_id']);
                }
            })//选择的客户id,会员id/单位id
            ->select('o.oure_id', 'o.oure_number', 'o.oure_original_number', 'o.oure_type', 'o.oure_count', 'o.oure_out_ware_id', 'o.oure_in_ware_id', 'a.adm_name', 'a.adm_phone', 'o.oure_create_time', 'oure_all_stock', 'oure_lock_quantity', 'oure_priority_all_stock', 'oure_priority_lock_quantity', 'oure_unchecked_all_stock', 'oure_out_in_type', 'oure_waon_class', 'oure_original_correlation_number', 'oure_original_correlation_type', 'oure_client_type', 'oure_client_id')
            ->orderBy('oure_id', 'desc')
            ->paginate($this->show_count);

        $data = $list_data->items();
        if ($data) {
            // 获取出入库记录的仓库id
            $out_ware_id = array_column($data, 'oure_out_ware_id');
            $in_ware_id = array_column($data, 'oure_in_ware_id');
            $ware_id = array_unique(array_merge($out_ware_id, $in_ware_id));
            // 查询仓库信息
            $find_ware = DB::table('warehouse')
                // ->where('ware_cid', $user_info->adm_cid)
                // ->where('ware_superior_shop_id', $shop_id)
                ->whereIn('ware_id', $ware_id)
                ->pluck('ware_name', 'ware_id')->toArray();

            // 循环将出库名称/入库名称追加进去
            foreach ($data as $key => $value) {
                if ($value->oure_out_ware_id) {
                    $data[$key]->oure_out_ware_name = $find_ware[$value->oure_out_ware_id]; //出库仓库名称
                }
                if ($value->oure_in_ware_id) {
                    $data[$key]->oure_in_ware_name = $find_ware[$value->oure_in_ware_id]; //入库仓库名称
                }
            }
        }
        
        $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'] = $data;                //返回数据

        // 获取当前列表下的按钮
        $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 warehouseInfo(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOutinRecordController;
        $error_message = $verify_data->warehouseInfoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询出所有仓库
        $info = DB::table('warehouse as w')
                ->where('ware_id', $request['ware_id'])
                ->get(['ware_name','ware_leader_id','ware_address']);
        foreach ($info as $key => $value) {
            $adm_id = explode(',',$value->ware_leader_id);
            $adm_name = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->select('adm_name', 'adm_phone')
                ->get()->toArray();
            $adm_name = array_column($adm_name, 'adm_name');
            $adm_name =  implode(',', $adm_name);
            $adm_phone = array_column($adm_phone, 'adm_phone');
            $adm_phone =  implode(',', $adm_phone);
            $info[$key]->adm_name = $adm_name;
            $info[$key]->adm_phone = $adm_phone;
        }
        return response()->json(['code'=> 200,'msg'=>'success','data'=>$info]);
    }

    // 单号详情
    public function numberDetails(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOutinRecordController;
        $error_message = $verify_data->numberDetailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $outin_data = DB::table('outin_record')
                ->where('oure_id', $request['oure_id'])
                ->first(['oure_out_ware_id','oure_in_ware_id']);
        $out_ware_data = DB::table('warehouse as a')
            ->leftJoin('admin as b', 'b.adm_id', '=', 'a.ware_leader_id')
            ->where('ware_id', $outin_data->oure_out_ware_id)
            ->get(['ware_name','adm_name','adm_phone']);
        $in_ware_data = DB::table('warehouse as a')
            ->leftJoin('admin as b', 'b.adm_id', '=', 'a.ware_leader_id')
            ->where('ware_id', $outin_data->oure_in_ware_id)
            ->get(['ware_name','adm_name','adm_phone']);

        $goods_data = DB::table('outin_details as r')
            ->leftJoin('goods as g', 'r.oude_goo_id', '=', 'g.goo_id')
            ->where('oude_oure_id', $request['oure_id'])
            ->get(['g.goo_name', 'g.goo_type', 'g.goo_goods_encode','r.oude_goo_number','oude_type']);
        $data['out_ware_data'] = $out_ware_data;
        $data['in_ware_data'] = $in_ware_data;
        $data['goods_data'] = $goods_data;
        return response()->json(['code'=> 200,'msg'=>'success','data'=>$data]);
    }

    // 删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOutinRecordController;
        $error_message = $verify_data->numberDetailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($user_info->adm_id != 1) {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无删除权限']);
        }
        DB::beginTransaction();
        $oure_res = DB::table('outin_record')
                ->where('oure_id', $request['oure_id'])
                ->delete();

        $oude_res = DB::table('outin_details')
                ->where('oude_oure_id', $request['oure_id'])
                ->delete();
        if ($oure_res && $oude_res) {
            DB::commit();
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'删除成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'删除失败']);
        }
    }
}
