"use strict";
/**
 * 试乘试驾全部逻辑处理文件
 * 主页：indexCtrl
 * Created by wh on 2015/7/13.
 */

var tdriveId =  window.location.pathname.split("/")[2];
requirejs.config({
    paths:{
        angular:"/js/angular.min",
        jquery:'http://cdn.bootcss.com/jquery/1.11.2/jquery.min',
        angularResource: "/js/angular-resource.min",
        angularSanitize:"/js/angular-sanitize.min",
        angularRoute:"/js/angular-route.min",
        highchart:"/js/highcharts",
        exporting:"/js/exporting",
        sha1: "/js/sha1",
        bootstrap:'../bootstrap.min',
        datetimepicker:'/js/bootstrap-datetimepicker2.min',
        text:"http://cdn.staticfile.org/require-text/2.0.12/text.min",
        prevload:"/testDrive/scripts/prevload",
        react: "http://cdn.bootcss.com/react/15.1.0/react.min",
        reactdom: "http://cdn.bootcss.com/react/15.1.0/react-dom.min"
    },
    shim:{
        jquery: { exports: '$' },
        angular: { exports: 'angular',deps:['jquery']},
        angularResource: ['angular'],
        angularSanitize:['angular'],
        angularRoute:['angular'],
        bootstrap:['jquery'],
        datetimepicker:['bootstrap'],
        highchart:['jquery'],
        exporting:['highchart'],
        react: "http://cdn.bootcss.com/react/15.1.0/react.min",
        reactdom: "http://cdn.bootcss.com/react/15.1.0/react-dom.min"
    }
});
requirejs(['../testDrive','jquery','../service/testDriveService','../directive/myCurrentTime','../directive/icBaiduMap','./testDrivingControl','./testDrivingReportControl',
    './alarmControl', './testDriverControl', './testSalesPersonControl', './testVehicleControl', './analysisControl',
    'bootstrap','datetimepicker','highchart','exporting','sha1','prevload','../../fence/icFence','./outsideReactControl'], function(module, $){
    var pathname = 'testDrive';
    module
        .config(function($routeProvider,$locationProvider){
            $routeProvider.
                when('/testDrive/:tdriveId/index', {
                    controller: 'indexCtrl',
                    templateUrl: '/'+pathname+'/view/main.html'
                })
            .when('/testDrive/:tdriveId/testDriving', {
                controller: 'testDrivingCtrl',
                templateUrl: '/'+pathname+'/view/testDriving/index.html'
            })
            .when('/testDrive/:tdriveId/report', {
                controller: 'testDrivingReportCtrl',
                templateUrl: '/'+pathname+'/view/report/index.html'
            })
            .when('/testDrive/:tdriveId/alarm',{
                controller:'alarmCtrl',
                templateUrl:'/'+pathname+'/view/alarm/index.html'
            })
            .when('/testDrive/:tdriveId/more/testDriver',{
                controller:'testDriverCtrl',
                templateUrl:'/'+pathname+'/view/testDriver/index.html'
            })
            .when('/testDrive/:tdriveId/more/testSalesPerson',{
                controller:'testSalesPersonCtrl',
                templateUrl:'/'+pathname+'/view/testSalesPerson/index.html'
            })
            .when('/testDrive/:tdriveId/more/testVehicle',{
                controller:'testVehicleCtrl',
                templateUrl:'/'+pathname+'/view/testVehicle/index.html'
            })
            .when('/testDrive/:tdriveId/analysis',{
                controller:'analysisCtrl',
                templateUrl:'/'+pathname+'/view/dataAnalysis/index.html'
            })
            .when('/testDrive/:tdriveId/outside/:osid',{
                controller: 'OutsideReactCtrl',
                template: "<div id='outside' style='height:100%' />"
            });

            $locationProvider.html5Mode(true).hashPrefix("!");
        })
        .controller("mainCtrl",function($scope,$resource,$location,$http,testDriveService) {

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

            //时间显示
            var today = new Date();
            var n_day=today.getDay();
            $scope.weekTime = "";
            switch(n_day){
                case 0:
                {$scope.weekTime=" 星期日 "}break;
                case 1:
                {$scope.weekTime=" 星期一 "}break;
                case 2:
                {$scope.weekTime=" 星期二 "}break;
                case 3:
                {$scope.weekTime=" 星期三 "}break;
                case 4:
                {$scope.weekTime=" 星期四 "}break;
                case 5:
                {$scope.weekTime=" 星期五 "}break;
                case 6:
                {$scope.weekTime=" 星期六 "}break;
                case 7:
                {$scope.weekTime=" 星期日 "}break;
            }

            $scope.format = 'yyyy-MM-dd';
            //$scope.pathname = pathname;

            $scope.tdriveId = tdriveId;
            $scope.loginStaff = {};

            //获取当前登录用户
            var apiLoginStaff = $resource('/' + pathname + '/api/loginStaff');
            apiLoginStaff.get({tdriveId: $scope.tdriveId}, function (data) {
                var tdriveId = data.s4_id;
                $scope.tdriveId = tdriveId;
                $scope.loginStaff = data;

                var xPath = $location.url().split('/');
                if(xPath.length > 2 && xPath[1].toLowerCase() == 'testdrive'){
                    var append = '';
                    if(xPath.length < 3 || (xPath.length==3 && xPath[2]=='')){
                        if(xPath.length < 3) append = '/';
                        append += (tdriveId + '/index');
                        $location.url($location.url() + append);
                    }
                    else if(xPath.length < 4 || (xPath.length==4 && xPath[3]=='')) {
                        if (xPath.length < 4) append = '/';
                        append += 'index';
                        $location.url($location.url() + append);
                    }
                };


                //进入分析页面时，默认最近7天的分析，日期显示最近的7天
                $scope.sta ={};
                $scope.sta.tm_start = testDriveService.getBeforeDate(6);
                $scope.sta.tm_end = testDriveService.getBeforeDate(0);
                $scope.analysisUrl = "/testDrive/"+tdriveId+"/analysis"+"?_s="+$scope.sta.tm_start+"&_e="+$scope.sta.tm_end+"&_n=vehicle";//定义分析的url


                //获取试乘试驾信息
                var apiTestDrive = $resource('/' + pathname + '/api/testDrive/:tdriveId');
                apiTestDrive.get({tdriveId:$scope.tdriveId},function(data){
                    $scope.testDrive = data;
                },function(error){
                    if(error.status == 403 || error.status == 401){
                        //fleetService.errorHandle();
                    }
                });

                //报告    统计未打印
                var apiDrivingReport = $resource('/'+pathname+'/api/testDrive/:tdriveId/report');  //获取所有报告 get
                apiDrivingReport.get({tdriveId:$scope.tdriveId,status:0}, function(data) {
                    $scope.reportTotal = data.total;
                });

                //报警   统计未处理
                var apiAllAlarm = $resource('/'+pathname+'/api/testDrive/:tdriveId/alarm');  //获取报警信息
                apiAllAlarm.get({tdriveId:$scope.tdriveId,s4_id:$scope.tdriveId,careStatus:1},function(data){
                    if(data.status == 'ok'){
                        $scope.alarmTotal = data.total;
                    }
                });
            });

            //初始化激活菜单 TODO :等全部写好后把name对一下
            var menu = {1:{name:"index"},2:{name:"testDriving"},3:{name:"report"},4:{name:"alarm"},5:{name:"more"},6:{name:"analysis"}};
            var submenu = {1:{name:"testDriver"},2:{name:"testSalesPerson"},3:{name:"testVehicle"}};
            var url = $location.absUrl();
            $scope.active = function(index){

                for(var id in submenu){
                    $("#sub_"+id).removeClass("now");
                }
                for(var id in menu){

                    $("#li_active_"+id).removeClass("now");
                    if(index == 0){
                        if(url.indexOf(menu[id].name) != -1){
                            $("#li_active_"+id).addClass("now");
                            if(id == 6){
                                $scope.subactive(0);
                            }
                        }
                    }else{
                        $("#li_active_"+index).addClass("now");
                        if(index == 6){
                            $scope.subactive(0);
                        }
                    }
                }
            };

            //更多里面的菜单
            $scope.subactive = function(index){
                for(var id in menu) {
                    $("#li_active_" + id).removeClass("now");
                }
                $("#li_active_6").addClass("now");
                for(var id in submenu){
                    $("#sub_"+id).removeClass("now");
                    if(index == 0){
                        if(url.indexOf(submenu[id].name) != -1){
                            $("#sub_"+id).addClass("now");
                        }
                    }else{
                        $("#sub_"+index).addClass("now");
                    }
                }
            };
            $scope.active(0); //菜单激活样式

            //注销
            $scope.logout = function()
            {
                if(confirm("您是否确定要退出登录?"))
                {
                    $http.get("/wservice/logout").success(function(data){
                        if(data.status == "ok")
                        {
                            window.location="/login.html";
                        }
                    }).error(function(data){
                        alert("请求无响应!");
                    })
                }
            };

            var apiVehicle = $resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle');  //获取试驾信息 get
            var apiFence = $resource('/' + pathname + '/api/testDrive/:tdriveId/fence'); // 电子围栏
            // 更新电子围栏
            $scope.fences = [];
            $scope.configFence = function(){
                $('#configFence').modal('show');
                apiFence.query({tdriveId: $scope.tdriveId}).$promise.then(function(data){
                    $scope.fences = data;
                });
                apiVehicle.get({tdriveId: $scope.tdriveId}).$promise.then(function(data){
                    console.log(data);
                    $scope.vehicles = data;
                });
            };
            $scope.saveFence = function(fences){
                apiFence.save({tdriveId: $scope.tdriveId}, fences).$promise.then(function(data){
                        $('#configFence').modal('hide');
                    },
                    function(err){
                        console.error(err);
                    }
                );
                $('#configFence').modal('hide');
                $scope.fences = [];
            };
            $scope.closeFence = function(){
                $('#configFence').modal('hide');
                $scope.fences = [];
            };


        }).controller("indexCtrl", function ($scope, $resource, $location, $http, $filter, $routeParams,testDriveService){
               var apiVehicle = $resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle');  //获取试驾信息 get
               var apivehLocation = $resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle/:vehicleId/pos'); //获取车最后位置信息
               var apiVehStatus = $resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle/:vehicleId/status'); //获取车的状态

            var height = $("#mapbox").height();
            $scope.mapStyle ={width:"100%",height:height,margin:"auto"};


            $scope.currentPage = 1;//车辆主页默认当前页
            $scope.pageRecord = 10; //分页记录数
            $scope.dataPath = "";

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

            $scope.sexOption = [{id:0,name:"男"},{id:1,name:"女"}];

            testDriveService.delQueryUrl("page",function(data){ //当前页
                $scope.currentPage = data;
            });

            //查询路径
            $scope.changePath = function(currentPage) {
                var hash = 'page='+currentPage;
                $location.path($location.path()).search(hash);
            };

            $scope.vehiclePaging = function(currentPage){
                if(!currentPage) $scope.currentPage = 1;
                else $scope.currentPage = currentPage;
                $scope.postData ={
                    tdriveId:$scope.tdriveId,
                    sortBy: "id-",
                    license:'<>null'
                };

                var nextMarker = parseInt($scope.pageRecord * ($scope.currentPage - 1)) + 1;
                $scope.postData.pageSize = $scope.pageRecord;
                $scope.postData.nextMarker = nextMarker;

                $scope.vehicles = [];
                //$scope.pagingIndex = [];  //解决数据不能同步显示的问题
                //试驾信息
                apiVehicle.get($scope.postData, function(data) {
                    angular.forEach(data.vehicles,function(dv){
                        dv.status = 1;   ///默认车辆状态为‘空闲’
                         $scope.vehicles.push(dv)
                    });
                    $scope.total = $scope.vehicles.length;
                    $scope.dataPathTmp = [];
                    if(data.total > 0){
                        PagingInfo(data.total);
                        var j = 0;
                        angular.forEach($scope.vehicles,function(veh){
                            apivehLocation.get({ tdriveId:$scope.tdriveId,vehicleId:veh.id},function(data){
                                if(data.status == "ok" && data.vehiclePos[0]){
                                    var direction = 0;
                                    var locInfo = data.vehiclePos[0];
                                    if(data.vehiclePos[1]){
                                        var tmpLoc = data.vehiclePos[1];
                                        var x = tmpLoc.latitude.substr(1) - locInfo.latitude.substr(1);
                                        var y = tmpLoc.longitude.substr(1) - locInfo.longitude.substr(1);
                                        direction = parseInt((Math.atan2(x,y) * 180 / Math.PI) * -1);
                                        direction = direction - 180;
                                    }else{
                                        direction = parseInt(locInfo.direction - 90);
                                    }
                                    veh.lon = locInfo.longitude;
                                    veh.lat = locInfo.latitude;
                                    veh.direction = direction;
                                }

                            apiVehStatus.get({tdriveId:$scope.tdriveId,vehicleId:veh.id},function(data){
                                if(data.status == "ok" && data.vehicleStatus[0]){
                                     veh.status = data.vehicleStatus[0].status;
                                    if(veh.lon && veh.lat){
                                        var mark = "";
                                        if(veh.status == 1) mark = "caroffline";
                                        else mark = "caronline";
                                            $scope.dataPathTmp.push({lon:veh.lon.substr(1),lat:veh.lat.substr(1),
                                                license:veh.license,mileage:veh.mileage,status:$filter('vehStatus')(veh.status) ,mark: mark,direction:veh.direction});
                                    }
                                }
                                j++;
                                if(j == $scope.total){
                                    $scope.dataPath = [1];
                                    $scope.dataPath =  $scope.dataPathTmp;
                                }
                            })
                        })
                       });

                        $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:"请选择"}];

                        var apiTestDriving = $resource('/'+pathname+'/api/testDrive/:tdriveId/testDriving');  //获取试驾信息 get
                        var apiVehicle = $resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle');  //获取试驾车辆
                        var apiStaff = $resource('/'+pathname+'/api/testDrive/:tdriveId/staff');  //获取试驾员 /销售员

                        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});
                                }

                                $scope.freeTotal = 0;  //空闲车数；
                                //显示行驶中车辆的状态
                                angular.forEach($scope.vehicles,function(vs){
                                    for(var i=0;i<$scope.vehicleOption.length;i++){
                                        if(vs.id == $scope.vehicleOption[i].id){
                                            $scope.freeTotal =  $scope.freeTotal+1;
                                           vs.carStatus = true;
                                        }
                                    }
                                });
                                //$scope.pagingIndex = $scope.vehicles;  //解决数据不能同步显示的问题
                                $scope.workingTotal = $scope.total - $scope.freeTotal; //试驾中的车辆

                            });


                            //试驾员
                            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;
                            });

                        });
                    }else{
                        alert("暂无数据");
                    }
                });
                $scope.currentPage =  (nextMarker - 1) / $scope.pageRecord + 1;
            };

            $scope.vehiclePaging($scope.currentPage);



            $scope.operIndex = function(index) {
                $scope.testDriving = $scope.vehicles[index];  //单个试乘试驾

                    $scope.freeStaff.id = 0;
                    $scope.freeSalesperson.id = 0;
                    $scope.freeVehicle.id = $scope.testDriving.id;
                    $scope.addTestDriving = {};  //添加的试乘试驾信息
                    $scope.addTestDriving.customer = {}; //客户信息

                    $scope.addTestDriving.customer.cust_sex = 0;  //默认性别

                    //获取当前时间
                    testDriveService.getLocationDate(function (datetime) {
                        $scope.addTestDriving.tm_start = datetime.date + " " + datetime.time;
                    });

            };
            //创建一条试驾信息
            $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-生成报告中

                };
                var apiTestDriving = $resource('/'+pathname+'/api/testDrive/:tdriveId/testDriving');  //获取试驾信息 get
                //添加试驾信息
                apiTestDriving.save({tdriveId:$scope.tdriveId},$scope.postTestDriving, function(data) {
                    if(data.status = 'ok'){
                        $scope.vehiclePaging($scope.currentPage);
                    }else{
                        alert("添加试驾出现错误");
                    }
                });
            };

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

        })
        .filter('changeDate',function(){
            return function(date){
                if(date == "0000-00-00 00:00:00" || date == null) return null;
                var year = date.substring(0,4);
                var month = date.substring(5,7);
                var day = date.substring(8,10);
                var time = date.substring(11,16);
                return (year+"-"+month+"-"+day+" "+time);
            }
        }).filter('reportStatus', function() {//司机当前状态过滤
            return function (input) {
                var staffStatus = "";
                if (input == 0) staffStatus = "未打印";
                else  staffStatus = "已打印";
                return staffStatus;
            };
        }).filter('alarmType',function(){
            return function(input){
                var alarmType = "";
                if(input == 1) alarmType = "故障报警";
                else if(input == 2) alarmType = "碰撞报警";
                else if(input == 3) alarmType = "震动报警";
                else if(input == 4) alarmType = "水温报警";
                else if(input == 5) alarmType = "充电报警";
                else if(input == 6) alarmType = "电压报警";
                else if(input == 7) alarmType = "终端拔出报警";
                else if(input == 8) alarmType = "无出车记录报警";
                else if(input == 9) alarmType = "超速报警";
                else if(input == 10) alarmType = "急加减报警";
                else if(input == 12) alarmType = "越界报警";
                else alarmType = "其它报警";
                return alarmType;
            };
        }).filter('alarmStatus',function(){
            return function(input) {
                var alarmStatus = "";
                if (input == 1) alarmStatus = "未处理";
                else if (input == 2) alarmStatus = "已处理";
                return alarmStatus;
            }
        }).filter('engineType',function(){
            return function(input) {
                var engineType = "";
                if (input == 'L') engineType = "自然吸气";
                else if (input == 'T') engineType = "涡轮增压";
                return engineType;
            }
        }).filter('vehStatus', function() {//司机当前状态过滤
            return function (input) {
                var staffStatus = "";
                if (input == 0) staffStatus = "试驾中";
                else if(input == 1)  staffStatus = "空闲";
                else staffStatus = "生成报告中";
                return staffStatus;
            };
        }).filter('alarmDesc',function(){
            return function(input,type){
                var desc = "无";
                if(type != undefined){
                    if(type == 1){
                         var tempJ = JSON.parse(input);
                        desc = "";
                         for(var i = 0; i < tempJ.length; i++){
                             desc += "["+parseInt(i+1)+"]\t故障码：" + tempJ[i].code + ";故障描述：" + tempJ[i].desc + "\n";
                         }
                    }
                    else if(type != 12){
                        if(input){desc = input};
                    }
                }
                return desc;
            };
        });
    angular.bootstrap(document, ['testDrive', 'fence']);
});