(function (app) {
    app.controller('myCtrl', ["$scope", "$state", 'userService', 'msg','config','$timeout', function ($scope, $state, userService,msg,config,$timeout) {
        $scope.user = {};
        $scope.host = config.server +'/upload/avatar/';
        $scope.$on('$ionicView.beforeEnter', function (viewResult) {
            $scope.load(true);
        });
        $scope.load = function (init) {
            userService.getUser().then(function (result) {
                $timeout(function () {
                    $scope.user = result.data.data; 
                });
            }, function (erro) {
                msg.error(erro.data.message);
            });
            $scope.toProfile = function () {
                $state.go('wl.my_profile');
            }
        }
    }]);
    app.controller('mySettingCtrl', ['$scope', 'data', '$state', '$http','$ionicModal','myService', function ($scope, data, $state, $http,$ionicModal,myService) {
        myService.setting().then(function (result) {
            $scope.res = result.data;
        }, function (erro) {
            msg.error(erro);
        });
        $scope.logout = function () {
            data.remove('user');
            data.remove('token');
            $http.defaults.headers.common["Authorization"] =undefined;
            $state.go('login');
        }
        $ionicModal.fromTemplateUrl('low.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function(modal) {
            $scope.modal1 = modal;
        });
        $ionicModal.fromTemplateUrl('compay.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function(modal) {
            $scope.modal2 = modal;
        });
        $scope.openModal1 = function() {
            $scope.modal1.show();
        };
        $scope.closeModal1 = function() {
            $scope.modal1.hide();
        };
        $scope.openModal2 = function() {
            $scope.modal2.show();
        };
        $scope.closeModal2 = function() {
            $scope.modal2.hide();
        };
        // Cleanup the modal when we're done with it!
        $scope.$on('$destroy', function() {
            $scope.modal1.remove();
            $scope.modal2.remove();
        });
    }]);
    app.controller('mySetPasswordCtrl', ['$scope', '$state', 'myService', 'msg', function ($scope, $state, myService, msg) {
        $scope.$on('$ionicView.beforeEnter', function (viewResult) {
            $scope.vm = {
                oldpassword:'',
                password: '',
                password1: '',
            };
        });
        $scope.submit = function (vm) {
            msg.loading('保存中...');
            var model = { old_password: vm.oldpassword, password: vm.password, password_confirmation: vm.password1 };
            myService.resetPassword(model).then(function () {
                msg.hide();
                $scope.data = {
                    oldpassword:'',
                    password: '',
                    password1: '',
                };
                msg.success('密码修改成功');
            }, function (erro) {
                msg.hide();
                msg.error(erro.message);
            });
        }
    }]);
    
    app.controller('myProfileCtrl', ['$scope', '$ionicActionSheet', '$ionicPopup', '$timeout', 'userService', 'msg', 'util', 'data', 'camera','config', function ($scope, $ionicActionSheet, $ionicPopup, $timeout, userService, msg, util, data, camera,config) {
        $scope.user = data.getObject('user');
        $scope.genderOpt = [
              { name: "男", value: 1 },
              { name: "女", value: 0 }
        ];
        $scope.host = config.server +'/upload/avatar/';
     
        $scope.setAvator = function () {
            camera.chooseImage().then(function (imageUri) {
                var uploadOptions = new FileUploadOptions();
                uploadOptions.fileKey = "photo";
                uploadOptions.fileName = "avatar.jpg";
                uploadOptions.mimeType = "image/jpeg";
                uploadOptions.httpMethod = 'post';
                uploadOptions.chunkedMode = true;
                var token = 'Bearer ' + localStorage['token'];
                uploadOptions.headers = { "Authorization": token };
                var ft = new FileTransfer();
                ft.upload(imageUri, encodeURI(config.server + "api/user"), function (sucess) {
                    $timeout(function () {
                        var res = JSON.parse(sucess.response);
                        $scope.user.avatar = res.data.avatar;
                    });
                    console.log('上传成功'+JSON.stringify(sucess.response));
                     //alert('上传成功'+JSON.stringify(sucess));
                }, function (fail) {
                    console.log('上传失败'+JSON.stringify(fail));
                      //alert('上传失败'+JSON.stringify(fail));
                }, uploadOptions);
            }, function (erro) {
                msg.error(erro);
            });
             
        }
        $scope.save = function () {
            data.updateObject('user', $scope.user);
            msg.loading('保存中...');
            userService.update($scope.user).then(function () {
                msg.hide();
                msg.success('保存成功');
            }, function (erro) {
                msg.hide();
                msg.error(erro.data.message);
            });
        }
    }]);
    
    app.controller('myTruckCtrl', ['$scope', '$state', 'myService', 'msg','config', function ($scope, $state, myService, msg,config) {
        $scope.filter = {
            hasMore: false,
            page: 0,
            pageSize: 10,
        }
        $scope.items = [];
        $scope.host = config.server +'/upload/photo/';
        $scope.load = function (init) {
            if (init) {
                $scope.filter.pageIndex = 1;
                $scope.items = [];
            }
            myService.listTrucks($scope.filter).then(function (result) {
                $scope.filter.pageIndex++;
                var more = (result.data.data.length >= $scope.filter.pageSize);
                $scope.filter.hasMore = more;
                $scope.items = $scope.items.concat(result.data.data);
                if (init) {
                    $scope.$broadcast('scroll.refreshComplete');
                } else {
                    $scope.$broadcast('scroll.infiniteScrollComplete');
                }
            }, function (erro) {
                msg.error(erro.data.message);
            });
        }
        $scope.add = function () {
            $state.go('wl.my_truck_add', { item: {}});
        }
        $scope.detail = function (item) {
            $state.go('wl.my_truck_add', {item:item});
        }
        $scope.delete = function (item, $event) {
            $event.stopPropagation();
            msg.confirm('删除提示', '确定删除？').then(function (res) {
                if (res) {
                    msg.loading('删除中...');
                    myService.deleteTruck(item.id).then(function (result) {
                        msg.hide();
                        $scope.load(true);
                    }, function (erro) {
                        msg.hide();
                        msg.error(erro.data.message);
                    })
                } else {

                }
            });
        }
        $scope.$on('$ionicView.beforEnter', function (viewResult) {
            $scope.load(true);
        });
    }]);
    app.controller('myTruckAddCtrl', ['$scope', 'myService', 'msg', '$state', '$stateParams', 'camera', 'config', '$timeout', function ($scope, myService, msg, $state, $stateParams, camera, config, $timeout) {
        $scope.vm = {};
        if ($stateParams.item) {
            $scope.vm = $stateParams.item;
            $scope.vm.type = 1;
            $scope.vm.begin_use_date = new Date($scope.vm.begin_use_date);
            $scope.vm.expire_date = new Date($scope.vm.expire_date);
        }
        $scope.typeOpt = [
            { name: '厢式货车', value: 1 },
            { name: '面包车', value: 2 },
            { name: '金杯车', value: 3 },
        { name: '中巴货车', value: 4 },
        { name: '高栏车', value: 5 },
        { name: '低栏车', value: 6 },
        { name: '平板车', value: 7 },
        { name: '高低板车', value: 8 },
        { name: '半挂车', value: 9 },
        { name: '自卸车', value: 10 },
        { name: '冷藏车', value: 11 },
        { name: '保温车', value: 12 },
        { name: '罐式车', value: 13 },
        { name: '铁笼车', value: 14 },
        { name: '集装箱运输车', value: 15 },
        { name: '大件运输车', value: 16 },
        { name: '危险品车', value: 17 },
        { name: '全挂车', value: 18 },
        { name: '加长挂车', value: 19 },
        { name: '其他', value: 20 }];
        $scope.save = function () {
            msg.loading('保存中...');
            console.log('id '+$scope.vm.id);
            if ($scope.vm.id>0) {
                $scope.vm.photo = null;
                console.log('updateTruck '+ JSON.stringify($scope.vm));
                myService.updateTruck($scope.vm).then(function (result) {
                    msg.hide();
                    $state.go('wl.my_truck');
                }, function (erro) {
                    msg.hide();
                    msg.error(erro.data.message);
                });
            } else {
                myService.addTruck($scope.vm).then(function (result) {
                    msg.hide();
                    $state.go('wl.my_truck');
                }, function (erro) {
                    msg.hide();
                    msg.error(erro.data.message);
                });
            }
         
        }
        //上传图片 
        $scope.host = config.server +'/upload/photo/';
        $scope.setPhoto = function () {
            camera.chooseImage().then(function (imageUri) {
                var uploadOptions = new FileUploadOptions();
                uploadOptions.fileKey = "photo";
                uploadOptions.fileName = "photo.jpg";
                uploadOptions.mimeType = "image/jpeg";
                uploadOptions.httpMethod = 'post';
                var id = '';
                if ($scope.vm.id>0) {
                    id = '/'+$scope.vm.id;
                }
                uploadOptions.chunkedMode = true;
                var token = 'Bearer ' + localStorage['token'];
                uploadOptions.headers = { "Authorization": token };
                
                var ft = new FileTransfer();
                    ft.upload(imageUri, encodeURI(config.server + "api/trucks" + id), function (sucess) {
                        $timeout(function () {
                            var res = JSON.parse(sucess.response);
                            $scope.vm.id = res.data.id;
                            $scope.vm.photo = res.data.photo;
                        });
                        console.log('上传成功'+JSON.stringify(sucess.response));
                        //alert('上传成功'+JSON.stringify(sucess));
                    }, function (fail) {
                        console.log('上传失败'+JSON.stringify(fail));
                        //alert('上传失败'+JSON.stringify(fail));
                    }, uploadOptions);
            }, function (erro) {
                msg.error(erro);
            });

        }
     
    }]);
    app.controller('myTruckDetailCtrl', ['$scope', function ($scope) {

    }]);
    app.controller('myMessageCtrl', ['$scope', 'myService', 'msg', '$state', function ($scope, myService, msg, $state) {
        $scope.filter = {
            hasMore: false,
            page: 0,
            pageSize: 10,
        }
        $scope.shouldShowDelete = false;
        $scope.items = [];
        $scope.load = function (init) {
            if (init) {
                $scope.filter.pageIndex = 1;
                $scope.items = [];
            }
            myService.listMessages($scope.filter).then(function (result) {
                $scope.filter.pageIndex++;
                var more = (result.data.data.length >= $scope.filter.pageSize);
                $scope.filter.hasMore = more;
                $scope.items = $scope.items.concat(result.data.data);
                 
                if (init) {
                    $scope.$broadcast('scroll.refreshComplete');
                } else {
                    $scope.$broadcast('scroll.infiniteScrollComplete');
                }
            }, function (erro) {
                msg.error(erro.data.message);
            });
        }
        $scope.close = function () {
            if ($scope.shouldShowDelete) {
                $scope.shouldShowDelete = false;
            } else {
                $scope.shouldShowDelete = true;
            }
            
        }
        $scope.detail = function (item) {
            $state.go('wl.my_message_detail', { item: item });
        }
        $scope.closeItem = function (item, $index) {
            $scope.items.splice($index, 1);
            item.state = 10;
            myService.updateMessage(item).then(function () {
            }, function (erro) {
                msg.error(erro.data.message);
            });
        }
        $scope.$on('$ionicView.beforeEnter', function (viewResult) {
            $scope.load(true);
        });
    }]);
    app.controller('myMessageDetailCtrl', ['$scope', '$stateParams', function ($scope, $stateParams) {
        $scope.vm = $stateParams.item;
        
    }]);
    app.controller('myOrderCtrl', ['$scope', 'myService', 'msg', '$state', function ($scope, myService, msg, $state) {
        $scope.filter = {
            hasMore: false,
            page: 0,
            pageSize: 10,
        }
        $scope.items = [];
        $scope.load = function (init) {
            if (init) {
                $scope.filter.pageIndex = 1;
                $scope.items = [];
            }
            myService.listOrders($scope.filter).then(function (result) {
                $scope.filter.pageIndex++;
                var more = (result.data.data.length >= $scope.filter.pageSize);
                $scope.filter.hasMore = more;
                $scope.items = $scope.items.concat(result.data.data);
              
                if (init) {
                    $scope.$broadcast('scroll.refreshComplete');
                } else {
                    $scope.$broadcast('scroll.infiniteScrollComplete');
                }
            }, function (erro) {
                msg.error(erro.data.message);
            });
        }
        $scope.pay = function (item,$event) {
            $event.stopPropagation();
            msg.text('支付尚未开通，敬请期待');
            //var price = item.message.data.price;
            //window.alipay.pay({
            //    tradeNo: new Date().getTime(),
            //    subject: "测试标题",
            //    body: "我是测试内容",
            //    price: price,
            //    notifyUrl: "http://your.server.notify.url"
            //}, function (successResults) { alert(successResults) }, function (errorResults) { alert(errorResults) });
            //to do 
        }
        $scope.delete = function (item,$event) {
            $event.stopPropagation();
            msg.confirm('删除提示', '确定删除？').then(function (res) {
                if (res) {
                    msg.loading('删除中...');
                    myService.deleteOrder(item.id).then(function (result) {
                        msg.hide();
                        $scope.load(true);
                    }, function (erro) {
                        msg.hide();
                        msg.error(erro.data.message);
                    })
                } else {

                }
            });
        }
        $scope.detail = function (item) {
            $state.go('wl.my_order_detail', { item: item });
        }
        $scope.$on('$ionicView.beforeEnter', function (viewResult) {
            $scope.load(true);
        });
    }]);
    app.controller('myOrderDetailCtrl', ['$scope', '$stateParams', function ($scope, $stateParams) {
        $scope.vm = $stateParams.item;
    }]);
})(angular.module('app.controllers'));