/**
 * Created by wh on 2015/7/20.
 */
define(['../testDrive', 'jquery','prevload'],function(module, $){
    module.controller("testVehicleCtrl",function($scope,$resource,$location,$filter,$timeout,$routeParams,testDriveService){

        //initCopyRight(); //版权信息位置调整

        var pathname = 'testDrive';
        $scope.tdriveId = $routeParams.tdriveId;
        $scope.currentPage = 1;//车辆主页默认当前页
        $scope.pageRecord = 10; //分页记录数
        $scope.addVehicle = {};//添加驾驶员的信息
        $scope.float = /^[0-9]{1}[.]{1}[0-9]{1}$/; //小数正则表达式
        $scope.eng_types = [{id:0,name:"请选择"},{id: 1, name: "自然吸气"}, {id: 2, name: "涡轮增压"}];//发动机类型
        $scope.vehicleSelect = {};

        var apiVehicle = $resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle');  //获取试驾车
        var apiUpdateVehicle = $resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle/:vehicleId',null,{'update': { method:'PUT' }});  //修改试驾车
        var apiVehicleById = $resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle/:vehicleId');  //get delete 试驾车
        var apiTestDrive = $resource('/'+pathname+'/api/testDrive/:tdriveId');  //get delete 试驾店

        testDriveService.delQueryUrl("page",function(data){ //当前页
            $scope.currentPage = data;
        });
        testDriveService.delQueryUrl("_l",function(data){ //车牌号
            if(data)$scope.vehicleSelect.license = data;
            else $scope.vehicleSelect.license = "";
        });
        testDriveService.delQueryUrl("_s",function(data){ //车系
            if(data)$scope.vehicleSelect.seriesName = data;
            else $scope.vehicleSelect.seriesName = "";
        });

        //查询路径
        $scope.changePath = function(currentPage) {
            var hash = 'page='+currentPage;
            if($scope.vehicleSelect.license != "") hash += "&_l="+$scope.vehicleSelect.license;
            if($scope.vehicleSelect.seriesName != "") hash += "&_s="+$scope.vehicleSelect.seriesName;
            $location.path($location.path()).search(hash);
        };


        //查询试驾店信息
        apiTestDrive.get({tdriveId:$scope.tdriveId},function(data){
              $scope.thisBrand = data.brand;
        });


        $scope.vehiclePaging = function(currentPage){
            if(!currentPage) $scope.currentPage = 1;
            else $scope.currentPage = currentPage;
            $scope.postData = {
                tdriveId:$scope.tdriveId,
                //is_demo:1,  // 车辆状态 （ 0:没有试驾   1：在试驾中）
                sortBy:'id-'
            };

            if($scope.vehicleSelect.license != ""){
                $scope.postData.license = $scope.vehicleSelect.license;
            }
            if($scope.vehicleSelect.seriesName != ""){
                $scope.postData.seriesName = $scope.vehicleSelect.seriesName;
            }

            var nextMarker = parseInt($scope.pageRecord * ($scope.currentPage - 1)) + 1;
            $scope.postData.pageSize = $scope.pageRecord;
            $scope.postData.nextMarker = nextMarker;
            apiVehicle.get($scope.postData, function(data) {
                $scope.pagingVehicles =[];
                $scope.vehicles =  data.vehicles;
                angular.forEach($scope.vehicles,function(pv){
                    if(!$scope.float.test(pv.disp)){
                        pv.disp =pv.disp+'.0';
                    }
                    if(pv.license != null && pv.license!=""){
                        $scope.pagingVehicles.push(pv)
                    }
                });
                PagingInfo(data.total);
            });
            $scope.currentPage =  (nextMarker - 1) / $scope.pageRecord + 1;
        };


        $scope.vehiclePaging($scope.currentPage);



        //分页数据处理方法
        function PagingInfo(totalCount) {
            $scope.totalCount = totalCount;
            $scope.totalPage = Math.ceil($scope.totalCount / $scope.pageRecord);
            $scope.totalOption = [{}];
            for (var i = 0; i < $scope.totalPage; i++) {
                $scope.totalOption[i] = {size: i + 1};
            }
        }


        //试驾车的基本操作
        $scope.operVehicle = function(operType,index,id){
            $scope.vehicle ={};
            if(operType == 'add'){
                $scope.vehicle.obdArray = [{id:0,obd_code:"请选择"}];
                $scope.vehicle.engineType = 0;
                var postData = {tdriveId:$scope.tdriveId,is_demo:0};
                testDriveService.getVehiclesInfo(postData,"","obd",function(data){
                    Array.prototype.push.apply($scope.vehicle.obdArray, data.vehiclesArray);
                });
                getAllBrandSeries(operType,index);
            }else if(operType == 'delete'){
                $scope.vehicleDetail = $scope.pagingVehicles[index];
                if (confirm("是否确定删除试驾车?")) {
                    $scope.deletePostData = {
                        license:null,
                        mileage:null,
                        brand:null,
                        series:null,
                        engineType:null,
                        disp:null,
                        is_demo:0
                    };
                    apiUpdateVehicle.update({tdriveId:$scope.tdriveId,vehicleId:$scope.vehicleDetail.id},$scope.deletePostData,function(data){
                        if(data.status == 'ok'){
                            alert("试驾车删除成功");
                            $scope.vehiclePaging($scope.currentPage);
                        }
                    })
                }
            }else if(operType == 'update'){
                //$scope.vehicle = $scope.pagingVehicles[index];
                $scope.vehicle.id = $scope.pagingVehicles[index].id;
                updateVehicle($scope.vehicle.id,index);
                getAllBrandSeries(operType,index);

            }
        };

        //添加试驾车
        $scope.createVehicle = function(){

            for(var i=0;i<$scope.vehicle.obdArray.length;i++){
                if($scope.vehicle.chooseObd == $scope.vehicle.obdArray[i].id){
                    $scope.vehicle.obd_code = $scope.vehicle.obdArray[i].obd_code
                }
            }

            if($scope.vehicle.chooseBrand == 0){
                alert("请选择车辆品牌！");
                return;
            }
            if($scope.vehicle.chooseSeries == 0){
                alert("请选择车系！");
                return;
            }
            if($scope.vehicle.engineType == 0){
                alert("请选择发动机类型！");
                return;
            }
            if($scope.vehicle.chooseObd == 0){
                alert("请选择发动机类型！");
                return;
            }

            $scope.postData ={
                s4_id: $scope.tdriveId,
                license:$scope.vehicle.license,
                obd_code:$scope.vehicle.obd_code,
                mileage:$scope.vehicle.mileage,
                brand:$scope.vehicle.chooseBrand,
                series:$scope.vehicle.chooseSeries,
                engineType:$scope.vehicle.engineType,
                disp:$scope.vehicle.disp,
                is_demo:1
            };

            for(var i=0;i<$scope.eng_types.length;i++){
                if($scope.eng_types[i].id == $scope.vehicle.engineType){
                    if ($scope.eng_types[i].name === '涡轮增压') $scope.postData.engineType = 'T';
                    else $scope.postData.engineType = 'L';
                }
            }

            apiUpdateVehicle.update({tdriveId:$scope.tdriveId,vehicleId:$scope.vehicle.chooseObd},$scope.postData).$promise.then(function(addvehicle){
                if(addvehicle.status =='ok'){
                    alert("车辆添加成功！");
                    $scope.vehiclePaging($scope.currentPage);
                } else{
                    alert("车辆添加失败！");
                }
            },function(error){
                if(error.data.indexOf("ER_DUP_ENTRY: Duplicate entry")!= -1){
                    alert("车牌号"+$scope.vehicle.license+"的车辆已存在,请重填！");
                }
                else{
                    alert("网速不给力,请稍后再试！~");
                }
            });

        };


        //修改试驾车
        $scope.modifyVehicle = function(){

            if($scope.vehicle.chooseBrand == 0){
                alert("请选择车辆品牌！");
                return;
            }
            if($scope.vehicle.chooseSeries == 0){
                alert("请选择车系！");
                return;
            }
            if($scope.vehicle.engineType == 0){
                alert("请选择发动机类型！");
                return;
            }
            if($scope.vehicle.chooseObd == 0){
                alert("请选择发动机类型！");
                return;
            }

            $scope.postData ={
                s4_id: $scope.tdriveId,
                license:$scope.vehicle.license,
                obd_code:$scope.vehicle.obd_code,
                mileage:$scope.vehicle.mileage,
                brand:$scope.vehicle.chooseBrand,
                series:$scope.vehicle.chooseSeries,
                engineType:$scope.vehicle.engineType,
                disp:$scope.vehicle.disp,
                is_demo:1
            };

            for(var i=0;i<$scope.eng_types.length;i++){
                if($scope.eng_types[i].id == $scope.vehicle.engineType){
                    if ($scope.eng_types[i].name === '涡轮增压') $scope.postData.engineType = 'T';
                    else $scope.postData.engineType = 'L';
                }
            }

            apiUpdateVehicle.update({tdriveId:$scope.tdriveId,vehicleId:$scope.vehicle.id},$scope.postData).$promise.then(function(updatevehicle){
                if(updatevehicle.status =='ok'){
                    alert("车辆信息修改成功！");
                    $scope.vehiclePaging($scope.currentPage);
                } else{
                    alert("车辆信息修改失败！");
                }

            },function(error){
                if(error.data.indexOf("ER_DUP_ENTRY: Duplicate entry")!= -1){
                    alert("车牌号为"+$scope.vehicle.license+"的车辆已存在,请重填！");
                }
                else{
                    alert("网速不给力,请稍后再试！~");
                }
            });
        };

        //获取所有的品牌和车系
        function getAllBrandSeries(operType){
            //$scope.vehicle = {};
            $scope.vehicle.carSeries = [{seriesId:0,seriesName:"请选择"}];
            $scope.vehicle.chooseObd = 0;
            $scope.vehicle.chooseSeries = 0;
            testDriveService.getBrandSeries($scope.tdriveId,true,function(brands){
                $scope.vehicle.brands = brands;
                if($scope.thisBrand != 0){
                    angular.forEach($scope.vehicle.brands,function(brand){
                        if(brand.brandId == $scope.thisBrand){
                            $scope.vehicle.chooseBrand  =  brand.brandId;
                        }
                    });
                    $scope.getAllSeries($scope.vehicle.chooseBrand,brands,$scope.vehicle.series)
                }
                else if(operType == "update"){
                    angular.forEach($scope.vehicle.brands,function(brand){
                        if(brand.brandId == $scope.vehicle.brand){
                            $scope.vehicle.chooseBrand  =  brand.brandId;
                        }
                    });
                    $scope.getAllSeries($scope.vehicle.chooseBrand,brands,$scope.vehicle.series)
                }else{
                    $scope.vehicle.chooseBrand = 0;
                }
            });
        }

        //获取所有车系
        $scope.getAllSeries = function(chooseBrand,brands,chooseSeries){
            $scope.vehicle.chooseBrand = chooseBrand;
            testDriveService.getSeriesByBrandId(chooseBrand,brands,function(data){
                $scope.vehicle.carSeries = data.carSeries;
                if(chooseSeries){
                    angular.forEach($scope.vehicle.carSeries,function(series){
                        if($scope.vehicle.series == series.seriesId){
                            $scope.vehicle.chooseSeries = series.seriesId;
                        }
                    })
                }
            });


        };

        //匹配发动机类型
        function updateVehicle(vehicleId){
            apiVehicleById.get({tdriveId:$scope.tdriveId,vehicleId:vehicleId},function(data){
                $scope.vehicle = data;
                if($scope.vehicle.engineType == 'L'){
                    $scope.vehicle.engineType = 1;
                    $scope.vehicle.unit ="(L)"
                }else if($scope.vehicle.engineType == 'T'){
                    $scope.vehicle.engineType = 2;
                    $scope.vehicle.unit ="(T)"
                }
                if(!$scope.float.test($scope.vehicle.disp)){
                    $scope.vehicle.disp =$scope.vehicle.disp+'.0';
                }
            })
        }

        ////改变排气量的单位
        //$scope.changeUnit = function (type) {
        //    switch (type) {
        //        case 0:
        //            $scope.vehicle.unit = "";
        //            break;
        //        case 1:
        //            $scope.vehicle.unit = "(L)";
        //            break;
        //        case 2:
        //            $scope.vehicle.unit = "(T)";
        //            break;
        //    }
        //};

    });
});