(function (app) {
    //公共服务
    app.factory('common', ['$http', 'config', '$q', 'msg', function ($http, config, $q, msg) {
        return {
            //经营范围
            getSetting: function (category) {
                return $http({
                    url: config.server + 'api/setting/get/' + category,
                    method: "get"
                })
            },
            //选择图片
            chooseImage: function (cameraOptions) {
                var deferred = $q.defer();
                var defaultCameraOptions = {
                    quality: 50,
                    sourceType: 1,
                    allowEdit: true,
                    encodingType: 0,//0为jpg,1为png
                    //targetHeight: 112,
                    //targetWidth: 112
                };
                var options = angular.extend(defaultCameraOptions, cameraOptions);
                var sheetOptions = {
                    title: '选择图片方式',
                    buttonLabels: ['拍摄照片', '从相册选择'],
                    addCancelButtonWithLabel: '取消',
                    androidEnableCancelButton: true
                };
                window.plugins.actionsheet.show(sheetOptions, function (index) {
                    switch (index) {
                        case 1: //拍摄图片
                            options.sourceType = 1;
                            break;
                        case 2://从图库选择
                            options.sourceType = 2;
                            break;
                        default:
                            return;
                            deferred.resolve();
                            break;
                    }
                    navigator.camera.getPicture(function (imageUri) {
                        if (imageUri) {
                            deferred.resolve(imageUri);
                        } else {
                            deferred.reject('图片未找到');
                        }
                    }, function (error) {
                      
                        deferred.reject(error);
                    }, options);
                });
                return deferred.promise;
            },
            //选择视频
            chooseVideo: function () {
                var deferred = $q.defer();
                var sheetOptions = {
                    title: '选择视频方式',
                    buttonLabels: ['拍摄视频', '从相册选择'],
                    addCancelButtonWithLabel: '取消',
                    androidEnableCancelButton: true
                };
                window.plugins.actionsheet.show(sheetOptions, function (index) {
                    switch (index) {
                        case 1: //拍摄视频
                            var options1 = { limit: 1, duration:20};
                            navigator.device.capture.captureVideo(function (videos) {
                                if (videos[0]) {
                                    deferred.resolve(videos[0].fullPath);
                                } else {
                                    deferred.reject("视频未找到");
                                }
                            }, function (error) {
                                deferred.reject(error);
                            }, options1);
                            break;
                        case 2://从相册选择
                            var options2 = {
                                quality:100,
                                sourceType: 0,
                                mediaType: 1
                            };
                            navigator.camera.getPicture(function (imageUri) {
                                if (imageUri) {
                                    deferred.resolve(imageUri);
                                } else {
                                    deferred.reject('视频未找到');
                                }
                            }, function (error) {
                                deferred.reject(error);
                            }, options2);
                            break;
                        default:
                            deferred.resolve();
                            break;
                    }
                });
                return deferred.promise;
            },
            uploadFiles: function (imageUri,type) {//通用上传,type:1图片,2视频
                var deferred = $q.defer();
                if (imageUri) {
                    var uploadOptions = new FileUploadOptions();
                    if (type==1) {//图片
                        uploadOptions.fileKey = "picture";
                        uploadOptions.fileName = "picture.jpg";
                        uploadOptions.mimeType = "image/jpeg";
                        uploadOptions.params = { tag: "dream" };
                    }
                    if (type==2) {//视频
                        uploadOptions.fileKey = "video";
                        uploadOptions.fileName = "video.mp4";
                        uploadOptions.mimeType = "video/mpeg";
                        uploadOptions.params = { tag: "video" };
                    }
                    if (type == 3) {//头像
                        uploadOptions.fileKey = "avatar";
                        uploadOptions.fileName = "avatar.jpg";
                        uploadOptions.mimeType = "image/jpeg";
                        uploadOptions.params = { tag: "avatar" };
                    }
                    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/attachment/upload"), function (sucess) {
                        deferred.resolve(sucess);
                        //  alert('上传成功' + JSON.stringify(sucess));
                    }, function (fail) {
                        deferred.reject(fail);
                        //alert('上传失败' + JSON.stringify(fail));
                    }, uploadOptions);
                } else {
                    deferred.reject('图片未找到');
                }
                return deferred.promise;
            },
            deletefile:function (file) {
                return $http({
                    url: config.server + 'api/attachment/delete/' + file,
                    method: "get"
                })
            },
            setAvator: function () {//上传头像
                var deferred = $q.defer();
                this.chooseImage().then(function (imageUri) {
                    msg.text('上传中');
                    var uploadOptions = new FileUploadOptions();
                    uploadOptions.fileKey = "avatar";
                    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/auth/avatar"), function (sucess) {
                        msg.hide();
                        deferred.resolve(sucess);
                        //  alert('上传成功' + JSON.stringify(sucess));
                    }, function (fail) {
                        msg.hide();
                        deferred.reject(fail);
                        alert('上传失败' + JSON.stringify(fail));
                    }, uploadOptions);
                });
                return deferred.promise;
            },
            continue_consume: function (data) {
                var deferred = $q.defer();
                $http({
                    url: config.server + 'api/service/continue_consume',
                    method: "post",
                    data: data
                }).success(function (result) {
                    console.log("result pay:"+JSON.stringify(result));
                    var payInfo = result.data.orderString;
                    if (data.pay_type == "alipay_app") {
                        //支付宝
                        console.log("result AliPay");
                        cordova.plugins.AliPay.pay(payInfo, function success(e) {
                            //e.resultStatus  状态代码  e.result  本次操作返回的结果数据 e.memo 提示信息
                            //e.resultStatus  9000  订单支付成功 ;8000 正在处理中  调用function success
                            //e.resultStatus  4000  订单支付失败 ;6001  用户中途取消 ;6002 网络连接出错  调用function error
                            //当e.resultStatus为9000时，请去服务端验证支付结果
                            //  alert('状态码：' + e.resultStatus);
                            if (e.resultStatus == '9000') {
                                deferred.resolve(e.resultStatus);
                            } else {
                                deferred.reject(e);
                            }
                        }, function error(e) {
                            deferred.reject(e);
                        });
                    }
                    if (data.pay_type== "wechatpay_app") { //微信
                        window.wxpay.payment({
                            appid: payInfo.appid,
                            noncestr: payInfo.noncestr,
                            package: payInfo.package,
                            partnerid: payInfo.partnerid,
                            prepayid: payInfo.prepayid,
                            timestamp: payInfo.timestamp,
                            sign: payInfo.sign
                        }, function success(msg) {
                            console.log("wxpay success:"+JSON.stringify(msg));
                            deferred.resolve(msg);
                        }, function error(e) {
                            console.log("wxpay error:"+JSON.stringify(e));
                            deferred.reject(e);
                        })
                    }
                }).error(function (error) {
                  //  alert(JSON.stringify(error));
                    deferred.reject(error);
                });
                return deferred.promise;
            },
            pay: function (data) {
                var deferred = $q.defer();
                $http({
                    url: config.server + 'api/merchant/charge',
                    method: "post",
                    data: data
                }).success(function (result) {
                    console.log("result pay:"+JSON.stringify(result));
                    var payInfo = result.data.orderString;
                    if (data.type == 1) {
                        //支付宝
                        cordova.plugins.AliPay.pay(payInfo, function success(e) {
                            //e.resultStatus  状态代码  e.result  本次操作返回的结果数据 e.memo 提示信息
                            //e.resultStatus  9000  订单支付成功 ;8000 正在处理中  调用function success
                            //e.resultStatus  4000  订单支付失败 ;6001  用户中途取消 ;6002 网络连接出错  调用function error
                            //当e.resultStatus为9000时，请去服务端验证支付结果
                            //  alert('状态码：' + e.resultStatus);
                            if (e.resultStatus == '9000') {
                                deferred.resolve(e.resultStatus);
                            } else {
                                deferred.reject(e);
                            }
                        }, function error(e) {
                            deferred.reject(e);
                        });
                    }
                    if (data.type==2) { //微信
                        window.wxpay.payment({
                            appid: payInfo.appid,
                            noncestr: payInfo.noncestr,
                            package: payInfo.package,
                            partnerid: payInfo.partnerid,
                            prepayid: payInfo.prepayid,
                            timestamp: payInfo.timestamp,
                            sign: payInfo.sign
                        }, function success(msg) {
                            console.log("wxpay success:"+JSON.stringify(msg));
                            deferred.resolve(msg);
                        }, function error(e) {
                            console.log("wxpay error:"+JSON.stringify(e));
                            deferred.reject(e);
                        })
                    }
                }).error(function (error) {
                  //  alert(JSON.stringify(error));
                    deferred.reject(error);
                });
                return deferred.promise;
            }
        };
    }]);
})(angular.module('app.services'));