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

use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Data\Service\DataCenter\AutoDataService;
use Illuminate\Http\Request;

/**
 * 车型车系接口功能控制器
 *
 * @funtions search/getTopBrandByLetter/getBrandByTopID/getSeriesByBrandID/getModelsBySeriesID
 * @copyright
 * @author Jerry Li
 * @version
 */

class AutoDataController extends Controller
{
    /**
     * @api {post} /api/autoData/search 通过关键字搜索车型
     * @apiGroup 车型接口
     * @apiName 通过关键字搜索车型
     * @apiVersion 1.0.0
     *
     * @apiDescription 通过关键字搜索车型
     *
     * @apiParam {String} keyword  关键字
     * @apiParam {int} number  需要的数量
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "data": [
            {
            "id": "1",
            "firstLetter": "A",
            "carMasterBrandId": "1347097490201255936",
            "carMasterBrandName": "奥迪",
            "carBrandId": "1347104982528434176",
            "carBrandName": "一汽-大众奥迪",
            "carSeriesId": "1356859574560497703",
            "carSeriesName": "奥迪A3",
            "carName": "Sportback 35 TFSI 王一博联名限量款",
            "carNewName": "Sportback 35 TFSI 王一博联名限量款",
            "carEmissionStandardId": "1356593643473084424",
            "carEmissionStandardName": "国VI",
            "carYearId": "1356600020052484098",
            "carYear": "2021",
            "carDpmId": "1356600221634928648",
            "carDpm": "1.4",
            "dpmMl": "1395",
            "carStructureId": "1356603310467194953",
            "carStructure": "5门5座两厢车",
            "carDrive": "前置前驱",
            "carTms": "7挡干式双离合",
            "engineType": 2,
            "carEngine": "1.4T 150马力 L4",
            "carEngineModel": "DJS",
            "marketTime": "2020.11",
            "carEnergyType": "汽油",
            "frontBrakeType": "通风盘式",
            "backBrakeType": "盘式",
            "parkingBrakeType": "电子驻车",
            "frontTireSize": "225/40 R18",
            "backTireSize": "225/40 R18",
            "variableSuspensionFunction": "",
            "airSuspension": "-",
            "electromagneticInductionSuspension": "-",
            "code": "SD21B01N00001",
            "autoHomeId": "0",
            "gearNum": 0,
            "delFlag": false
            }
            ],
            "code": 200,
            "msg": "成功"
       }
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    // public function search(Request $request) {
    //     $keywords = $request->input('keyword');
    //     $limit = $request->input('number', 10);
    //     if ($keywords == '') {
    //         // return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'关键字不能为空']);
    //         return $this->error('关键字不能为空', ErrorInc::INVALID_PARAM);
    //     }
    //     $data = AutoDataService::getCarMByWord($keywords, $limit);
    //     if ($data) {
    //         return $this->success('成功', $data);
    //         // return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
    //     } else {
    //         return $this->error('获取数据失败', ErrorInc::DATA_EMPTY);
    //         // return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
    //     }
    // }

    public function search(Request $request) {
        $keywords = $request->input('keyword');
        $limit = $request->input('number', 20);
        if ($keywords == '') {
            // return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'关键字不能为空']);
            return $this->error('关键字不能为空', ErrorInc::INVALID_PARAM);
        }
        $data = AutoDataService::getCarMByWord($keywords, $limit);
        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => $value) {
                // $data[$key]['allname'] = $value['carMasterBrandName'].' '.$value['carBrandName'].' '.$value['carSeriesName'].' '.$value['carDpm'].' '.$value['carName'].' '.$value['carYear'];
                $new_data[$key]['allname'] = $value['carMasterBrandName'].' '.$value['carBrandName'].' '.$value['carSeriesName'];
            }
        }
        if ($new_data) {
            return $this->success('成功', $new_data);
            // return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        } else {
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
            // return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    /**
     * @api {post} /api/autoData/getTopBrandByLetter 通过字母搜索主品牌
     * @apiGroup 车型接口
     * @apiName 通过字母搜索主品牌
     * @apiVersion 1.0.0
     *
     * @apiDescription 通过字母搜索主品牌
     *
     * @apiParam {String} letter  关键字
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "data": [
            {
            "carMasterBrandId": "1347097483226128384",
            "carMasterBrandName": "阿尔法·罗密欧",
            "enable": true,
            "hot": false,
            "firstLetter": "A",
            "carOtherName": "",
            "carEnName": "",
            "carSeoName": "",
            "carCountryName": "",
            "carSpell": "",
            "carFullSpell": "",
            "carUrlSpell": "",
            "carLogo": "",
            "carUsedName": ""
            }
            ],
            "code": 200,
            "msg": "成功"
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function getTopBrandByLetter(Request $request) {
        $letter = $request->input('letter');
        // if ($letter == '') {
        //     return $this->error('首字母不能为空', ErrorInc::INVALID_PARAM);
        // }
        $data = AutoDataService::getBrandByFirstLetter($letter, 1);
        if ($data['data']) {
            return $this->success('成功', $data['data']);
        } else {
            return $this->error('获取数据失败', ErrorInc::DATA_EMPTY);
        }
    }
    
    /**|---------------------------------------------------------------------------------
     * @name 获取车辆品牌
     * @param string brandName 品牌名
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2023/10/12 9:21
     * |---------------------------------------------------------------------------------
    */
    public function getTopBrand ( Request $request ){
        $brandName = $request->input('brandName');
        $data = AutoDataService::search($brandName);
        if ($data) {
            return $this->success('成功', $data['data']);
        } else {
            return $this->error('获取数据失败', ErrorInc::DATA_EMPTY);
        }
    }

    /**
     * @api {post} /api/autoData/getBrandByTopID 通过主品牌查询子品牌
     * @apiGroup 车型接口
     * @apiName 通过主品牌查询子品牌
     * @apiVersion 1.0.0
     *
     * @apiDescription 通过字母搜索主品牌
     *
     * @apiParam {int} top_id  主品牌id
     * @apiParam {String} keyword  关键字
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "data": [
        {
        "carBrandId": "1347104976396361728",
        "carBrandName": "阿尔法·罗密欧",
        "carBrandShortName": "",
        "enable": true,
        "carCountryName": "",
        "carMasterBrandId": "1347097483226128384",
        "firstLetter": "A",
        "carMasterBrandName": "阿尔法·罗密欧"
        }
        ],
        "code": 200,
        "msg": "成功"
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function getBrandByTopID(Request $request) {
        $topID = trim($request->input('top_id'));
        $keywords = $request->input('keyword') ?? '';
        if ($topID == '') {
            return $this->error('主品牌不能为空', ErrorInc::INVALID_PARAM);
        }
        $data = AutoDataService::searchSubBrand($topID, $keywords);
        if ($data) {
            return $this->success('成功', $data['data']);
        } else {
            return $this->error('获取数据失败', ErrorInc::DATA_EMPTY);
        }
    }

    /**
     * @api {post} /api/autoData/getSeriesByBrandID 通过子品牌查车系
     * @apiGroup 车型接口
     * @apiName 通过子品牌查车系
     * @apiVersion 1.0.0
     *
     * @apiDescription 通过子品牌查车系
     *
     * @apiParam {int} brand_id  子品牌id
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "data": [
        {
        "carMasterBrandId": "1347097483226128384",
        "carMasterBrandName": "阿尔法·罗密欧",
        "carBrandId": "1347104976396361728",
        "carBrandName": "阿尔法·罗密欧",
        "carSeriesId": "1356859574560497710",
        "carSeriesName": "Stelvio",
        "carSeriesShortName": "",
        "enable": true
        }
        ],
        "code": 200,
        "msg": "成功"
      }
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function getSeriesByBrandID(Request $request) {
        $brandID = trim($request->input('brand_id'));
        if ($brandID == '') {
            return $this->error('子品牌不能为空', ErrorInc::INVALID_PARAM);
        }
        $data = AutoDataService::getSeries($brandID, 2);
        if ($data) {
            return $this->success('成功', $data['data']);
        } else {
            return $this->error('获取数据失败', ErrorInc::DATA_EMPTY);
        }
    }

    /**
     * @api {post} /api/autoData/getModelsBySeriesID 通过车系查车型
     * @apiGroup 车型接口
     * @apiName 通过车系查车型
     * @apiVersion 1.0.0
     *
     * @apiDescription 通过车系查车型
     *
     * @apiParam {int} series_id  车系id
     *
     * @apiSuccess {Number} error    状态码，0：请求成功
     * @apiSuccess {String} msg   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "data": {
        "code": 0,
        "msg": "",
        "data": {
        "records": [
        {
        "id": "1279",
        "firstLetter": "A",
        "carMasterBrandId": "1347097483226128384",
        "carMasterBrandName": "阿尔法·罗密欧",
        "carBrandId": "1347104976396361728",
        "carBrandName": "阿尔法·罗密欧",
        "carSeriesId": "1356859574560497710",
        "carSeriesName": "Stelvio",
        "carName": "2.0T 280HP 豪华版",
        "carNewName": "2.0T 280HP 豪华版",
        "carEmissionStandardId": "1356593643473084424",
        "carEmissionStandardName": "国VI",
        "carYearId": "1349970819421577216",
        "carYear": "2020",
        "carDpmId": "1356600221634928655",
        "carDpm": "2.0",
        "dpmMl": "1995",
        "carStructureId": "1356603310467194948",
        "carStructure": "5门5座SUV",
        "carDrive": "前置四驱",
        "carTms": "8挡手自一体",
        "engineType": 2,
        "carEngine": "2.0T 280马力 L4",
        "carEngineModel": "-",
        "marketTime": "2019.11",
        "carEnergyType": "汽油",
        "frontBrakeType": "通风盘式",
        "backBrakeType": "通风盘式",
        "parkingBrakeType": "电子驻车",
        "frontTireSize": "235/55 R19",
        "backTireSize": "235/55 R19",
        "variableSuspensionFunction": "",
        "airSuspension": "-",
        "electromagneticInductionSuspension": "-",
        "code": "SD21B01N01279",
        "autoHomeId": "0",
        "gearNum": 0,
        "delFlag": false
        }
        ],
        "total": "0",
        "size": 10,
        "current": 1,
        "pages": "0"
        }
        },
        "code": 200,
        "msg": "成功"
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     *
     */
    public function getModelsBySeriesID(Request $request) {
        $seriesID = trim($request->input('series_id'));
        if ($seriesID == '') {
            return $this->error('车系不能为空', ErrorInc::INVALID_PARAM);
        }
        $data = AutoDataService::getCarMByBrandID($seriesID, 3);
        if ($data) {
            return $this->success('成功', $data);
        } else {
            return $this->error('获取数据失败', ErrorInc::DATA_EMPTY);
        }
    }

    public function getGoodsByCarId(Request $request) {
        $carId = trim($request->input('car_id'));
        $categoryId = trim($request->input('categoryId'));
        if ($carId == '') {
            return $this->error('车型不能为空', ErrorInc::INVALID_PARAM);
        }
        $data = AutoDataService::getGoodsByCarId($carId, $categoryId, 3);
        if ($data) {
            return $this->success('成功', $data);
        } else {
            return $this->error('获取数据失败', ErrorInc::DATA_EMPTY);
        }
    }

    public function getCarSeriesListByKeyword(Request $request) {
        $keywords = $request->input('keywords');
        $is_sudian = $request->input('is_sudian',FALSE);
        if ($keywords == '') {
            return $this->error('关键字不能为空', ErrorInc::INVALID_PARAM);
        }
        $data = AutoDataService::getCarSeriesListByKeyword($keywords, $is_sudian);
        //第一步 构造数据
        $items = array();
        foreach($data['data'] as $value){
            $items[$value['id']] = $value;
        }
        //第二部 遍历数据 生成树状结构
        $tree = array();
        foreach($items as $key => $value){
            if(isset($items[$value['pid']])){
                $items[$value['pid']]['son'][] = &$items[$key];
            }else{
                $tree[] = &$items[$key];
            }
        }
        $new_data = [];
        $i = 0;
        foreach ($tree as $key => $value) {
            if (isset($value['son'])) {
                foreach ($value['son'] as $key1 => $value1) {
                    if (isset($value1['son'])) {
                        foreach ($value1['son'] as $key2 => $value2) {
                            $new_data[$i]['id'] = $value2['id'];
                            $new_data[$i]['level'] = $value2['level'];
                            $new_data[$i]['pid'] = $value2['pid'];
                            $new_data[$i]['firstLetter'] = $value2['firstLetter'];
                            $new_data[$i]['car_series'] = $value['name'].'-'.$value1['name'].'-'.$value2['name'];
                            $i++;
                        }
                    }else{
                        $new_data[$i]['id'] = $value['id'];
                        $new_data[$i]['level'] = $value['level'];
                        $new_data[$i]['pid'] = $value['pid'];
                        $new_data[$i]['firstLetter'] = $value['firstLetter'];
                        $new_data[$i]['car_series'] = $value['name'].'-'.$value1['name'].'-无';
                        $i++;
                    }
                }
            }else{
                $new_data[$i]['id'] = $value['id'];
                $new_data[$i]['level'] = $value['level'];
                $new_data[$i]['pid'] = $value['pid'];
                $new_data[$i]['firstLetter'] = $value['firstLetter'];
                if ($value['level']==1) {
                    $new_data[$i]['car_series'] = $value['name'].'-无-无';
                }
                if ($value['level']==2) {
                    $new_data[$i]['car_series'] = '无-'.$value['name'].'-无';
                }
                if ($value['level']==3) {
                    $new_data[$i]['car_series'] = '无-无-'.$value['name'];
                }
                $i++;
            }
            
        }
        
        if ($data) {
            if($data['code'] != 0){
                return $this->error($data['msg'], ErrorInc::MYSQL_FAILED);exit;
            }
            if(empty($data)){
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
            }
            return $this->success('成功', $new_data);
        } else {
            return $this->error('获取数据失败', ErrorInc::DATA_EMPTY);
        }
    }
}
