<?php

namespace App\Http\Controllers\Api\MemberManage;

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

class MemberCarController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberCarController;
        $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']);
        $page_size = $request->input('show_count', 10);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->adm_shop_id;
        $post['string'] = 'meca_';
        $post['user_info'] = $user_info;
        $type = 1;
        $where_data = whereFunction($post,$type);
        $search_data = $request->all();
        $list_data = DB::table('member_car as a')
            ->leftJoin('member as b', 'b.mem_id', '=', 'a.meca_mem_id')
            ->where('meca_cid', $user_info->adm_cid)
            ->whereIn($where_data['string'], $where_data['shop_id'])
            ->where(function($query) use($search_data) {
                if (!empty($search_data['meca_car_num'])) {
                    $query->where('meca_car_num', 'like', '%'.$search_data['meca_car_num'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['meca_car_series'])) {
                    $query->where('meca_car_series', 'like', '%'.$search_data['meca_car_series'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['meca_car_model'])) {
                    $query->where('meca_car_model', 'like', '%'.$search_data['meca_car_model'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['mem_phone'])) {
                    $query->where('mem_phone', 'like', '%'.$search_data['mem_phone'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['meca_insure_time'])) {
                    $query->where('meca_insure_time', 'like', '%'.$search_data['meca_insure_time'].'%' );
                }
            })
            ->select('meca_id', 'mem_name', 'mem_phone', 'meca_car_num', 'meca_car_series', 'meca_car_model', 
                'meca_insure_time')
            ->orderBy('meca_id', 'desc')
            ->paginate($page_size);
        $list_items = $list_data->items();         
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                if ($value->meca_insure_time == '0000-00-00') {
                    $value->meca_insure_time = ''; 
                }
            }
        }

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

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

        // 1. 判断车牌号是否存在
        $find_meca = DB::table('member_car')
            ->where('meca_cid', $user_info->adm_cid)
            ->where('meca_superior_shop_id', $shop_id)
            ->where('meca_car_num', $request['meca_car_num'])
            ->first(['meca_id']);
        if ($find_meca) {
            return response()->json(["code"=>500,'msg'=>'该车牌号已存在','data'=>'该车牌号已存在']);
        }

        // 2 新增一个车牌号
        $meca_add_data['meca_cid'] = $user_info->adm_cid;
        $meca_add_data['meca_shop_id'] = $user_info->adm_shop_id;
        $meca_add_data['meca_superior_shop_id'] = $shop_id;
        $meca_add_data['meca_create_adm_id'] = $user_info->adm_id;
        $meca_add_data['meca_mem_id'] = $request['meca_mem_id'];
        $meca_add_data['meca_car_num'] = $request['meca_car_num'];
        $meca_add_data['meca_car_series'] = $request['meca_car_series'] ? $request['meca_car_series'] : '';
        $meca_add_data['meca_car_model'] = $request['meca_car_model'] ? $request['meca_car_model'] : '';
        $meca_add_data['meca_insure_time'] = $request['meca_insure_time'] ? $request['meca_insure_time'] : '';
        $meca_add_data['meca_insure_company'] = $request['meca_insure_company'] ? $request['meca_insure_company'] : '';
        $meca_add_data['meca_year'] = $request['meca_year'] ? $request['meca_year'] : '';
        $meca_add_data['meca_car_frame'] = $request['meca_car_frame'] ? $request['meca_car_frame'] : '';
        $meca_add_data['meca_update_time'] = date('Y-m-d H:i:s');
        $meca_res =  DB::table('member_car')->insert($meca_add_data);
        if ($meca_res) {
            Common::addLog($user_info, getRealIp($request), '车辆列表','新增','新增车辆：'.$request['meca_car_num'].'成功');
            return response()->json(["code"=>200,'msg'=>'新增车辆成功','data'=>'新增车辆成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'新增车辆失败','data'=>'新增车辆失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberCarController;
        $error_message = $verify_data->editShowValidator($request->all()); //验证编辑id是否存在
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if ($request['type'] == 1) {
        	// 查询车辆信息
    		$find_meca = DB::table('member_car as a')
                    ->leftJoin('member as b', 'b.mem_id', '=', 'a.meca_mem_id')
                    ->where('meca_id', $request['meca_id'])
                    ->select('meca_mem_id', 'meca_car_num', 'meca_car_series', 'meca_car_model', 'meca_insure_time', 
                    'meca_insure_company',  'meca_year', 'meca_car_frame', 'mem_name')
                    ->first(['meca_id']);
            if ($find_meca->meca_insure_time == '0000-00-00') {
                $find_meca->meca_insure_time = ''; 
            }
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$find_meca]);
        }

        $error_message = $verify_data->addValidator($request->all()); //验证除编辑id外的参数是否存在
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'参数错误', '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;

        // 1. 判断车牌号是否存在
        $find_meca = DB::table('member_car')
                        ->where('meca_cid', $user_info->adm_cid)
                    	->where('meca_superior_shop_id', $shop_id)
                        ->where('meca_id', '<>', $request['meca_id'])
                    	->where('meca_car_num', $request['meca_car_num'])
                        ->first(['meca_id']);
        if ($find_meca) {
            return response()->json(["code"=>500,'msg'=>'该车牌号已存在','data'=>'该车牌号已存在']);
        }

        // 2 编辑车牌号
        $meca_edit_data['meca_mem_id'] = $request['meca_mem_id'];
        $meca_edit_data['meca_car_num'] = $request['meca_car_num'];
        $meca_edit_data['meca_car_series'] = $request['meca_car_series'] ? $request['meca_car_series'] : '';
        $meca_edit_data['meca_car_model'] = $request['meca_car_model'] ? $request['meca_car_model'] : '';
        $meca_edit_data['meca_insure_time'] = $request['meca_insure_time'] ? $request['meca_insure_time'] : '';
        $meca_edit_data['meca_insure_company'] = $request['meca_insure_company'] ? $request['meca_insure_company'] : '';
        $meca_edit_data['meca_year'] = $request['meca_year'] ? $request['meca_year'] : '';
        $meca_edit_data['meca_car_frame'] = $request['meca_car_frame'] ? $request['meca_car_frame'] : '';
        $meca_edit_data['meca_update_time'] = date('Y-m-d H:i:s');
        $meca_res = DB::table('member_car')
                    ->where('meca_id', $request['meca_id'])
                    ->update($meca_edit_data);
        if ($meca_res) {
            Common::addLog($user_info, getRealIp($request), '车辆列表','编辑','编辑车辆：'.$request['meca_car_num'].'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'编辑车辆成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'编辑车辆失败']);
        }
    }

    // 详情
    public function info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberCarController;
        $error_message = $verify_data->infoValidator($request->all()); //验证编辑id是否存在
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
    	// 查询车辆信息
    	$find_meca = DB::table('member_car as a')
                    ->leftJoin('member as b', 'b.mem_id', '=', 'a.meca_mem_id')
                    ->where('meca_id', $request['meca_id'])
                    ->select('meca_mem_id', 'meca_car_num', 'meca_car_series', 'meca_car_model', 'meca_insure_time', 
                    'meca_insure_company',  'meca_year', 'meca_car_frame', 'mem_name', 'mem_phone')
                    ->first();
        if ($find_meca->meca_insure_time == '0000-00-00') {
            $find_meca->meca_insure_time = '';
        }
        return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$find_meca]);
    }

    // 删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberCarController;
        $error_message = $verify_data->deleteValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_bra = DB::table('member_car')
                    ->whereIn('meca_id',$request['meca_id'])
                    ->select('meca_car_num')
                    ->get();
        foreach ($find_bra as $key => $value) {
            $meca_car_num[] = $value->meca_car_num;
        }

        $meca_res = DB::table('member_car')
                    ->whereIn('meca_id', $request['meca_id'])
                    ->delete();
        if($meca_res) {
            Common::addLog($user_info, getRealIp($request), '车辆列表','删除','车辆：（'.implode(',', $meca_car_num).'）删除成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'删除成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'删除失败']);
        }
    }

    // 搜索会员
    public function searchMember(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 查询信息
        $find_data = DB::table('member')
                    ->where('mem_cid', $user_info->adm_cid)
                    ->where('mem_superior_shop_id', $shop_id)
                    ->where(function($query) use($search_data) {
	                    if (!empty($search_data['search_data'])) {
	                        $query->where('mem_name', 'like', '%'.$search_data['search_data'].'%' )
					              ->orwhere('mem_phone', 'like', '%'.$search_data['search_data'].'%' );
					    }
	                })
                    ->select('mem_id', 'mem_name', 'mem_phone')
                    ->get();
        return response()->json(["code"=>200,'msg'=>'success','data'=>$find_data]);
    }
}

