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

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

       var pathname = 'testDrive';
        $scope.tdriveId = $routeParams.tdriveId;
        $scope.allVehicle = {}; //所有车辆
        $scope.allStaff = {};  //所有试驾员
        $scope.allSalesperson = {};  //所有销售员

        $scope.freeVehicle = {};  //空闲车辆
        $scope.freeStaff = {}; //空闲驾驶员
        $scope.freeSalesperson = {}; //空闲销售员

        $scope.sexOption = [{id:0,name:"男"},{id:1,name:"女"}];
        $scope.currentPage = 1;//车辆主页默认当前页
        $scope.pageRecord = 10; //分页记录数
        //搜索全部车辆
        $scope.allVehicleOption = [{id:0,name:"请选择"}];

        //全部试驾员
        $scope.allStaffOption = [{id:0,name:"请选择"}];

        //全部试驾员
        $scope.allSalespersonOption = [{id:0,name:"请选择"}];

        //$scope.operShow = true;


        var apiTestDriving = $resource('/'+pathname+'/api/testDrive/:tdriveId/testDriving');  //获取试驾信息 get
        var apiTestDrivingById = $resource('/'+pathname+'/api/testDrive/:tdriveId/testDriving/:tdrivingId');  //获取一条试驾信息
        var apiUpdateTestDriving = $resource('/'+pathname+'/api/testDrive/:tdriveId/testDriving/:tdrivingId',null,{'update': { method:'PUT' }});  //修改一条试驾信息

        var apiVehicle = $resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle');  //获取试驾车辆

        var apiStaff = $resource('/'+pathname+'/api/testDrive/:tdriveId/staff');  //获取试驾员 /销售员

        var apiTestDrivingReport = $resource('/'+pathname+'/api/testDrive/:tdriveId/testDriving/:tdrivingId/reportinfo');  //报告信息
        var apiTestDrivingAlarm = $resource('/'+pathname+'/api/testDrive/:tdriveId/testDriving/:tdrivingId/alarminfo');  //报警信息
        var apiTestDrivingAddReport = $resource('/'+pathname+'/api/testDrive/:tdriveId/report');  //生成报告
        var apiReport = $resource('/'+pathname+'/api/testDrive/:tdriveId/testDriving/:tdrivingId/report');  //报告

        var apiTripDetail = $resource('/wservice/cmpx/drive_detail/:obd_code/:drive_id');

        //读取地址栏的数据

        testDriveService.delQueryUrl("page",function(data){ //当前页
            $scope.currentPage = data;
        });
        testDriveService.delQueryUrl("_s",function(data){ //试驾员
            if(data)$scope.allStaff.name = data;
            else $scope.allStaff.name = "请选择";
        });
        testDriveService.delQueryUrl("_sp",function(data){ //试驾员
            if(data)$scope.allSalesperson.name = data;
            else $scope.allSalesperson.name = "请选择";
        });
        testDriveService.delQueryUrl("_v",function(data){ //车牌号
            if(data)$scope.allVehicle.name = data;
            else $scope.allVehicle.name = "请选择";
        });


        //查询路径
        $scope.changePath = function(currentPage) {
            var hash = 'page='+currentPage;
            if($scope.allStaff.name != "请选择") hash += "&_s="+$scope.allStaff.name;
            if($scope.allSalesperson.name != "请选择") hash += "&_sp="+$scope.allSalesperson.name;
            if($scope.allVehicle.name != "请选择" ) hash += "&_v="+$scope.allVehicle.name;
            $location.path($location.path()).search(hash);
        };


        //所有的试驾信息
        $scope.testDrivingPaging = function(currentPage){

            if(!currentPage) $scope.currentPage = 1;
            else $scope.currentPage = currentPage;
            $scope.postData ={
                tdriveId:$scope.tdriveId,
                sortBy: "id-"
            };

            if($scope.allStaff.name != "请选择" ){
                $scope.postData.name = $scope.allStaff.name;
            }
            if($scope.allSalesperson.name != "请选择" ){
                $scope.postData.salesPerson = $scope.allSalesperson.name;
            }
            if($scope.allVehicle.name != "请选择" ){
                $scope.postData.license = $scope.allVehicle.name;
            }
            var nextMarker = parseInt($scope.pageRecord * ($scope.currentPage - 1)) + 1;
            $scope.postData.pageSize = $scope.pageRecord;
            $scope.postData.nextMarker = nextMarker;

            //试驾信息
            apiTestDriving.get($scope.postData, function(data) {
                $scope.pagingTestDriving = data.testDriving;

                if($scope.pagingTestDriving.length>0){
                    angular.forEach($scope.pagingTestDriving,function(ptd){
                        if(ptd.status == 0){
                            ptd.operShow = true;
                            ptd.statusShow = "试驾中"
                        }else if(ptd.status == 1){
                            ptd.operShow = false;
                            ptd.statusShow = "已结束"
                        }else if(ptd.status == 2){
                            ptd.operShow = true;
                            ptd.statusShow = "生成报告中";
                        }
                    });
                    PagingInfo(data.total);//分页
                }else{
                    alert("没有数据");
                }
            });
            $scope.currentPage =  (nextMarker - 1) / $scope.pageRecord + 1;
        };

        $scope.testDrivingPaging($scope.currentPage);
        allSelectOption();  //试驾的select

        //分页数据处理方法
        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};
            }
        }

        //试驾的select
        function allSelectOption (){
            $scope.workTestDriving = {};   //行驶中的信息
            $scope.workTestDriving.workStaff = [];  //行驶中的试驾员
            $scope.workTestDriving.workSalesperson = [];  //行驶中的销售员
            $scope.workTestDriving.workVehicle = [];  //行驶中的车辆

            //搜索全部车辆
            $scope.allVehicleOption = [{id:0,name:"请选择"}];
            //全部试驾员
            $scope.allStaffOption = [{id:0,name:"请选择"}];
            //全部试驾员
            $scope.allSalespersonOption = [{id:0,name:"请选择"}];

            apiTestDriving.get({tdriveId: $scope.tdriveId, tm_end: "null"}, function (totalTestDriving) {
                angular.forEach(totalTestDriving.testDriving, function (data) {
                    $scope.workTestDriving.workStaff.push(data.staffId);
                    $scope.workTestDriving.workSalesperson.push(data.salespersonId);
                    $scope.workTestDriving.workVehicle.push(data.vehicleId);
                });

                //车辆
                apiVehicle.get({tdriveId:$scope.tdriveId}, function(data) {
                    $scope.vehicle = data.vehicles;
                    var vehicleHash = {};
                    angular.forEach($scope.vehicle,function(vehicle){
                        if(vehicle.license !="" && vehicle.license != null ){
                            vehicleHash[vehicle.id] = vehicle;
                        }
                    });
                    for(var i in vehicleHash){
                        $scope.allVehicleOption.push({id:vehicleHash[i].id,name:vehicleHash[i].license});
                    }

                    //空闲车辆
                    $scope.vehicleOption = [{id:0,name:"请选择"}];
                    $scope.freeVehicle.id = 0;

                    for(var i=0;i<$scope.workTestDriving.workVehicle.length;i++) {
                        if (vehicleHash[$scope.workTestDriving.workVehicle[i]]) {
                            delete vehicleHash[$scope.workTestDriving.workVehicle[i]];
                        }
                    }
                    for(var i in vehicleHash){
                        $scope.vehicleOption.push({id:vehicleHash[i].id,name:vehicleHash[i].license});
                    }
                });

                //试驾员
                apiStaff.get({tdriveId:$scope.tdriveId}, function(data) {
                    $scope.staff = data.staffs;

                    var staffHash = {};
                    var salespersonHash = {};
                    angular.forEach( $scope.staff,function(staff){
                        if(staff.userType === 3){
                            staffHash[staff.id] = staff;
                        }else if(staff.userType == 4){
                            salespersonHash[staff.id] = staff;
                        }
                    });
                    for(var i in staffHash){
                        $scope.allStaffOption.push({id:staffHash[i].id,name:staffHash[i].name});
                    }
                    for(var i in salespersonHash){
                        $scope.allSalespersonOption.push({id:salespersonHash[i].id,name:salespersonHash[i].name});
                    }

                    //可用试驾员
                    $scope.staffOption = [{id:0,name:"请选择"}];
                    $scope.freeStaff.id = 0;

                    for(var i=0;i<$scope.workTestDriving.workStaff.length;i++) {
                        if (staffHash[$scope.workTestDriving.workStaff[i]]) {
                            delete staffHash[$scope.workTestDriving.workStaff[i]];
                        }
                    }
                    for(var i in staffHash){
                        $scope.staffOption.push({id:staffHash[i].id,name:staffHash[i].name});
                    }

                    //可用销售员
                    $scope.salespersonOption = $scope.allSalespersonOption;
                    $scope.freeSalesperson.id = 0;
                });

            });
        }


        //创建一条试驾信息
        $scope.createTestDriving = function(){
            $scope.addTestDriving.staffId = $scope.freeStaff.id;
            $scope.addTestDriving.salespersonId = $scope.freeSalesperson.id;
            $scope.addTestDriving.vehicleId = $scope.freeVehicle.id;

            $scope.postTestDriving = {
                staffId: $scope.addTestDriving.staffId,      //驾驶员
                salespersonId: $scope.addTestDriving.salespersonId,      //销售员
                vehicleId: $scope.addTestDriving.vehicleId,   //车辆
                cust_name:$scope.addTestDriving.customer.cust_name,  //客户姓名
                cust_license:$scope.addTestDriving.customer.cust_license,  //客户驾驶证号
                cust_sex:$scope.addTestDriving.customer.cust_sex,  //客户性别
                cust_phone:$scope.addTestDriving.customer.cust_phone,  //客户电话
                tm_start:$scope.addTestDriving.tm_start,   //更新时间
                status: 0                    //试驾状态：0-试驾开始 1-试驾结束 2-生成报告中

            };
            //添加试驾信息
            apiTestDriving.save({tdriveId:$scope.tdriveId},$scope.postTestDriving, function(data) {
                if(data.status = 'ok'){
                    $scope.testDrivingPaging($scope.currentPage);
                    allSelectOption();  //试驾的select
                }else{
                    alert("添加试驾出现错误");
                }
            });
        };

        //提交修改
        $scope.modifyTestDriving = function(){
            $scope.postUpdateData = {
                cust_license:$scope.updateTDriving.cust_license,
                cust_name:$scope.updateTDriving.cust_name,
                cust_sex:$scope.updateTDriving.cust_sex,
                cust_phone:$scope.updateTDriving.cust_phone
            };
            apiUpdateTestDriving.update({tdriveId:$scope.tdriveId,tdrivingId:$scope.updateTDriving.id},$scope.postUpdateData, function(data) {
                if(data.status =="ok"){
                    $scope.testDrivingPaging($scope.currentPage);
                }else{
                    alert("修改出现错误");
                }
            });
        };



        //试驾的基本操作
        $scope.operTestDriving = function(operType,index,id){
            $scope.testDriving = $scope.pagingTestDriving[index];  //单个试乘试驾
            if(operType == "add"){   //添加
                $scope.freeStaff.id = 0;
                $scope.freeSalesperson.id = 0;
                $scope.freeVehicle.id = 0;
                $scope.addTestDriving = {};  //添加的试乘试驾信息
                $scope.addTestDriving.customer = {}; //客户信息

                $scope.addTestDriving.customer.cust_sex = 0;

                //获取当前时间
                testDriveService.getLocationDate(function(datetime){
                    $scope.addTestDriving.tm_start = datetime.date+" "+datetime.time;
                });
            }else if(operType == "finish"){  //结束
                $scope.postFinishData ={};
                //获取当前时间
                if (confirm("是否确定结束试驾?")) {
                    testDriveService.getLocationDate(function(datetime){
                        $scope.postFinishData.tm_end = datetime.date+" "+datetime.time;
                        $scope.postFinishData.status = 2;  //生成报告中
                        apiUpdateTestDriving.update({tdriveId:$scope.tdriveId,tdrivingId:$scope.testDriving.id},$scope.postFinishData, function(data) {
                            if(data.status =="ok"){
                                //TODO  生成报告
                                getReportInfo($scope.testDriving); //获取生成报告所要的信息


                                $scope.testDrivingPaging($scope.currentPage);
                                allSelectOption();  //试驾的select
                            }else{
                                alert("结束试驾出现错误");
                            }
                        });
                    });
                }
            }else if(operType == "update"){  //修改
                $scope.testDriving.status=$scope.testDriving.status == 0?'试驾中':'已结束';
                //解决没有确认修改，页面还会出现修改后的信息
                apiTestDrivingById.get({tdriveId:$scope.tdriveId,tdrivingId:id},function(data){
                    $scope.updateTDriving = data
                })
            }else if(operType == "report"){
                apiReport.get({tdriveId:$scope.tdriveId,tdrivingId:$scope.testDriving.id},function(data){
                    if(data.report[0]){
                       var id = data.report[0].id;
                       window.open ('/testDrive/view/report/print.html?rid='+id+"&sid="+$scope.tdriveId, 'newwindow', 'height=670, width=720, top=50, left=301, toolbar=no, menubar=no, scrollbars=yes, resizable=no,location=no, status=no');//这句要写成一行
                    }else{
                        alert("本次试驾暂无试驾报告！");
                    }
                 },function(err){
                    console.log("打印报告有问题！");
                })
            }else if(operType == "trip"){//**新增查询行程数据
                apiTestDrivingReport.get({tdriveId:$scope.tdriveId,tdrivingId: $scope.testDriving.id},function(reportData){
                    $scope.tripTemplate = "tripView";
                    if (reportData.status == 'ok') {
                        $scope.trips = reportData.trips;
                    }else{
                        alert("查询行程出错！");
                    }
                })
            }
        };


        //切换行程-行程详情试图
        $scope.getDriveDetail = function(index,id){
            switch (index){
                case 1:
                    $scope.tripTemplate = "tripView";
                    break;
                case 2:
                    if(id != null){
                        $scope.thisTrip = $scope.trips[id];
                        apiTripDetail.get({obd_code:$scope.thisTrip.obdCode,drive_id:$scope.thisTrip.id},{page:-1,pageRecord:-1},function(detailData){
                                  console.log(detailData);
                            if(detailData.status == "ok"){
                                if(detailData.totalCount > 0) {
                                    $scope.tripTemplate = "tripDetailView";
                                    $scope.tripDetails = detailData.details;
                                }
                            }else{
                                 alert("暂无数据！");
                            }
                        });
                    }
                    else{
                        $scope.tripTemplate = "tripDetailView";
                    }
                    break;
                case 3:
                    $scope.details = $scope.tripDetails[id].detail;
                    $scope.tripTemplate = "tripParamView";
                    break;
            }

        };

        //获取生成报告所要的信息 and 生成报告
        function getReportInfo(testDriving){
            apiTestDrivingReport.get({tdriveId:$scope.tdriveId,tdrivingId:testDriving.id},function(reportData){
                if (reportData.status == 'ok') {
                    apiTestDrivingAlarm.get({tdriveId:$scope.tdriveId,tdrivingId:testDriving.id},function(alarmData){
                        if (alarmData.status == 'ok') {

                            $scope.reportInfo = {};
                            $scope.reportInfo.mileage = 0;  //里程
                            $scope.reportInfo.oilUsed = 0;   //油耗
                            $scope.reportInfo.speedMax = 0; //最高车速;
                            $scope.reportInfo.avgOilUsed = 0; //平均油耗
                            $scope.reportInfo.speedGroup = [
                                {speed:1,time:0,distance: 0},{speed:45,time:0,distance: 0},
                                {speed:90,time:0,distance: 0},{speed:255,time:0,distance: 0}
                            ];
                            for (var i = 0; i < reportData.trips.length; i++) {
                                $scope.reportInfo.mileage = $scope.reportInfo.mileage + reportData.trips[i].currentMileage; //一个试驾 行驶的里程
                                $scope.reportInfo.oilUsed = $scope.reportInfo.oilUsed + reportData.trips[i].currentMileage / (1000*100) * (reportData.trips[i].currentAvgOilUsed/100); //试驾行车油耗(L)
                                if(reportData.trips[i].speedMax> $scope.reportInfo.speedMax)
                                    $scope.reportInfo.speedMax = reportData.trips[i].speedMax;

                                var obj = eval(reportData.trips[i].speedGroup);//通过eval() 函数可以将JSON字符串转化为对象
                                $scope.reportInfo.speedGroup[0].time = $scope.reportInfo.speedGroup[0].time + obj[0].time;
                                $scope.reportInfo.speedGroup[0].distance = $scope.reportInfo.speedGroup[0].distance + obj[0].distance;
                                $scope.reportInfo.speedGroup[1].time = $scope.reportInfo.speedGroup[1].time + obj[1].time;
                                $scope.reportInfo.speedGroup[1].distance = $scope.reportInfo.speedGroup[1].distance + obj[1].distance;
                                $scope.reportInfo.speedGroup[2].time = $scope.reportInfo.speedGroup[2].time + obj[2].time;
                                $scope.reportInfo.speedGroup[2].distance = $scope.reportInfo.speedGroup[2].distance + obj[2].distance;
                                $scope.reportInfo.speedGroup[3].time = $scope.reportInfo.speedGroup[3].time + obj[3].time;
                                $scope.reportInfo.speedGroup[3].distance = $scope.reportInfo.speedGroup[3].distance + obj[3].distance;

                            }
                            $scope.reportInfo.overSpeed = 0;  //超速
                            $scope.reportInfo.speedUp = 0;   //急加速
                            $scope.reportInfo.speedDown = 0; //急减速
                            $scope.reportInfo.speedTurn = 0; //急转弯
                            for(var i = 0; i <alarmData.alarms.length; i++){
                                if(alarmData.alarms[i].alarmType == 6 ){  //超速
                                    $scope.reportInfo.overSpeed = $scope.reportInfo.overSpeed +1
                                }else if(alarmData.alarms[i].alarmType == 7){  //急加速
                                    $scope.reportInfo.speedUp = $scope.reportInfo.speedUp +1
                                }else if(alarmData.alarms[i].alarmType == 8){ //急减速
                                    $scope.reportInfo.speedDown = $scope.reportInfo.speedDown +1
                                }else if(alarmData.alarms[i].alarmType == 9){  //急转弯
                                    $scope.reportInfo.speedTurn = $scope.reportInfo.speedTurn +1
                                }

                            }
                            $scope.reportInfo.avgOilUsed = Math.round($scope.reportInfo.oilUsed/($scope.reportInfo.mileage/1000)*100*100);  //四舍五入取整 （百公里油耗*100）的油耗


                            $scope.reportInfo.staffId = testDriving.staffId;
                            $scope.reportInfo.tdrivingId = testDriving.id;
                            $scope.reportInfo.vehicleId = testDriving.vehicleId;
                            $scope.reportInfo.status = 0;
                             testDriveService.getLocationDate(function(data){
                                 $scope.reportInfo.reportTime =data.date+" "+data.time
                             });
                            $scope.reportInfo.speedGroup = JSON.stringify($scope.reportInfo.speedGroup); //JSON数组转换为字符串

                            //TODO 添加报告信息
                            apiTestDrivingAddReport.save({tdriveId:$scope.tdriveId},$scope.reportInfo,function(data){
                                if(data.status == 'ok'){
                                    apiUpdateTestDriving.update({tdriveId:$scope.tdriveId,tdrivingId:testDriving.id},{status:1}, function(data) {
                                        if(data.status =="ok"){
                                            $scope.testDrivingPaging($scope.currentPage);
                                            allSelectOption();  //试驾的select
                                        }else{
                                            alert("结束试驾出现错误");
                                        }
                                    });
                                }
                            })
                        }
                    })
                }
            });
        }

    });

});
