/**
 * Created by wh on 2015/7/7.
 */
var debug = require('debug')('@gopalroy/test-drive');
var co = require('co');
var express = require('express');
var bizCore = require('@gopalroy/biz-core');
var bizTestDrive = require('@gopalroy/biz-testdrive');
var ApiHelper = require('./ApiHelper');

var testDriveAPI = (function(){
    function TestDriveAPI(){
        var router = new express();
        router.get('/', this.get);
        router.put('/', this.update);
        router.delete('/', this.delete);
        //router.get('/vehicleWithPos',this.getAllVehiclesWithPos);//获取所有试驾车带位置信息

        router.get('/bs', this.getBrandSeries);//获取品牌车系

        // staff
        router.get('/staff', this.getAllStaffs);  //获取所有试驾员
        router.post('/staff', this.addStaff);  //添加试驾员
        var staffAPI = new (require('./StaffAPI'))();
        router.use('/staff/:staffId', staffAPI.resolveStaff, staffAPI.getRouter());

        // vehicle
        router.get('/vehicle', this.getAllVehicles); //获取所有试驾车
        router.post('/vehicle', this.addVehicle);   //添加试驾车
        var vehicleAPI = new (require('./VehicleAPI'))();
        router.use('/vehicle/:vehicleId', vehicleAPI.resolveVehicle, vehicleAPI.getRouter());

        //testDriving 试驾
        router.get('/testdriving',this.getAllTestDrivings); //获取所有试驾信息
        router.post('/testdriving',this.addTestDriving); //增加驾驶信息
        var testDrivingAPI = new (require('./TestDrivingAPI'))();
        router.use('/testdriving/:tDrivingId', testDrivingAPI.resolveTestDriving, testDrivingAPI.getRouter());


        //report 报告
        router.get('/report',this.getAllDrivingReports);
        router.post('/report',this.addDrivingReport);
        var drivingReportAPI = new (require('./DrivingReportAPI'))();
        router.use('/report/:reportId', drivingReportAPI.resolveDrivingReport, drivingReportAPI.getRouter());

        //alarm 报警
        router.get('/alarm', this.getAllAlarms);//获取所有报警信息
        var AlarmAPI = new (require('./AlarmAPI'))();
        router.use('/alarm/:alarmId', AlarmAPI.resolveAlarm, AlarmAPI.getRouter());

        //车辆管理分析
        var vehicleAnalysisAPI = new (require('./VehicleAnalysisAPI'))();
        router.use('/vehicleAnalysis/:vehicleId', vehicleAnalysisAPI.resolveTripAnalysis, vehicleAnalysisAPI.getRouter());

        //司机管理分析
        var staffAnalysisAPI = new (require('./StaffAnalysisAPI'))();
        router.use('/staffAnalysis/:staffId', staffAnalysisAPI.resolveTripAnalysis, staffAnalysisAPI.getRouter());

        //组织整体分析
        var StatistcsAPI = new (require('./StatisticsAPI'))();
        router.use('/statistics', StatistcsAPI.resolveStatistics, StatistcsAPI.getRouter());

        router.get('/drivingTimes', this.StaVehicleTDrivingTimes);//获取出车详情
        router.get('/staffDrivingTimes', this.StaStaffTDrivingTimes);//获取整个testDrive司机出车详情
        router.get('/salespersonDrivingTimes', this.StaSPTDrivingTimes);//获取整个testDrive销售员出车详情

        // 电子围栏
        var fenceAPI = new (require('./FenceAPI'))();
        router.use('/fence', fenceAPI.getRouter());

        this.router = router;
    }

    // 查询所有试乘试驾
    TestDriveAPI.getAll = function(req, res){
        // 不允许直接操纵数据库,请使用bizCore中的业务对象Org完成功能
        co(function*(){
            var args = ApiHelper.makeQueryArgs(req.query);
            // 强制过滤,只保留试乘试驾
            args.filter['biz_mode'] = 2;
            // 并行查询试乘试驾和试乘试驾总数
            var result = yield [ bizCore.Org.GetOrgsCountG(args.filter),
                bizCore.Org.GetOrgsG(args.filter, args.sortBy, args.pageSize, args.nextMarker) ];
            var orgSafeArray = [];
            result[1].forEach(function(org){ orgSafeArray.push(org.toSafe()); });
            res.json({ total: result[0], orgs: orgSafeArray });
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex).end();
        });
    };

    // 增加一个试乘试驾
    TestDriveAPI.post = function(req, res){
        // 不允许直接操纵数据库,请使用bizCore中的业务对象Org完成功能
        co(function*(){
            var data = req.body;
            var rgxName = /^[0-9a-zA-Z_]{1,}$/;
            if(data.short_name.match(rgxName)){
                var orgNew = bizCore.Org.FromJson(data);
                orgNew.biz_mode = 2;
                var orgAdded = yield orgNew.addG();
                res.json(orgAdded.toSafe());
            }else{
                res.status(500).send("short_name只能由字母数字下划线组成:"+data.short_name).end();
            }
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack).end();
        });
    };

    TestDriveAPI.prototype.getRouter = function(){
        return this.router;
    };

    TestDriveAPI.prototype.resolveTestDrive = function(req, res, next){
        co(function*(){
            req.incar.testDrive = yield bizTestDrive.TestDrive.FromIdG(req.params.tdriveId);
            next();
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    ////////////////////////////////获取一个试乘试驾
    TestDriveAPI.prototype.get = function(req, res){
        res.json(req.incar.testDrive.toSafe())
    };

    //修改一个试乘试驾
    TestDriveAPI.prototype.update = function(req, res){
        co(function*(){
            var data = req.body;
            var orgNew = req.incar.testDrive;

            var id = orgNew.id;
            var biz_mode = orgNew.biz_mode;

            for(var k in data){
                if(data.hasOwnProperty(k)){
                    orgNew[k] = data[k]
                }
            }

            // 这2个字段不允许被修改
            orgNew.id = id;
            orgNew.biz_mode = biz_mode;

            yield orgNew.updateG();
            res.json(orgNew);
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    // 删除一个试乘试驾
    TestDriveAPI.prototype.delete = function(req, res){
        co(function*(){
            var testDrive = req.incar.testDrive;

            // 删除所有职员 && 车辆
            var result = yield [testDrive.getStaffsG(), testDrive.getVehiclesG() ];
            var task = [];
            result[0].forEach(function(staff){ task.push(testDrive.removeStaffG(staff)); });
            result[1].forEach(function(vehicle){ task.push(testDrive.removeVehicleG(vehicle)); });
            yield task;
            yield req.incar.testDrive.deleteG();
            res.send('成功删除一个组织和所属的全部职员');
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //////////////////////////////// staff
    TestDriveAPI.prototype.getAllStaffs = function(req, res){
        co(function*(){
            var args = ApiHelper.makeQueryArgs(req.query);
            var testDriveCtx = req.incar.testDrive;

            // 这里有时有不明原因ECONNRESET,怀疑是网络不稳定导致,尝试重试1次
            yield ApiHelper.retryWrapG(1, function*(){
                var result = yield [testDriveCtx.getStaffsCountG(args.filter),
                    testDriveCtx.getStaffsG(args.filter, args.sortBy, args.pageSize, args.nextMarker)];
                var staffSafeArray = [];
                result[1].forEach(function (staff) {
                    staffSafeArray.push(staff.toSafe());
                });
                res.json({total: result[0], staffs: staffSafeArray});
            }, function(ex){
                return (ex.toString().indexOf("ECONNRESET") !== -1);
            });

        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //试乘试驾中增加一个Staff
    TestDriveAPI.prototype.addStaff = function(req, res){
        co(function*(){
            var data = req.body;
            var staffNew = bizCore.Staff.FromJson(data);
            var orgNew = req.incar.testDrive;
            var staffAdded = yield orgNew.addStaffG(staffNew);
            res.json({status:'ok',staffAdded:staffAdded.toSafe()});
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    ////////////////////////////////  vehicles
    TestDriveAPI.prototype.getAllVehicles = function(req, res){
        co(function*(){
            var args = ApiHelper.makeQueryArgs(req.query);
            var testDriveCtx = req.incar.testDrive;
            var result = yield [ testDriveCtx.getVehiclesCountG(args.filter),
                testDriveCtx.getVehiclesG(args.filter, args.sortBy, args.pageSize, args.nextMarker) ];
            res.json({ total: result[0], vehicles: result[1] });
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //获取所有的vehicles带位置和状态信息
    //TestDriveAPI.prototype.getAllVehiclesWithPos = function(req,res){
    //    co(function*(){
    //        var args = ApiHelper.makeQueryArgs(req.query);
    //        var testDriveCtx = req.incar.testDrive;
    //        var result = yield [ testDriveCtx.GetVehiclesLastPosG(args.filter),
    //            testDriveCtx.getVehiclesG(args.filter, args.sortBy, args.pageSize, args.nextMarker) ];
    //        res.json({ total: result[0], vehicles: result[1] });
    //    }).catch(function(ex){
    //        debug(ex.stack);
    //        res.status(500).send(ex.stack);
    //    });
    //}

    //添加一个vehicle
    TestDriveAPI.prototype.addVehicle = function(req, res){
        co(function*(){
            var data = req.body;
            var vehicleNew = bizCore.Vehicle.FromJson(data);
            var orgNew = req.incar.testDrive;
            var vehicleAdded = yield orgNew.addVehicleG(vehicleNew);
            res.json({status:'ok',vehicleAdded:vehicleAdded});
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //获取所有的试驾
    TestDriveAPI.prototype.getAllTestDrivings = function(req, res){
        co(function*(){
            var args = ApiHelper.makeQueryArgs(req.query);
            var testDriveCtx = req.incar.testDrive;
            var result = yield [ testDriveCtx.getAllTestDrivingCountG(args.filter),
                testDriveCtx.getAllTestDrivingG(args.filter, args.sortBy, args.pageSize, args.nextMarker) ];
            res.json({ total: result[0], testDriving: result[1] });
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //添加一个试驾
    TestDriveAPI.prototype.addTestDriving = function(req, res){
        co(function*(){
            var data = req.body;
            var testDrivingNew = bizTestDrive.TestDriving.FromJson(data);
            var orgNew = req.incar.testDrive;
            var testDrivingAdded = yield orgNew.addTestDrivingG(testDrivingNew);
            res.json({status:'ok',testDrivingAdded:testDrivingAdded});
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //获取所有的报告
    TestDriveAPI.prototype.getAllDrivingReports = function(req, res){
        co(function*(){
            var args = ApiHelper.makeQueryArgs(req.query);
            var testDriveCtx = req.incar.testDrive;
            var result = yield [ testDriveCtx.getAllTestDrivingReportCountG(args.filter),
                testDriveCtx.getAllTestDrivingReportG(args.filter, args.sortBy, args.pageSize, args.nextMarker) ];
            res.json({ total: result[0], drivingReport: result[1] });
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    }

    //添加试驾报告
    TestDriveAPI.prototype.addDrivingReport = function(req, res){
        co(function*(){
            var data = req.body;
            var drivingReportNew = bizTestDrive.TestDrivingReport.FromJson(data);
            var orgNew = req.incar.testDrive;
            var drivingReportAdded = yield orgNew.addTestDrivingReportG(drivingReportNew);
            res.json({status:'ok',drivingReportAdded:drivingReportAdded});
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    }


    //获取所有的报警信息
    TestDriveAPI.prototype.getAllAlarms = function(req,res){
        co(function*(){
            var args = ApiHelper.makeQueryArgs(req.query);
            var result = yield[bizCore.Alarm.getAllAlarmCountG(args.filter),
                bizCore.Alarm.getAllAlarmG(args.filter,args.pageSize,args.nextMarker)];
            res.json({status:"ok",total:result[0],alarmData:result[1]});
        }).catch(function(ex){
            res.status(500).send(ex.stack);
        });
    };

    // 查询品牌&系列
    TestDriveAPI.prototype.getBrandSeries = function(req, res){
        co(function*(){
            res.json(yield req.incar.testDrive.getBrandSeriesG(req.query.isAll));
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //车辆出车次数
    TestDriveAPI.prototype.StaVehicleTDrivingTimes = function(req,res){
        co(function*(){
            var data = req.query;
            var tm_start = "";
            var tm_end = "";
            var isChart = data['isChart'];
            if(data['tm_start']) tm_start = data['tm_start'];
            if(data['tm_end']) tm_end = data['tm_end'];

            var testDriveCtx = req.incar.testDrive;
            var tdriveId = testDriveCtx.id;
            var statisticsData = yield testDriveCtx.StaTestDrivingTimesG(tdriveId,tm_start,tm_end,isChart);
            if(isChart == "true"){
                var count = yield testDriveCtx.StaTestDrivingTimesCountG(tdriveId,tm_start,tm_end);
                res.json({status:'ok',total:count,statisticsData:statisticsData});
            }else{
                res.json({status:'ok',allTestDrivingTimes:statisticsData});
            }

        }).catch(function(ex){
            res.status(500).send(ex.stack);
        });
    };


    //司机出车次数
    TestDriveAPI.prototype.StaStaffTDrivingTimes = function(req,res){
        co(function*(){
            var data = req.query;
            var tm_start = "";
            var tm_end = "";
            var isChart = data['isChart'];
            if(data['tm_start']) tm_start = data['tm_start'];
            if(data['tm_end']) tm_end = data['tm_end'];
            var testDriveCtx = req.incar.testDrive;
            var tdriveId = testDriveCtx.id;
            var statisticsData = yield testDriveCtx.StaStaffTestDrivingTimesG(tdriveId,tm_start,tm_end,isChart);
            if(isChart == "true"){
                var count =  yield testDriveCtx.StaTestDrivingTimesCountG(tdriveId,tm_start,tm_end);
                res.json({status:'ok',total:count,statisticsData:statisticsData});
            }else{
                res.json({status:'ok',allTestDrivingTimes:statisticsData});
            }
        }).catch(function(ex){
            res.status(500).send(ex.stack);
        });
    };

    //销售员出车次数
    TestDriveAPI.prototype.StaSPTDrivingTimes = function(req,res){
        co(function*(){
            var data = req.query;
            var tm_start = "";
            var tm_end = "";
            var isChart = data['isChart'];
            if(data['tm_start']) tm_start = data['tm_start'];
            if(data['tm_end']) tm_end = data['tm_end'];
            var testDriveCtx = req.incar.testDrive;
            var tdriveId = testDriveCtx.id;
            var statisticsData = yield testDriveCtx.StaSPTestDrivingTimesG(tdriveId,tm_start,tm_end,isChart);
            if(isChart == "true"){
                var count =  yield testDriveCtx.StaTestDrivingTimesCountG(tdriveId,tm_start,tm_end);
                res.json({status:'ok',total:count,statisticsData:statisticsData});
            }else{
                res.json({status:'ok',allTestDrivingTimes:statisticsData});
            }
        }).catch(function(ex){
            res.status(500).send(ex.stack);
        });
    };
    return TestDriveAPI;
})();

module.exports = testDriveAPI;
