<?php

namespace App\Http\Controllers\Api\PublicsManage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Services\PublicSearch;
use App\Http\Controllers\Api\Verify\PublicsManage\VerifyPublicSearchController;
use App\Services\BasicManagement\MeritPayService;
use App\Services\BasicManagement\QualityTestingService;
use BlueCity\Core\Inc\ErrorInc;

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

    /**
     * [searchPersonel 搜索人员]
     * @param  [type] $user_info    [用户信息]
     * @param  [type] $search_data  [搜索信息]
     * @param  [type] $select_field [查询字段，字符串多个字段用,分开]
     * @return [type]               [description]
     */
    public function searchPersonel(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();
        if (isset($request['show_count'])) {
            $this->show_count = $request['show_count'];
        }
        $list_data = DB::table('admin as a')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->where('asr.adm_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('a.adm_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('a.adm_phone', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('a.adm_id', 'a.adm_name', 'a.adm_phone')
            ->paginate($this->show_count);

        $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_data->items();                //返回数据
        return ['code'=>200, 'msg'=>'success', 'data'=>$data_info];
    }

    // 搜索业务员
    public function searchSalesman(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $select_field = "adm_id, adm_name, adm_phone";

        $public_search = new PublicSearch;
        $list_data = $public_search->searchSalesman($user_info, $request->all(), $select_field, $this->show_count);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data['data']]);
    }

    // 搜索服务技师
    public function searchTechnician(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();
        $public_search = new PublicSearch;
        $list_data = $public_search->searchTechnician($user_info, $search_data, 10);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data['data_info']]);
    }

    // 搜索商品
    public function searchGoods(Request $request)
    {
        // 获取当前操作账号信息
        $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();

        $shop_state = true;
        if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
            $shop_state = false;
        }

        $list_data = DB::table('goods')
            ->where('goo_type', $request['goo_type'])
            ->where('goo_delete', 1)
            ->where('goo_state', 1)
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_cid', 0)
                        ->orwhere('goo_cid', $user_info->adm_cid);
                } else {
                    $query->where('goo_cid', $user_info->adm_cid);
                }
            })
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_shop_id', 0)
                        ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                } else {
                    $query->where('goo_shop_id', $user_info->adm_shop_id);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            }) //品牌系列id
            ->select('goo_id', 'goo_type', 'goo_class', 'goo_name', 'goo_goods_encode', 'goo_price', 'goo_ampere_hour', 'goo_brse_id', 'goo_bra_name')
            ->orderBy('goo_goods_encode', 'asc')
            ->paginate($this->show_count);
        $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_data->items();                //返回数据
        $data_info['brse_data'] = []; //品牌系列数据
        if ($data_info['data']) {
            // 查询品牌系列数据
            $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();
            }

            $goods_data = $list_data->items();
            $goo_id = array_column($goods_data, 'goo_id');
            if (!empty($request['chun_id'])) {
                // 查询客户单位设置的商品价格
                $channel_goo_data = DB::table('channel_unit_goods_correlation')
                    ->where('cugc_shop_id', $shop_id)
                    ->where('cugc_chun_id', $request['chun_id'])
                    ->whereIn('cugc_goo_id', $goo_id)
                    ->pluck('cugc_set_goo_price', 'cugc_goo_id')
                    ->toArray();
            }
            $data_info['data'] = $goods_data;
        }
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 查询图片上传模板权限
    public function findImageUploadPrivilege(Request $request)
    {
        // 查询登录权限表
        $find_login = DB::table('login_temporary')
            ->where('api_token', $request['api_token'])
            ->select('role_auth')
            ->first();
        // 账号登录权限
        $role_auth = json_decode($find_login->role_auth, true);
        // 权限id
        $pri_id = array_column($role_auth, 'pri_id');
        // 判断是否有图片上传模板的权限
        if (in_array(546, $pri_id)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无权限！']);
        }
    }

    // 生成订单的唯一标识
    public function searchUniqueString(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 获取唯一字符串标识
        $ord_unique_string = md5(md5($user_info->adm_id . $user_info->adm_shop_id . date('Y-m-d H:i:s') . rand(10000, 99999)) . rand(10000, 99999));
        $data = ['ord_unique_string' => $ord_unique_string];
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 搜索历史价格
    public function searchHistoricalPrice(Request $request)
    {
        $verify_data = new VerifyPublicSearchController;
        $error_message = $verify_data->searchHistoricalPriceValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if ($request['client_id'] && !empty($request['ord_type'])) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);

            // 查询商品历史价格
            $find_data = DB::table('order_goods as orgo')
                ->leftjoin('order as o', 'o.ord_id', '=', 'orgo.orgo_ord_id')
                ->where('ord_shop_id', $user_info->adm_shop_id)
                ->where('ord_type', $request['ord_type'])
                ->where('orgo_goo_id', $request['goo_id'])
                ->where('ord_client_id', $request['client_id'])
                ->select('orgo_goo_price as goo_price')
                ->orderBy('ord_create_time', 'desc')
                ->offset(0)->limit(5)
                ->get()->toArray();
        } else {
            $find_data = [];
        }

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_data]);
    }

    // 查看仓位商品
    public function searchFreightGoods(Request $request)
    {
        $search_data = $request->all();
        $list_data = DB::table('warehouse_freight_goods as wafg')
            ->leftJoin('goods as goo', 'goo.goo_id', '=', 'wafg.wafg_goo_id')
            ->where('wafg_ware_id', $request['ware_id'])
            ->where('goo_delete', 1)
            ->where('goo_state', 1)
            ->where(function ($query) use ($search_data) {
                $query->where('wafg_stock_number', '>', 0)
                    ->orWhere('wafg_priority_stock_number', '>', 0)
                    ->orWhere('wafg_unchecked_stock_number', '>', 0);
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_id'])) {
                    $query->where('wafg_goo_id', $search_data['goo_id']);
                }
            }) //品类id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wafr_id'])) {
                    $query->where('wafg_wafr_id', $search_data['wafr_id']);
                }
            }) //仓位id
            ->select('wafg_id', 'wafg_wafr_id', 'wafg_wago_id', 'wafg_goo_id', 'wafg_stock_number', 'wafg_priority_stock_number')
            ->orderBy('goo_goods_encode', 'asc')
            ->get()->toArray();
        $data_info['data'] = $list_data; //返回数据
        if ($data_info['data']) {
            // 查询仓位数据
            $wafg_wafr_id = array_column($data_info['data'], 'wafg_wafr_id');
            $wafr_data = DB::table('warehouse_freight')
                ->whereIn('wafr_id', $wafg_wafr_id)
                ->pluck('wafr_name', 'wafr_id')
                ->toArray();
            foreach ($data_info['data'] as $key => $value) {
                if (!empty($value->wafg_wafr_id)) {
                    $data_info['data'][$key]->wafr_name = $wafr_data[$value->wafg_wafr_id];
                } else {
                    $data_info['data'][$key]->wafr_name = '';
                }
            }
        }
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 洗美-搜索服务项目
    public function searchWashService(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        if (empty($fields)) {
            $fields = ['sepr_id', 'sepr_name', 'sepr_order_money', 'sepr_work_type']; //默认查询字段
        }
        $post['string'] = 'sepr_';
        $post['user_info'] = $user_info;
        $type = 3;
        $where_data = whereFunction($post,$type);
        if (!isset($request['show_count']) || empty($request['show_count'])) {
            $request['show_count'] = 10;
        }
        $list_data = DB::table('service_project as a')
            ->whereIn($where_data['string'], $where_data['shop_id'])
            ->where('sepr_state', 1) //状态1启用2停用
            ->where('sepr_delete', 1) //是否删除：1正常2已删除
            ->select($fields)
            ->where(function ($query) use ($request) { //服务项目名称
                if (!empty($request['keywords'])) {
                    $query->where('sepr_name', 'like', '%' . $request['keywords'] . '%');
                }
            })
            ->where(function ($query) use ($request) { //服务项目id
                if (!empty($request['sepr_id'])) {
                    if(is_int($request['sepr_id'])) {
                        $query->where('sepr_id', $request['sepr_id']);
                    }else{
                        $query->where('sepr_name', 'like', '%' . $request['sepr_id'] . '%');
                    }
                }
            })
            ->where(function ($query) use ($request) { //流程分类1生成工单2不生成工单
                if (!empty($request['sepr_work_type'])) {
                    $query->where('sepr_work_type', $request['sepr_work_type']);
                }
            })
            ->orderBy('sepr_id', 'desc')
            ->paginate($request['show_count']);
        $list_items = $list_data->items();
        if (isset($request['search_admin_id']) && !empty($request['search_admin_id'])) {
            foreach ($list_items as $key => $value) {
                $gppe_performance = DB::table('goods_performance')
                    ->where('gppe_goo_id', $value->sepr_id)
                    ->where('gppe_type',2)//类型1商品2服务
                    ->where('gppe_sale_id',$request['search_admin_id'])
                    ->value('gppe_performance');
                $list_items[$key]->gppe_performance = $gppe_performance??0;
            }
        }
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $request['show_count'];        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        if ($list_items) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        } else {
            return response()->json(['code'=>200, 'msg'=>'暂无数据', 'data'=>[]]);
        }
    }

    // 洗美-搜索商品
    public function searchWashGooods(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();

        $list_data = DB::table('goods')
            ->where('goo_shop_id', $user_info->adm_shop_id)
            ->where('goo_type', 5) //商品类型 1正常商品2赠品商品3活动商品4旧货商品5无库存商品
            ->where('goo_delete', 1)
            ->where('goo_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            }) //品牌系列id
            ->select('goo_id', 'goo_type', 'goo_class', 'goo_name', 'goo_goods_encode', 'goo_price', 'goo_guarantee', 'goo_bra_name')
            ->orderBy('goo_id', 'asc')
            ->paginate($this->show_count);
        $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_data->items();                //返回数据
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 洗美-搜索会员
    public function searchWashMember(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($user_info->shop_superior_id) {
            // 总店id
            $shop_id = $user_info->shop_superior_id;
        } else {
            $shop_id = $user_info->adm_shop_id;
        }

        $search_data = $request->all();
        $list = DB::table('member as a')
            ->where('mem_cid', $user_info->adm_cid)
            ->where('mem_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', 'mem_car_num', 'mem_province', 'mem_city', 'mem_county', 'mem_address', 'mem_bership')
            ->paginate(10);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list->items()]);
    }

    // 洗美-搜索考核项
    public function searchExaminationItem(Request $request)
    {
        if (empty($request['pema_type'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'pema_type必传']);
        }

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

        $search_data = $request->all();

        $service = new MeritPayService();
        request()->offsetSet('pema_state', 1);
        // 查询字段
        $field_columns = ['pema_id', 'pema_name', 'pema_grpr_id', 'pema_grle_id', 'pema_standard', 'pema_remark', 'grle_name', 'grpr_name', 'pema_state'];
        $search_data = $service->searchPage($user_info, $request->all(), 10, $field_columns);

        if (empty($search_data)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data]);
        }
    }

    // 洗美-搜索质检项
    public function searchQualityInspectionItem(Request $request)
    {
        if (empty($request['qurp_type'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'qurp_type必传']);
        }

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

        $search_data = $request->all();
        request()->offsetSet('qurp_state', 1);
        $service = new PublicSearch();

        // 查询字段
        $field_columns = ['qurp_id', 'qurp_name', 'qurp_type', 'qurp_standard', 'qurp_standard_type', 'qurp_remark', 'qurp_create_time', 'qurp_state'];
        $search_data = $service->searchQualityInspectionItem($user_info, $request->all(), $field_columns);

        if (empty($search_data)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            return response()->json($search_data);
        }
    }

    // 获取施工部位
    public function getParts(Request $request) {
        $type = DB::table('auto_parts')
            ->where('enabled', 1)
            ->select('type', 'type_id')
            ->groupBy('type')
            ->get()->toArray();
        $new_data = [];
        foreach ($type as $key1 => $value1) {
            $new_data[$key1]['type'] = $value1->type;
            $new_data[$key1]['type_id'] = $value1->type_id;
            $new_data[$key1]['type_num'] = 0;
            $new_data[$key1]['data'] = DB::table('auto_parts')
                ->where('enabled', 1)
                ->where('type', $value1->type)
                ->select('title', 'id', 'type')
                ->get()->toArray();
        }
        return response()->json(['code'=>200,'msg'=>'success','data'=>$new_data]);
    }
}
