"use strict";
/**
 * Created by wh on 2015/7/14.
 */
define(['../testDrive','jquery','datetimepicker','angular'],function(module,$,x3,angular){
    var pathname = 'testDrive';

    return module.service('testDriveService', (function(){
        function TestDriveService($http,$resource,$timeout,$location){
            this.$http = $http;
            this.$resource = $resource;
            this.$timeout = $timeout;
            this.$location = $location;
        }

        //加载日期控件
        TestDriveService.prototype.changeDatePicker = function(type,ids){
            if(type == "date"){
                angular.forEach(ids,function(id){
                    $('#'+id).datetimepicker({
                        language:  'fr',
                        weekStart: 1,
                        todayBtn:  1,
                        autoclose: 1,
                        todayHighlight: 1,
                        startView: 2,
                        minView: 2,
                        forceParse: 0
                    });
                })
            }else if(type == "time"){
                angular.forEach(ids,function(id){
                    $('#'+id).datetimepicker({
                        weekStart: 1,
                        todayBtn:  1,
                        autoclose: 1,
                        todayHighlight: 1,
                        startView: 1,
                        minView: 0,
                        maxView: 1,
                        forceParse: 0
                    });
                })
            }else if(type == "datetime"){
                angular.forEach(ids,function(id){
                    $('#'+id).datetimepicker({
                        weekStart: 1,
                        todayBtn:  1,
                        autoclose: 1,
                        todayHighlight: 1,
                        startView: 2,
                        forceParse: 0,
                        showMeridian: 1
                    });
                })
            }
        };

        //通过url的关键字获取值
        TestDriveService.prototype.delQueryUrl =function (key,cb){
            var queryUrl = this.$location.url().split("?");
            if (queryUrl.length > 1) {
                var params = decodeURIComponent(queryUrl[1]).split("&");
                var flag = false;
                var value = "";
                for (var i = 0; i < params.length; i++) {
                    var param = params[i].split("=");
                    if (param[0] == key) {
                        value = param[1];
                        flag = true;
                    }
                }
                if(flag) cb(value);
                else cb(null);
            }else{
                cb(null);
            }
        };

        //获取当前日期与时间
        TestDriveService.prototype.getLocationDate =function(cb){
            var now = new Date();
            var date = now.getFullYear() + "-" + ((now.getMonth() + 1) < 10 ? "0" : "") + (now.getMonth() + 1) + "-" + (now.getDate() < 10 ? "0" : "") + now.getDate();
            var time = (now.getHours() < 10 ? "0" : "") + now.getHours() + ":" + (now.getMinutes() < 10 ? "0" : "") + now.getMinutes() + ":" + (now.getSeconds() < 10 ? "0" : "") + now.getSeconds();
            cb({date:date,time:time});
        };

        //获取现在相对于东八区的时间
        TestDriveService.prototype.getunowStr = function(){
            var unow = new Date(new Date().getTime() + new Date().getTimezoneOffset()*60000);
            var year = unow.getFullYear();
            var mon = unow.getMonth()+1;
            var day = unow.getDate();
            var hours = unow.getHours();
            var minute = unow.getMinutes();
            var second = unow.getSeconds();
            var s = year+"-"+(mon<10?('0'+mon):mon)+"-"+(day<10?('0'+day):day)+" "+hours+":"+minute+":"+second;
            return s;
        };


        //最近n天的日期
        TestDriveService.prototype.getBeforeDate = function(n){
            var n = n;
            var d = new Date();
            var year = d.getFullYear();
            var mon=d.getMonth()+1;
            var day=d.getDate();
            if(day <= n){
                if(mon>1) {
                    mon = mon-1;
                }
                else {
                    year = year-1;
                    mon = 12;
                }
            }
            d.setDate(d.getDate()-n);
            year = d.getFullYear();
            mon=d.getMonth()+1;
            day=d.getDate();
            var s = year+"-"+(mon<10?('0'+mon):mon)+"-"+(day<10?('0'+day):day);
            return s;
        };

        //获取所有的品牌和车系 false:all    true:testDrive
        TestDriveService.prototype.getBrandSeries = function(tdriveId,isAll,cb){
            var apiBrandSeries = this.$resource('/'+pathname+'/api/testDrive/:tdriveId/bs');
            var postData={tdriveId: tdriveId};
            if(isAll) postData.isAll = true;
            apiBrandSeries.get(postData, function(bsData) {
                var brands = [{brandId: 0, brandName: "请选择", series: [{seriesId: 0, seriesName: "请选择"}]}];
                var i = 1;
                for (var brand in bsData) {
                    if (bsData.hasOwnProperty(brand)) {
                        if (brand != "$promise" && brand != "$resolved") {
                            brands.push({brandId: brand, brandName: "", series: []});
                            for (var series in bsData[brand]) {
                                brands[i].brandName = bsData[brand][series]["brand"];
                                brands[i].series.push({seriesId: series, seriesName: bsData[brand][series]["series"]});
                            }
                            i++;
                        }
                    }
                }
                cb(brands);
            });
        };

        //根据选中的品牌来切换车系
        TestDriveService.prototype.getSeriesByBrandId = function(chooseBrand,brands,cb){
            var carSeries = [{seriesId:0,seriesName:"请选择"}];
            var brandName = "";
            if(chooseBrand != 0){
                angular.forEach(brands, function(brand) {
                    if (brand.brandId == chooseBrand) {
                        Array.prototype.push.apply(carSeries, brand.series);
                        brandName = brand.brandName;
                    }
                });
            }
            cb({brandName:brandName,carSeries:carSeries});
        };

        //获取所有可用车辆对象 filter:查询条件 flag:(enable:可用的,all:所有的) type:(vehicle:车辆,obd:可用的车云终端编号)
        TestDriveService.prototype.getVehiclesInfo = function(filter,flag,type,cb) {
            var apiVehicle = this.$resource('/'+pathname+'/api/testDrive/:tdriveId/vehicle');
            apiVehicle.get(filter, function(totalVehicles){
                var vehicles = totalVehicles.vehicles;
                var vehiclesHash = {};
                var vehiclesArray =[];
                var i=0;
                if(vehicles.length == 0){
                    cb({vehiclesHash:vehiclesHash,vehiclesArray:vehiclesArray});
                }
                angular.forEach(vehicles,function(vehicle){
                    if(type == "vehicle" && vehicle.license != null && vehicle.license!=""){
                        if(flag == "enable" && vehicle.disabled !=1){
                            vehiclesHash[vehicle.id] = vehicle;
                        }else if(flag == "all"){
                            vehiclesHash[vehicle.id] = vehicle;
                            vehiclesArray.push(vehicle.id);
                        }
                        vehiclesArray.sort(function(a,b){return a<b?1:-1}); //从大到小排序
                    }else if(type == "obd" && vehicle.license == null){
                        vehiclesArray.push({id:vehicle.id,obd_code:vehicle.obd_code});
                    }
                    if(i == (vehicles.length -1)) {
                        cb({vehiclesHash:vehiclesHash,vehiclesArray:vehiclesArray});
                    }
                    i++;

                });
            })
        };

        return ['$http', '$resource','$timeout','$location', TestDriveService];
    })());
});