starter.factory('Tool', function ($http, $q, $translate, $ionicHistory) {
    var tempData = {};
    var translates = {
        "weekdays": ['sundayTitle', 'mondayTitle', 'tuesdayTitle', 'wednesdayTitle', 'thursdayTitle', 'fridayTitle', 'saturdayTitle']
    };
    return {
        trim: function (str) {
            if (str == null) {
                str = "";
            }
            return str.replace(/(^\s*)|(\s*$)/g, "");
        },
        cloneObj: function (obj) {
            if (obj == null) {
                return null
            }
            var str, newobj = obj.constructor === Array ? [] : {};
            if (typeof obj !== 'object') {
                return;
            } else if (window.JSON) {
                str = JSON.stringify(obj), //系列化对象
                    newobj = JSON.parse(str); //还原
            } else {
                for (var i in obj) {
                    newobj[i] = typeof obj[i] === 'object' ?
                        cloneObj(obj[i]) : obj[i];
                }
            }
            return newobj;
        },
        getTempData: function (key) {
            return tempData[key]
        },
        setTempData: function (key) {
            tempData[key] = []
        },
        get: function (url, iscache, key) {
            var deferred = $q.defer();
            iscache = iscache || false;
            $http.get(url).then(function (res) {
                    deferred.resolve(res.data);
                    if (iscache)
                        tempData[key] = res.data;
                },
                function (err) {
                    deferred.reject(err);
                });
            return deferred.promise;
        },
        post: function (url, data, isjson) {
            var deferred = $q.defer();
            var header = null;
            if (isjson == false) {
                header = {
                    'Content-Type': 'application/x-www-form-urlencoded'
                };
            }
            $http.post(url, data, {
                headers: header
            }).then(function (res) {
                    deferred.resolve(res.data);
                },
                function (err) {
                    deferred.reject(err);
                })
            return deferred.promise;

        },
        patch: function (url, data) {
            var deferred = $q.defer();
            $http.patch(url, data).then(function (res) {
                deferred.resolve(res.data);
            }, function (err) {
                deferred.resolve(err);
            });
            return deferred.promise;
        },
        put: function (url, data, iscache) {
            var deferred = $q.defer();
            iscache = iscache || false;
            $http.put(url, data).then(function (res) {
                    deferred.resolve(res.data);
                    if (iscache)
                        tempData = res.data;
                },
                function (err) {
                    deferred.reject(err);
                });
            return deferred.promise;
        },
        delete: function (url) {
            var deferred = $q.defer();
            $http.delete(url).then(function (res) {
                    deferred.resolve(res.data);
                },
                function (err) {
                    deferred.reject(err);
                });
            return deferred.promise;
        },
        getTranslateByKey: function (type, key) {
            if (translates[type] === undefined || translates[type][key] === undefined)
                return null;
            return $translate.instant(translates[type][key]);
        },
        removeBackView: function (routes) {
            var view = $ionicHistory.backView();
            if (!view)
                return;
            if (!(_.isArray(routes)))
                routes = [routes];
            _.find(routes, function (route) {
                if (view.stateName == route) {
                    return $ionicHistory.removeBackView();
                }
            });
        }
    }
})

.factory('showPopup', function ($timeout, $ionicLoading, $ionicPopup, $rootScope, $ionicModal) {
    var typeArr = [
        '<i class="icon icon-warn" style="font-size:3em;"></i><br/>',
        '<ion-spinner icon="android"></ion-spinner><br/>'
    ];

    function showLoadingToast(type, text, isShowBackDrop) {
        if (isShowBackDrop == undefined) {
            isShowBackDrop = true;
        }
        // Setup the loader
        $ionicLoading.show({
            template: typeArr[type] + text,
            animation: 'fade-in',
            showBackdrop: isShowBackDrop,
            maxWidth: 200,
            Showdelay: 0
        });
    }

    function hideLoadingToast() {
        $ionicLoading.hide();
    }

    function popupInfo(type, text, isShowBackDrop, delay) {
        if (delay == undefined) {
            delay = 1500;
        }
        //弹出缓冲提示
        showLoadingToast(type, text, isShowBackDrop);
        //这里使用定时器是为了缓存一下加载过程，防止加载过快
        $timeout(function () {
            //停止缓冲提示
            hideLoadingToast();
        }, delay);
    }

    return {
        //触发函数
        PopupWindow: function (type, text, isShowBackDrop, delay) {
            popupInfo(type, text, isShowBackDrop, delay);
        },
        hideLoading: function () {
            hideLoadingToast();
            $rootScope.commons.isShowPopup = false;
        },
        showLoading: function (type, text, isShowBackDrop, delay) {
            showLoadingToast(type, text, isShowBackDrop);
            $rootScope.commons.isShowPopup = true;
            delay = delay || 10000;
            $timeout(function () {
                if ($rootScope.commons.isShowPopup) {
                    $ionicLoading.hide();
                    console.log(self);
                    popupInfo(0, '请求超时！', false);
                    $rootScope.commons.isShowPopup = false;
                }
            }, delay);
        },
        confirm: function (title, okText, cancelText) {
            var confirmpopup = $ionicPopup.confirm({
                title: '<br/><div>' + title + '</div><br/>',
                okText: okText,
                cancelText: cancelText
            });
            return confirmpopup;
        },
        showSelectImgPopup: function (camera, imagePicker, scope) {
            var optionsPopup = $ionicPopup.show({
                templateUrl: '../../templates/template-selectimg.html',
                scope: scope
            });
            scope.Camera = camera;
            scope.ImagePicker = imagePicker;
            return optionsPopup;
        },
        modalTemplate: function (templateurl, animation, scope) {
            return $ionicModal.fromTemplateUrl(templateurl, {
                scope: scope,
                animation: animation,
                focusFirstInput: true
            })
        }
    }
})

.factory('ImageManage', function ($q, $cordovaCamera, $cordovaImagePicker, $cordovaFileTransfer, $cordovaFile, $http, cfg, formatFilter, Tool) {
    var Qiniu_UploadUrl = "http://up.qiniu.com";

    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    function guid() {
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    return {
        ImagePicker_getPictures: function (_imagecount) {
            if (_imagecount == undefined) {
                _imagecount = 1;
            }
            var deferred = $q.defer();
            var options = {
                maximumImagesCount: _imagecount,
                quality: 30
            };
            var promises = [];
            $cordovaImagePicker.getPictures(options).then(function (results) {
                _.each(results, function (res) {
                    var deferred1 = $q.defer();
                    $cordovaFile.readFileMetadata(cordova.file.cacheDirectory, res.substr(res.lastIndexOf('/') + 1)).then(function (metadata) {
                        console.log(metadata);
                    }, function (error) {
                        console.log(error);
                    });
                    $cordovaFile.readAsDataURL(cordova.file.cacheDirectory, res.substr(res.lastIndexOf('/') + 1)).then(function (base64) {
                        deferred1.resolve(base64);
                    }, function (error) {
                        deferred1.reject(error);
                        console.log(error);
                    });
                    // deferred1.resolve(res);
                    promises.push(deferred1.promise);
                });
                deferred.resolve(promises);
            }, function (err) {
                deferred.reject(err);
            });
            return deferred.promise;
        },
        Camera_getPicture: function (_allowEdit) {
            if (_allowEdit == undefined) {
                _allowEdit = false;
            }
            var deferred = $q.defer();
            var options = {
                quality: 30,
                destinationType: Camera.DestinationType.DATA_URL,
                sourceType: Camera.PictureSourceType.CAMERA,
                allowEdit: _allowEdit,
                encodingType: Camera.EncodingType.JPEG,
                popoverOptions: CameraPopoverOptions,
                saveToPhotoAlbum: true,
                correctOrientation: true
            };
            $cordovaCamera.getPicture(options).then(function (imageData) {
                deferred.resolve("data:image/jpeg;base64," + imageData);
            }, function (err) {
                deferred.reject(err);
            });
            return deferred.promise;
        },
        upload: function (fileurls, token, _filepath) {
            var promises = [];
            var files = fileurls;
            var options = new FileUploadOptions();
            if (!_.isArray(files)) {
                files = [];
                files.push(fileurls);
            }
            _.each(files, function (itemfile) {
                var params = {};
                options.params = params;
                params.token = token;
                params.mimeType = "image/jpg";
                params.key = _filepath + guid() + itemfile.substr(itemfile.lastIndexOf('.'));
                promises.push($cordovaFileTransfer.upload(Qiniu_UploadUrl, itemfile, options, true));
            });
            return $q.all(promises);
        },
        getToken: function (app, id, cls) {
            var url = formatFilter('{0}qiniuupload/?app={1}&cls={2}&pk={3}', cfg.api, app, cls, id);
            return $http.get(url);
        },
        get_upload_Token: function (_url, compid) {
            var url = formatFilter('{0}{1}/{2}/', cfg.api, _url, compid);
            return $http.get(url);
        },
        uploadImage: function (fileurls, app, id, cls) {
            var url = formatFilter('{0}qiniuupload/?app={1}&cls={2}&pk={3}', cfg.api, app, cls, id);
            var defreed1 = $q.defer();
            Tool.get(url).then(function (data) {
                var promises = [];
                var files = fileurls;
                var options = new FileUploadOptions();
                if (!_.isArray(files)) {
                    files = [];
                    files.push(fileurls);
                }
                _.each(files, function (itemfile) {
                    var params = {};
                    options.params = params;
                    params.token = data.token;
                    params.mimeType = "image/jpg";
                    params.key = data.filepath + guid() + itemfile.substr(itemfile.lastIndexOf('.'));
                    var deferred = $q.defer();
                    $cordovaFileTransfer.upload(Qiniu_UploadUrl, itemfile, options, true).then(function (res) {
                        deferred.resolve(res);
                    }, function (err) {
                        deferred.reject(err);
                    });
                    promises.push(deferred.promise);
                });
                defreed1.resolve(promises);
            }, function (err) {
                defreed1.reject(err);
                alert('get upload token error' + JSON.stringify(err));
            });
            return defreed1.promise;
        }
    }
})

.factory('Member', function () {
    var member = {};
    var defaultmember = {};
    member.resourcemember = []; //基础数据
    member.selectedemplst = []; //选中的员工数据
    member.selecteddepts = []; //选中的部门数据
    member.isallcheck = false; //是否选中全部成员(部门)
    member.unenabledata = [];//未启用的数据（禁用的数据）

    member.homerenderdata = []; //目前为展示部门数据

    member.routename = ''; //点击确定后需要跳转的路由名称，默认是goBack();
    member.routeparams = {}; //"确定" 路由参数
    member.cancelroutename = ''; //点击取消后需要跳转的路由名称，默认是goBack();
    member.cancelrouteparams = {}; //"取消" 路由参数
    member.titlename = "选择成员"; //页面显示的标题名称
    member.datatype = ''; //成员类型 0:不计考勤成员 1:可查看考勤统计成员
    member.disabled = true; //是否需要禁用基础数据
    member.hide = false; //是否需要隐藏基础数据
    member.dialogresult = 1; //0:是点击了取消按钮退出，1:点击了确定按钮
    member.showall = false; //默认不显示‘全部成员’栏位
    member.showgroup = false; //默认不显示‘选择小组’栏位
    member.all = 1; // 全部成员/部分成员  :  1/0
    member.customerop = null; //自定义操作

    member.member = {};//用来存放相对应部门的员工数据，一部门ID作为key
    return member;
})

.factory('Dept', function ($http, $q, cfg, formatFilter, Tool, global) {
    var deptlst = [];
    var resultdept = new Array();
    var resultemp = new Array();
    return {
        selecteddepts: [], //存放被选中的部门集合
        titleName: {
            name: ''
        },
        save: function (up_depts, del_deptids, add_depts, compid) {
            var datas = [];
            if (del_deptids.length > 0) {
                datas.push({
                    "op": "del",
                    "values": del_deptids
                });
            }
            if (add_depts.length > 0) {
                datas.push({
                    "op": "add",
                    "values": add_depts
                });
            }
            if (up_depts.length > 0) {
                datas.push({
                    "op": "up",
                    "values": up_depts
                });
            }
            var url = formatFilter('{0}depts/?compid={1}', cfg.api, compid);
            return Tool.patch(url, datas)
        },
        all: function () {
            deptlst = Tool.getTempData('deptlist') || [];
            return deptlst;
        },
        setdeptlst: function (data) {
            deptlst = data;
            Tool.setTempData('deptlist')
        },
        getDep: function (compid) {
            var url = formatFilter('{0}depts/', cfg.api);
            if (compid) {
                url = formatFilter('{0}depts/?compid={1}', cfg.api, compid);
            }
            return Tool.get(url, true, 'deptlist')
        },
        getEmp: function (deptid, compid) {
            var url = formatFilter('{0}usrs/', cfg.api);
            if (deptid != undefined) {
                url = formatFilter('{0}usrs/?deptid={1}', cfg.api, deptid);
            }
            if (compid != undefined && deptid != undefined) {
                url = formatFilter('{0}usrs/?compid={1}&deptid={2}', cfg.api, compid, deptid);
            }
            return Tool.get(url)
        },
        getChildDept: function (pid) {
            return _.filter(this.all(), function (dept) {
                return parseInt(dept.parent) == parseInt(pid);
            });
        },
        getUsrDetail: function () {
            return Tool.get(formatFilter('{0}usrs/{1}/?compid={2}', cfg.api, global.user.usrid, global.user.compno), true, 'userinfo');
        },
        putUsrInfo: function (data) {
            data.dept = data.dept_id;
            data = _.pick(data, 'username', 'sex', 'dept', 'degree', 'email');
            return Tool.put(formatFilter('{0}usrs/{1}/', cfg.api, global.user.usrid), data)
        }
    };
})

.factory('General', function ($http, $q, cfg, global, formatFilter) {
    var Comment = {};
    var Read = {};
    return {
        getComment: function (id, module) {
            var url = formatFilter('{0}{1}/comments/?{2}id={3}', cfg.api, module, module, id);
            var deferred = $q.defer();
            $http.get(url).then(function (res) {
                    deferred.resolve(res.data);
                    Comment = res.data;
                },
                function (err) {
                    deferred.reject(err);
                });
            return deferred.promise;
        },
        getRead: function (id, module, type) {
            var url = formatFilter('{0}{1}/readeds/?{2}id={3}', cfg.api, module, module, id);
            if (type != undefined) {
                url += '&type=unreads'
            }
            var deferred = $q.defer();
            $http.get(url).then(function (res) {
                    deferred.resolve(res.data);
                },
                function (err) {
                    deferred.reject(err);
                });
            return deferred.promise;
        },
        postComment: function (data, module) {
            var url = formatFilter('{0}{1}/comment/', cfg.api, module);
            var deferred = $q.defer();
            $http.post(url, data, {
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(function (res) {
                    console.log(res.data)
                    deferred.resolve(res.data);
                    res.data.user__username = global.user.usrname;
                    res.data.user_id = global.user.usrid;
                    res.data.create_dd = new Date();
                    Comment.splice(0, 0, res.data);
                },
                function (err) {
                    deferred.reject(err);
                });
            return deferred.promise;
        },
        postRead: function (data, module) {
            console.log(Read)
            var url = formatFilter('{0}{1}/readeds/', cfg.api, module);
            var deferred = $q.defer();
            $http.post(url, data, {
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(function (res) {
                    deferred.resolve(res.data);
                },
                function (err) {
                    deferred.reject(err);
                });
            return deferred.promise;
        },
        deleteComment: function (id, module) {
            var comment = _.find(Comment, function (item) {
                if (item.id === parseInt(id)) {
                    return item;
                }
            })
            if (comment != undefined) {
                Comment.splice(Comment.indexOf(comment), 1);
                var url = formatFilter('{0}{1}/comment/{2}/', cfg.api, module, id);
                return $http.delete(url);
            }
        }
    }
})
