/********************************************************
Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved. 
 创建人   : joe Song
 创建时间 : 2016-03-10
说明     :  GetData & SaveData实现
*********************************************************/
(function () {
    'use strict';
    angular.module('xrmApp')
        .service('rtData', ['$http', 'rtRestClient', 'rtUtils',function ($http, rtRestClient,rtUtils) {

            /**
             * 根据配置条件查询实体的数据
             * @param getDataName 配置文件中配置的查询节点的名字
             * @param paramsList 传入后端的查询条件
             * @param orderby 排序字段
             * @param pageIndex 当前页码
             * @param success 成功后的回调函数
             * @param error 失败后的回调函数
             * @returns DataListModel的对象
             */
            this.queryPagingData = function(getDataName,paramsList,orderby,pageIndex,success,error){
                rtRestClient.post("api/DataService/Query",{
                    GetDataName:getDataName,
                    Paramslist:paramsList,
                    Orderby:orderby,
                    PageSize:rtUtils.getPaginationSize(),
                    PageIndex:pageIndex
                }).success(function(dataString){
                    var data = JSON.parse(decodeURIComponent(dataString));
                    if(success){
                        success(data);
                    }
                }).error(function(msg){
                    if(error){
                        error(msg);
                    }
                    else{
                        rtUtils.showErrorToast(msg);
                    }
                });
            };

            /**
             * 根据配置条件查询实体的数据(过滤权限)
             * @param getDataName 配置文件中配置的查询节点的名字
             * @param paramsList 传入后端的查询条件
             * @param orderby 排序字段
             * @param pageIndex 当前页码
             * @param success 成功后的回调函数
             * @param error 失败后的回调函数
             * @returns DataListModel的对象
             */
            this.filteredQueryPagingData = function(getDataName,paramsList,orderby,pageIndex,success,error){
                rtRestClient.post("api/DataService/FilteredQuery",{
                    GetDataName:getDataName,
                    Paramslist:paramsList,
                    Orderby:orderby,
                    PageSize:rtUtils.getPaginationSize(),
                    PageIndex:pageIndex
                }).success(function(dataString){
                    var data = JSON.parse(decodeURIComponent(dataString));
                    if(success){
                        success(data);
                    }
                }).error(function(msg){
                    if(error){
                        error(msg);
                    }
                    else{
                        rtUtils.showErrorToast(msg);
                    }
                });
            };

            /**
             * 根据配置条件查询实体的数据
             * @param getDataName 配置文件中配置的查询节点的名字
             * @param paramsList 传入后端的查询条件
             * @param success 成功后的回调函数
             * @param error 失败后的回调函数
             * @returns DataListModel的对象
             */
            this.queryData = function(getDataName,paramsList,success,error){
                rtRestClient.post("api/DataService/Query",{
                    GetDataName:getDataName,
                    Paramslist:paramsList
                }).success(function(dataString){
                    var data = JSON.parse(decodeURIComponent(dataString));
                    if(success){
                        success(data);
                    }
                }).error(function(msg){
                    if(error){
                        error(msg);
                    }
                    else{
                        rtUtils.showErrorToast(msg);
                    }
                });
            };

            /**
             * 根据配置条件查询实体的数据(过滤权限)
             * @param getDataName 配置文件中配置的查询节点的名字
             * @param paramsList 传入后端的查询条件
             * @param success 成功后的回调函数
             * @param error 失败后的回调函数
             * @returns DataListModel的对象
             */
            this.filteredQueryData = function(getDataName,paramsList,success,error){
                rtRestClient.post("api/DataService/FilteredQuery",{
                    GetDataName:getDataName,
                    Paramslist:paramsList
                }).success(function(dataString){
                    var data = JSON.parse(decodeURIComponent(dataString));
                    if(success){
                        success(data);
                    }
                }).error(function(msg){
                    if(error){
                        error(msg);
                    }
                    else{
                        rtUtils.showErrorToast(msg);
                    }
                });
            };

            /**
             * 根据实体的Id获取实体的数据
             * @param entityName 实体的名字
             * @param id 主键字段
             * @param success 成功后的回调函数
             * @param error 失败后的回调函数
             */
            this.getData = function(entityName,id,success,error){
                rtRestClient.get("api/DataService/Get?entityName="+entityName + "&id=" + id)
                    .success(function(dataString){
                    var data = JSON.parse(decodeURIComponent(dataString));
                    if(success){
                        success(data);
                    }
                }).error(function(msg){
                    if(error){
                        error(msg);
                    }
                    else{
                        rtUtils.showErrorToast(msg);
                    }
                });
            };

            /**
             * 根据实体的Id获取实体的数据(过滤权限)
             * @param entityName 实体的名字
             * @param id 主键字段
             * @param success 成功后的回调函数
             * @param error 失败后的回调函数
             */
            this.filteredGetData = function(entityName,id,success,error){
                rtRestClient.get("api/DataService/FilteredGet?entityName="+entityName + "&id=" + id)
                    .success(function(dataString){
                        var data = JSON.parse(decodeURIComponent(dataString));
                        if(success){
                            success(data);
                        }
                    }).error(function(msg){
                        if(error){
                            error(msg);
                        }
                        else{
                            rtUtils.showErrorToast(msg);
                        }
                    });
            };

            /**
             * 插入或者更新实体数据
             * @param entityName 实体的名字
             * @param id 主键字段
             * @param obj 要插入数据的对象
             * @param success 成功后的回调函数
             * @param error 失败后的回调函数
             */
            this.saveData = function(entityName,id,obj,success,error){
                rtRestClient.post("api/DataService/Save",{
                    EntityName:entityName,
                    Fields:obj,
                    Id:id
                }).success(function(){
                    if(success){
                        success();
                    }
                }).error(function(msg){
                    if(error){
                        error(msg);
                    }
                    else{
                        rtUtils.showErrorToast(msg);
                    }
                });
            };

            /**
             * 删除实体数据
             * @param entityName 实体的名字
             * @param id 主键字段
             * @param success 成功后的回调函数
             * @param error 失败后的回调函数
             */
            this.deleteData = function(entityName,id,success,error){
                rtRestClient.post("api/DataService/Delete",{
                    EntityName:entityName,
                    Id:id
                }).success(function(){
                    if(success){
                        success();
                    }
                }).error(function(msg){
                    if(error){
                        error(msg);
                    }
                    else{
                        rtUtils.showErrorToast(msg);
                    }
                });
            };
        }]);
})();
/********************************************************
Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved. 
 创建人   : joe Song
 创建时间 : 2016-03-10
 说明     : 封装文件上传下载部分的公用函数
*********************************************************/
(function () {
    'use strict';
    angular.module('xrmApp')
        .service('rtFile', ['rtRestClient', 'rtUtils', '$q', function (rtRestClient, rtUtils, $q) {
            this.downloadFile = function (moduleType, fileId) {
                var baseurl = '/FileDownloadHandler.ashx?moduleType=' + moduleType + '&fileid=' + fileId;
                window.open(baseurl, "_self", 'toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no', true);
            };

            this.uploadBase64File = function (fileContent, moduleType, objectId, isoverwrite, success) {
                if (rtUtils.isNullOrWhiteSpace(objectId)) {
                    rtUtils.showErrorToast("objectId can not be null");
                    return;
                }

                if (rtUtils.isNullOrWhiteSpace(fileContent)) {
                    rtUtils.showErrorToast("fileContent can not be null");
                    return;
                }

                if (rtUtils.isNull(isoverwrite)) {
                    isoverwrite = true;
                }

                var data = {
                    ObjectId: objectId,
                    IsOverWrite: isoverwrite,
                    ModuleType: moduleType,
                    FileBase64Content: fileContent
                };
                var apiUrl = "api/File/UploadFile";

                rtRestClient.post(apiUrl, data)
                    .error(function (msg) {
                        rtUtils.showErrorToast(msg);
                    })
                    .success(function (data) {
                        if (success && rtUtils.isFunction(success)) {
                            success(data);
                        }
                    })
            };

            this.GetFilesByObjectId = function (moduleType, objectId) {
                var deffered = $q.defer();
                if (rtUtils.isNullOrWhiteSpace(moduleType)) {
                    deffered.reject("moduleType can not be null");
                    return deffered.promise;
                }

                if (rtUtils.isNullOrWhiteSpace(objectId)) {
                    deffered.reject("objectId can not be null");
                    return deffered.promise;
                }

                var apiUrl = "api/File/GetFilesByObjectId?moduleType=" + moduleType + "&objectId=" + objectId;
                return rtRestClient.get(apiUrl);
            };

            this.GetFileByFileId = function (moduleType, fileId) {
                if (rtUtils.isNullOrWhiteSpace(moduleType)) {
                    rtUtils.showErrorToast("moduleType can not be null");
                    return;
                }

                if (rtUtils.isNullOrWhiteSpace(fileId)) {
                    rtUtils.showErrorToast("objectId can not be null");
                    return;
                }

                var apiUrl = "api/File/GetFileByFileId?moduleType=" + moduleType + "&fileId=" + fileId;
                return rtRestClient.get(apiUrl);
            };
            this.deleteFile = function (moduleType, fileIds) {
                if (rtUtils.isNullOrWhiteSpace(moduleType)) {
                    rtUtils.showErrorToast("moduleType can not be null");
                    return;
                }
                var apiUrl = "api/File/DeleteFilesByFileIds?moduleType=" + moduleType;
                return rtRestClient.post(apiUrl, fileIds);
            };
        }]);
})();
/********************************************************
Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved. 
 创建人   : joe Song
 创建时间 : 2016-03-10
 说明     : 审批流程的相关帮助函数
*********************************************************/
(function () {
    'use strict';
    angular.module('xrmApp')
        .service('rtFlow', ['$http', 'rtRestClient', function ($http, rtRestClient) {

            /**
             * 获取表单签核按钮
             * @param {string} etn 实体名称
             * @param {string} id 单据名称
             * @returns {HttpPromise}
             */
            this.getFormFlowStatus = function(etn,id){
                var url = "api/flow/GetFormFlowStatus?etn=" + etn + "&id=" + id;
                return rtRestClient.get(url);
            };

            /**
             * 获取实体签核列表
             * @param {string} etn 实体名称
             * @returns {HttpPromise}
             */
            this.getWorkFlow = function(etn){
                var url = "api/flowextension/workflow?entity=" + etn;
                return rtRestClient.get(url);
            };

            /**
             * 获取实体签核步骤列表
             * @param {string} flowid 签核流程标识
             * @param {string} id 记录标识
             * @param {string} etn 实体名称
             * @returns {HttpPromise}
             */
            this.getFlowUser = function(flowid,id,etn){
                var url = "api/flowextension/flowuser?flowid=" + flowid + "&etn=" + etn + "&id=" + id;
                return rtRestClient.get(url);
            };

            /**
             * 提交签核
             * @param {*} 签核用户列表
             * @param {string} id 记录标识
             * @param {string} etn 实体名称
             * @param {string} flowsetpid 签核流程标识
             * @returns {HttpPromise}
             */
            this.submitFlow = function(approveUserList, etn, id, flowsetpid){
                var url = "api/flowextension/flowsubmit?etn=" + etn + "&id=" + id + "&flowid=" + flowsetpid;
                return rtRestClient.post(url,approveUserList);
            };

            /**
             * 撤回签核
             * @param {string} id 记录标识
             * @param {string} etn 实体名称
             * @returns {HttpPromise}
             */
            this.revokeFlow = function(etn,id){
                var url = "api/flowextension/revoke?etn=" + etn + "&id=" + id;
                return rtRestClient.get(url);
            };

            /*
            * 执行签核动作
            * @param {string} flowid 流程标识
            * @param {string} memo 意见
            * @param {string} actionType 执行动作
            * @returns {HttpPromise}
            */
            this.doFlowAction = function(flowId,memo,actionType){
                var url = "api/flow/flowaction?flowId=" + flowId + "&approvalMemo=" + memo +
                    "&actionType=" + actionType;
                return rtRestClient.get(url);
            };

            /*
             * 获取签核列表
             * @param {string} flowid 流程标识
             * @returns {HttpPromise}
             */
            this.getApproveList = function(formId){
                var url = "api/flow/approvelist?formId=" + formId;
                return rtRestClient.get(url);
            };
        }]);
})();
/********************************************************
Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved. 
 创建人   : joe Song
 创建时间 : 2016-03-10
 说明     : 格式化数据的Filter
*********************************************************/
(function () {
    'use strict';
    angular.module('xrmApp')
        .filter('getViewFieldValue', function () {
            /**
             * 根据传入的对象返回视图字段值
             * @param input 包含Type、Value和Name的属性的对象
             * @returns {string} 如果是lookup类型则返回Value.Text，否则直接返回Value
             */
            return function (input) {
                switch (input.Type) {
                    case "lookup":
                        var json = input.Value;
                        if (typeof json === 'string' && json.length > 0) {
                            json = JSON.parse(input.Value);
                        }
                        else if (typeof json === 'object') {
                            return json.Text;
                        }
                        else {
                            return "";
                        }

                        return json.Text;
                    default:
                        return input.Value;
                }
            };
        }).filter('friendlyFormatDateTime', function () {

            function formatDateTime(d, format) {
                var o = {
                    "M+": d.getMonth() + 1, //month
                    "d+": d.getDate(), //day
                    "h+": d.getHours(), //hour
                    "m+": d.getMinutes(), //minute
                    "s+": d.getSeconds(), //second
                    "q+": Math.floor((d.getMonth() + 3) / 3), //quarter
                    "S": d.getMilliseconds() //millisecond
                };

                if (/(y+)/.test(format)) {
                    format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
                }

                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(format)) {
                        format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                    }
                }
                return format;
            }

            return function (input) {
                var d;
                if (typeof input === 'string') {
                    d = moment(input).toDate()
                } else {
                    d = input;
                }

                var today = new Date();
                today.setHours(23, 59, 59, 999);

                var friendlyDateString;

                var internalDays = Math.floor((today.getTime() - d.getTime()) / (1000 * 60 * 60 * 24));
                if (internalDays >= -2 && internalDays <= 2) {
                    switch (internalDays) {
                        case -2:
                            friendlyDateString = "后天" + formatDateTime(d, " hh:mm");
                            break;
                        case -1:
                            friendlyDateString = "明天" + formatDateTime(d, " hh:mm");
                            break;
                        case 0:
                            friendlyDateString = "今天" + formatDateTime(d, " hh:mm");
                            break;
                        case 1:
                            friendlyDateString = "昨天" + formatDateTime(d, " hh:mm");
                            break;
                        case 2:
                            friendlyDateString = "前天" + formatDateTime(d, " hh:mm");
                            break;
                        default:
                            friendlyDateString = formatDateTime(d, "yyyy-MM-dd hh:mm");
                            break;
                    }

                    return friendlyDateString;
                }

                if (today.getMonth() == d.getMonth() && today.getFullYear() == d.getFullYear()) {
                    return "本月" + formatDateTime(d, "dd") + '号';
                }

                if (today.getFullYear() == d.getFullYear()) {
                    return formatDateTime(d, "MM") + "月" + formatDateTime(d, "dd") + '号';
                }

                return "";

            };
        })
        .filter('friendlyFormatDate', function () {

            function formatDateTime(d, format) {
                var o = {
                    "M+": d.getMonth() + 1, //month
                    "d+": d.getDate(), //day
                    "h+": d.getHours(), //hour
                    "m+": d.getMinutes(), //minute
                    "s+": d.getSeconds(), //second
                    "q+": Math.floor((d.getMonth() + 3) / 3), //quarter
                    "S": d.getMilliseconds() //millisecond
                };

                if (/(y+)/.test(format)) {
                    format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
                }

                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(format)) {
                        format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                    }
                }
                return format;
            }

            return function (input) {
                if (input === undefined || input === null)
                    return;

                var d;
                if (typeof input === 'string') {
                    d = moment(input).toDate()
                } else {
                    d = input;
                }

                var today = new Date();
                today.setHours(23, 59, 59, 999);

                var friendlyDateString;

                var internalDays = Math.floor((today.getTime() - d.getTime()) / (1000 * 60 * 60 * 24));
                switch (internalDays) {
                    case -2:
                        friendlyDateString = "后天";
                        break;
                    case -1:
                        friendlyDateString = "明天";
                        break;
                    case 0:
                        friendlyDateString = "今天" + formatDateTime(d, " hh:mm");
                        break;
                    case 1:
                        friendlyDateString = "昨天";
                        break;
                    case 2:
                        friendlyDateString = "前天";
                        break;
                    default:
                        if (today.getFullYear() == d.getFullYear()) {
                            friendlyDateString = formatDateTime(d, "MM-dd");
                        } else {
                            friendlyDateString = formatDateTime(d, "yyyy-MM-dd");
                        }
                        break;
                }

                return friendlyDateString;
            };
        })
        .filter('toFixNumber', function () {
            return function (input, decimalPlaces) {
                if (input == null) {
                    return input;
                }
                if (isNaN(input))
                    return input;
                else {
                    return input.toFixed(decimalPlaces);
                }
            };
        });
})();

/********************************************************
Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved. 
 创建人   : joe Song
 创建时间 : 2016-03-10
 说明     : 用户操作权限相关的帮助类
*********************************************************/
(function () {
    'use strict';
    angular.module('xrmApp')
        .service('rtPrivilege', ['$http', 'rtRestClient', function ($http, rtRestClient) {

            /**
             * 获取权限
             * @param {string} etn 实体名称
             * @param {string} id 单据名称
             * @param  type     权限类型
             * @returns {HttpPromise}
             */
            this.havePrivilege= function (etn, id, type) {
                var url = "api/privilege/GetPrivilegeByType?etn=" + etn + "&type=" + type;
                if(id !== null ){
                    url += "&id=" + id;
                }
                return rtRestClient.get(url);
            };
        }]);
})();
/********************************************************
Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved. 
 创建人   : joe Song
 创建时间 : 2016-03-10
 说明     : 请求WebApi的帮助函数
*********************************************************/
(function () {
    'use strict';
    angular.module('xrmApp')
        .service('rtRestClient', ['$http', 'rtUtils', function ($http, rtUtils) {
            this.getBaseApiUrl = function(){
                if (window.XrmDeviceData && window.XrmDeviceData.getXrmBaseUrl) {
                    return window.XrmDeviceData.getXrmBaseUrl();
                }
                else if (!rtUtils.isNullOrEmptyString(localStorage.XrmBaseUrl)) {
                    return localStorage.XrmBaseUrl;
                }

                return null;
            };

            this.getXrmAuthToken = function () {
                if (window.XrmDeviceData && window.XrmDeviceData.getXrmAuthToken) {
                    return window.XrmDeviceData.getXrmAuthToken();
                }
                else if (!rtUtils.isNullOrEmptyString(localStorage.XrmAuthToken)) {
                    return localStorage.XrmAuthToken;
                }

                return null;
            };

            /**
             * 通过post的方法调用WebAPI
             * @param {string} apiUrl WebAPI的URL地址，如 "api/sys/modules?showIcon=&lastUpdateTime=";
             * @param {*} data 要post到服务器端的数据
             * @param {string} ignoreError 忽略错误处理
             * @returns {HttpPromise}
             */
            this.post = function (apiUrl, data, ignoreError) {
                var url = this.getBaseApiUrl() + apiUrl;

                var token = this.getXrmAuthToken();
                if (!rtUtils.isNullOrEmptyString(token)) {
                    $http.defaults.headers.common.Authorization = 'Basic ' + this.getXrmAuthToken();
                }

                var resp = $http.post(url, data);
                return ignoreError === true ? resp : resp.error(function (msg) {
                    rtUtils.showErrorToast(msg);
                });
            };

            /**
             * 通过Get方法调用WebAPI
             * @param {string} apiUrl WebAPI的URL地址
             * @param {string} ignoreError 忽略错误处理
             * @returns {HttpPromise}
             */
            this.get = function (apiUrl, ignoreError) {
                var url = this.getBaseApiUrl() + apiUrl;

                var token = this.getXrmAuthToken();
                if (!rtUtils.isNullOrEmptyString(token)) {
                    $http.defaults.headers.common.Authorization = 'Basic ' + this.getXrmAuthToken();
                }

                var resp = $http.get(url);
                return ignoreError === true ? resp : resp.error(function (msg) {
                    rtUtils.showErrorToast(msg);
                });
            };

            this.delete = function (apiUrl) {
                var url = this.getBaseApiUrl() + apiUrl;

                var token = this.getXrmAuthToken();
                if (!rtUtils.isNullOrEmptyString(token)) {
                    $http.defaults.headers.common.Authorization = 'Basic ' + this.getXrmAuthToken();
                }

                return $http.delete(url);
            };

            /**
             * 通过post的方法调用WebAPI
             * @param {string} apiUrl WebAPI的URL地址，如 "api/sys/modules?showIcon=&lastUpdateTime=";
             * @param {*} data 要post到服务器端的数据
             * @returns {HttpPromise}
             */
            this.put = function (apiUrl, data) {
                var url = this.getBaseApiUrl() + apiUrl;

                var token = this.getXrmAuthToken();
                if (!rtUtils.isNullOrEmptyString(token)) {
                    $http.defaults.headers.common.Authorization = 'Basic ' + this.getXrmAuthToken();
                }

                return $http.put(url, data);
            };

            /*
             * 删除实体记录
             * @param {string} etn 实体名称
             * @param {string} id 实体记录标识
             * @returns {HttpPromise}
             * */
            this.deleteFormData = function (etn, id) {
                var apiUrl = "api/form/deletedata?etn=" + etn + "&id=" + id;
                return this.post(apiUrl);
            };

            /*
             * 通过WebAPI获取表单记录
             * @param {string} etn 实体名称
             * @param {string} id 实体记录标识
             * @returns {HttpPromise}
             * */
            this.getFormData = function (etn, id) {
                var entity = "{" +
                    "\"Id\":\"" + id + "\"," +
                    "\"LogicalName\":\"" + etn + "\"," +
                    "\"LinkEntityList\":[{\"LinkFieldName\":\"" + "\",\"LinkedEntity\":{\"Id\":\"" + "\"}}]" +
                    "}";

                var apiUrl = "api/formeditex/get?entity=" + entity;
                return this.get(apiUrl);
            };

            /*
             * 通过WebAPI提交表单记录
             * */
            this.postFormData = function (etn, id, fields, linkField, linkFieldId, linkEntity) {
                var entity = "{" +
                    "\"Id\":\"" + id + "\"," +
                    "\"LogicalName\":\"" + etn + "\"," +
                    "\"LinkEntityList\":[{\"LinkFieldName\":\"" + "\",\"LinkedEntity\":{\"Id\":\"" + "\"}}]" +
                    "}";

                for (var i = 0; i < fields.length; i++) {
                    var field = fields[i];

                    if (field.IsReq === true && rtUtils.isNull(field.FieldValue) === true) {
                        var message = field.FieldName + "不能为空。";
                        rtUtils.showErrorToast(message);
                        return;
                    }

                    if (field.FieldType === "lookup" && rtUtils.isNull(field.FieldValue) === false) {
                        field.FieldValue = JSON.stringify(field.FieldValue[0]);
                    }
                }

                var data = {
                    Entity: JSON.parse(entity),
                    FieldList: fields
                };

                return this.post("api/formedit/post", data);
            };

            /**
             * 通过WebAPI获取只读表单
             * @param {string} etn 实体名称
             * @param {string} id 实体记录标识
             * @returns {HttpPromise}
             */
            this.getReadOnlyForm = function (etn, id) {
                var apiUrl = "api/form/data?etn=" + etn + "&id=" + id;
                return this.get(apiUrl);
            };

            this.getViewData = function (etn, fieldName, id, viewId) {
                var entity = "{" +
                    "\"LogicalName\":\"" + etn + "\"," +
                    "\"LinkEntityList\":[{\"LinkFieldName\":\"" + fieldName + "\",\"LinkedEntity\":{\"Id\":\"" + id + "\"}}]" +
                    "}";

                var view = "{" +
                    "\"ViewId\":\"" + _vm.selectedViewId + "\"" +
                    "}";

                var apiUrl = "api/ViewQuery/quicksearchdata?entity=" + entity +
                    "&view=" + view +
                    "&queryValue=" + _vm.queryValue +
                    "&pageIndex=" + _vm.pageIndex +
                    "&pageSize=" + _vm.pageSize;
                return rt.get(apiUrl);
            };

            /**
             * 通过WebAPI获取picklist的可选的options （包含额外的 “请选择” 的选项）
             * @param {string} etn 实体名字
             * @param {string} fieldName 字段名
             * @returns {HttpPromise}
             */
            this.getPicklistOptions = function (etn, fieldName) {
                var url = "api/Picklist/Get?etn=" + etn + "&fieldName=" + fieldName;
                return this.get(url);
            };

            /**
             * 通过WebAPI获取picklist的可选的options （不包含 “请选择”）
             * @param {string} etn 实体名字
             * @param {string} fieldName 字段名
             * @returns {HttpPromise}
             */
            this.getPicklistOptions2 = function (etn, fieldName) {
                var url = "api/Picklist/Get2?etn=" + etn + "&fieldName=" + fieldName;
                return this.get(url);
            };

            /**
             * 根据配置文件中的SQL语句查询相关数据，已JSON的形式返回
             * @param {string} configname 配置节点的名字
             * @param {string} paramslist 配置文件中的SQL语句参数
             * @returns {Object}
             */
            this.getData = function (configname, paramslist) {
                var url = "common/GetData.aspx?configname=" + configname + "&paramslist=" + paramslist;
                return this.get(url);
            };

            /**
             * 获取指定实体的字段的值
             * @param {string} id 实体数据库记录的ID
             * @param {string} typename 实体的名称
             * @param {string} returnField 多个字段用逗号隔开；如果要返回所有的值，则为空或者是 *
             * @returns {Object} 返回returnField中指定的字段的值
             */
            this.getFieldValue = function (id, typename, returnField) {
                if (rtUtils.isNull(returnField)) {
                    returnField = '*';
                }

                var url = "common/GetFieldValue.aspx?id=" + id + "&typename=" + typename + "&fieldlist=" + returnField;
                return this.get(url);
            };

            /**
             * 根据实体的某个字段查询实体的数据行
             * @param {string} id 字段的值
             * @param {string} typename 实体的名字
             * @param {string} refname 字段的名字
             * @param {string} returnField 返回的字段的列表，逗号分隔
             * @returns {Object}
             */
            this.getRefFieldValue = function (id, typename, refname, returnField) {
                if (rtUtils.isNull(returnField)) {
                    returnField = '*';
                }

                var url = "common/GetRefFieldValue.aspx?id=" + id + "&typename=" + typename + "&refname=" + refname + "&fieldlist=" + returnField;
                return this.get(url);
            };
        }]);
})();

/********************************************************
 Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved.
 创建人   : joe Song
 创建时间 : 2016-03-10
 说明     : 常用帮助函数，如是否是手机号等
 *********************************************************/

(function() {
    'use strict';
    angular.module('xrmApp')
        .service('rtUtils', ['$rootScope', '$http', '$ionicLoading', '$filter', '$ionicModal', '$ionicPopup', '$ionicViewService', '$timeout', '$ionicActionSheet', function($rootScope, $http, $ionicLoading, $filter, $ionicModal, $ionicPopup, $ionicViewService, $timeout, $ionicActionSheet) {
            /**
             * 扩展日期对象，增加addDays的方法
             * @param days
             * @returns {Date}
             */
            Date.prototype.addDays = function(days) {
                var dat = new Date(this.valueOf());
                dat.setDate(dat.getDate() + days);
                return dat;
            };

            /**
             * 判断两个日期去掉事件后，是否相等
             */
            Date.prototype.isSameDate = function(d) {
                if (d === null || d === undefined) {
                    return false;
                }
                var thisDate = new Date(this.valueOf());
                return (thisDate.getFullYear() + '-' + thisDate.getMonth() + '-' + thisDate.getDate()) == (d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate());
            };
            /**
             * 判断两个时间之间的差异，如天数等
             * @returns {integer}
             */
            this.dateDiff = function(datepart, date1, date2) {
                var seconds = date2.getTime() - date1.getTime();

                if (datepart === "dd") {
                    return parseInt(seconds / (1000 * 60 * 60 * 24));
                }
            };

            /**
             * 判断字符是否有效的手机号码
             * @returns {boolean}
             */
            this.isCellphone = function(str) {
                var reg = /^0*(13|14|15|16|17|18)\d{9}$/;
                return reg.test(str);
            };


            /**
             * 检查是否是手机号码或者电话号码
             * */
            this.isPhoneNumberString = function(str) {
                var p1 = /^(\d{3,4})?(-)?\d{7,8}(-\d{3,4})?$/;
                var p2 = /^0*(13|14|15|16|17|18)\d{9}$/;
                if (p1.test(str) || p2.test(str))
                    return true;
                else
                    return false;
            };

            /**
             * 检查是否是邮件地址
             * */
            this.isEMailAddrString = function(str) {
                var p1 = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
                if (p1.test(str))
                    return true;
                else
                    return false;
            };

            /**
             * 判断字符是否有效的身份证括号
             * @returns {boolean}
             */
            this.isIDCard = function(str) {
                var reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/;
                return reg.test(str);
            };

            /**
             * 四舍五入取小数位精度
             * @param x 原变量
             * @param num 需要精度的位数
             * @returns {float or int} 返回num传入小数精度的已处理变量
             */
            this.xrmRound = function (input, decimalPlaces) {
            	if (input == null) {
            		return input;
            	}
            	if (isNaN(input))
            		return input;
            	else {
            		return input.toFixed(decimalPlaces);
            	}
            };

            /**
             * 判断一个变量是否是undefined或者null
             * @param o 需要进行判断的变量
             * @returns {boolean} 如果是undified或者null，则返回true，否则返回 false
             */
            this.isNull = function(o) {
                return o === undefined || o === null;
            };

            /**
             * 判断变量f是否是一个函数
             * @param f 变量f
             * @returns {boolean} 如果是函数则返回true，否则返回false
             */
            this.isFunction = function(f) {
                return f !== undefined && f !== null && typeof f === 'function';
            };

            /**
             * 判断一个字符串是否是undified、null、“”
             * @param s 字符串变量
             * @returns {boolean} 如果是，则返回true，否则返回false
             */
            this.isNullOrEmptyString = function(s) {
                return this.isNull(s) || this.trim(s) === "";
            };

            this.isNullOrWhiteSpace = this.isNullOrEmptyString;
            /**
             * 判断一个日期对象是否是无效的日期
             */
            this.isNullOrInvalidDate = function(d) {
                if (this.isNull(d)) {
                    return true;
                }

                if (Object.prototype.toString.call(d) !== "[object Date]") {
                    return true;
                }

                if (isNaN(d.getTime())) {
                    return true;
                }

                return false;
            };

            /**
             * 不区分大小、{}，比较两个guid
             * @param guid1 参与比较的第一个Guid
             * @param guid2 参与比较的第二个Guid
             * @returns {boolean}
             */
            this.isSameGuid = function(guid1, guid2) {
                var isEqual = false;
                if (this.isNull(guid1) || this.isNull(guid2)) {
                    isEqual = false;
                } else {
                    isEqual = guid1.replace(/[{}]/g, "").toLowerCase() === guid2.replace(/[{}]/g, "").toLowerCase();
                }

                return isEqual;
            };

            /**
             * 移除字符串开通和结尾的空格等特殊字符
             * @param s 待trim的字符串
             * @param charsToTrim 要去掉的特殊字符串，如果为空，则代码移除空格
             * @returns {string} 返回移除后的字符串
             */
            this.trim = function(s, charsToTrim) {
                if (this.isNull(s) || typeof s !== "string" || s.length <= 0) {
                    return "";
                }

                var result = s;
                var ctrim = (this.isNull(s) || typeof charsToTrim !== "string" || charsToTrim.length <= 0) ? " " : charsToTrim;

                var index = 0, count = s.length;
                while (count > 0) { //trim the head position
                    if (ctrim.indexOf(result[0]) >= 0) {
                        result = result.substring(1);
                        count--;
                    } else {
                        break;
                    }
                }
                while (count > 0) { //trim the tail position
                    if (ctrim.indexOf(result[count - 1]) >= 0) {
                        result = result.substring(0, count - 1);
                        count--;
                    } else {
                        break;
                    }
                }
                return result;
            };

            /**
             * 判断是否是Date类型
             * @param d
             * @returns {boolean}
             */
            this.isDate = function(d) {
                if (this.isNull(d)) {
                    return false;
                }

                return d instanceof Date && !isNaN(d.valueOf());
            };

            /**
             * 弹出操作执行成功的Toast
             * @param {string} msg 提示信息
             */
            this.showSuccessToast = function(msg) {
                if (this.isNullOrEmptyString(msg)) {
                    return;
                }
                $ionicLoading.show({
                    template: '<div><i style="font-size:2em;" class="icon ion-checkmark-circled"></i></div><div>' + msg + '</div>',
                    duration: 2000
                });
                //添加点击弹出层即隐藏提示
                document.getElementsByClassName("loading-container")[0].onclick = this.hideLoadingToast;
            };

            /**
             * 弹出执行错误的Toast
             * @param {string} msg 错误消息
             */
            this.showErrorToast = function(msg) {
                if (this.isNullOrEmptyString(msg)) {
                    return;
                }
                $ionicLoading.show({
                    template: '<div><i style="font-size:2em;" class="icon ion-close-circled"></i></div><div>' + msg + '</div>',
                    duration: 2000
                });
                //添加点击弹出层即隐藏提示
                document.getElementsByClassName("loading-container")[0].onclick = this.hideLoadingToast;
            };

            /**
             * 弹出正在执行的Toast
             * @param {string} msg 提示信息
             */
            this.showLoadingToast = function(msg) {
                if (this.isNullOrEmptyString(msg)) {
                    return;
                }
                $ionicLoading.show({
                    template: '<div><i style="font-size:2em;" class="icon ion-loading-c"></i></div><div>' + msg + '</div>',
                    duration: 0,
                    noBackdrop: true
                });
            };

            /**
             * 隐藏正在执行的消息提示框
             */
            this.hideLoadingToast = function() {
                $ionicLoading.hide();
            };


            /**
             * 格式化日期类型
             * @param {Date} d  日期
             * @param {string} format 格式化字符串，如果不传值，在默认为 ‘yyyy-MM-dd’
             * @returns {string} 返回格式化后的日期字符串
             */
            this.formatDateTime = function(d, format) {
                if (!this.isDate(d)) {
                    return "";
                }
                if (this.isNullOrEmptyString(format)) {
                    format = 'yyyy-MM-dd';
                }
                return $filter('date')(d, format);
            };

            /**
             * 创建弹出的对话框页面，如lookup的选择也
             * @param {string} url 对话框模板html文件的地址
             * @param {$scope} $s angularjs的$scope对象
             * @param {function} cb 对话框的执行完成的回掉函数，如点击OK按钮或者选择一行数据
             * @returns {promise} 返回promise对象，需要在then方法中调用show方法显示对话框，如then(function(d){ d.show();});
             */
            this.createDialog = function(url, $s, cb) {
                return $ionicModal.fromTemplateUrl(url, function($ionicModal) {
                    $s.dialog = $ionicModal;
                    $s.closeDialog = function() {
                        $s.dialog.hide();
                    };
                    if (cb !== undefined) {
                        $s.onDataSelected = cb;
                    }
                }, {
                        scope: $s, animation: 'slide-in-up'
                    });
            };

            /**
             * 弹出确认选择的对话框，如：是否要删除，包含确认和取消两个按钮
             * @param {string} msgTitle 消息提示的标题
             * @param {string} msgBody 消息提示的正文
             * @param {Function} cb 点击确认按钮之后的回调函数
             */
            this.showPopupDialog = function(msgTitle, msgBody, cb) {
                var popup = $ionicPopup.show({
                    template: msgBody,
                    title: msgTitle,
                    buttons: [
                        {
                            text: '取消',
                            onTap: function() {
                                $rootScope.$broadcast('xrm.popup.hidden');
                                popup.close();
                            }
                        },
                        {
                            text: '确认',
                            type: 'button-positive',
                            onTap: function() {
                                $rootScope.$broadcast('xrm.popup.hidden');
                                popup.close();
                                if (cb !== undefined && cb !== null) {
                                    cb();
                                }
                            }
                        }
                    ]
                });
                $rootScope.$broadcast('xrm.popup.shown', popup);
            };

            /**
             * 弹出提示对话框
             * @param {Object} config 消息提示的标题
             * @param {String} title 消息提示的标题
             * @param {String} content 消息提示的正文
             * @param {Function} callback 点击确认按钮之后的回调函数
             */
            this.showAlertDialog = function(config) {
                if (config === null) {
                    config = {};
                }

                var popup = $ionicPopup.show({
                    template: config.content !== undefined && config.content !== null ? config.content : "",
                    title: config.title !== undefined && config.title !== null ? config.title : "",
                    buttons: [
                        {
                            text: '确定',
                            type: 'button-positive',
                            onTap: function() {
                                $rootScope.$broadcast('xrm.popup.hidden');
                                popup.close();
                                if (config.callback !== undefined && config.callback !== null) {
                                    config.callback();
                                }
                            }
                        }
                    ]
                });

                $rootScope.$broadcast('xrm.popup.shown', popup);
            };

            /**
             * 弹出确认选择的对话框，如：是否要删除，包含确认和取消两个按钮
             * @param {string} msgTitle 消息提示的标题
             * @param {string} msgBody 消息提示的正文
             */
            this.showConfirmDialog = function(msgTitle, msgBody) {
                return $ionicPopup.confirm({
                    title: msgTitle,
                    subTitle: msgBody,
                    cancelText: '取消',
                    okText: '确认'
                });
            };

            /**
             * 判断当前页面是新打开的页面还是从子页面导航返回的页面
             * @returns {boolean}
             */
            this.isNavigationBack = function() {
                return $ionicViewService.getNavDirection() === 'back';
            };

            this.getBackView = function() {
                return $ionicViewService.getBackView();
            };

            /**
             * 生成随机的Guid
             * @returns {string} Guid
             */
            this.newGuid = function() {
                function s4() {
                    return Math.floor((1 + Math.random()) * 0x10000)
                        .toString(16)
                        .substring(1);
                }

                return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
                    s4() + '-' + s4() + s4() + s4();
            };

            this.getPaginationSize = function() {
                return 15;
            };

            this.convertGPS2BaiduLocation = function(l) {
                var apiUrl = "https://api.map.baidu.com/geoconv/v1/?coords=" + l.longitude +
                    "," + l.latitude + "&from=1&to=5&ak=ROninBdEIu93CBGDHc3fSPHE" + "&callback=JSON_CALLBACK";

                return $http.jsonp(apiUrl);
            };

            this.getGeolocation = function(success, errorCb) {
                function checkHasXrmDeviceGeoIOS() {
                    if (window.XrmDeviceGeoIOS && window.XrmDeviceGeoIOS.getGeoLocationData && window.XrmDeviceGeoIOS.getGeoLocationData() !== "") {

                        var position = window.XrmDeviceGeoIOS.getGeoLocationData();
                        if (position === null) {
                            errorCb && errorCb();
                            return;
                        }

                        var l = position;

                        //var result = getSurroundingPois(l.longitude, l.latitude);
                        //l.address = result.address;
                        //l.surroundingPois = result.surroundingPois;

                        // 创建地理编码实例
                        var myGeo = new BMap.Geocoder();
                        // 根据坐标得到地址描述
                        myGeo.getLocation(new BMap.Point(l.longitude, l.latitude), function(result) {
                            if (result) {
                                l.address = result.address;
                                //l.surroundingPois = result.surroundingPois;
                            }
                            success(l);
                        }, { poiRadius: 500, numPois: 10 });

                        window.XrmDeviceGeoIOS.clearGeoLocationData();
                        return;
                    }
                    $timeout(checkHasXrmDeviceGeoIOS, 1000);
                }

                if (window.localStorage.getItem('XrmDeviceGeoIOS')) { //IOS使用设备本身的原生定位
                    location.href = "app:get-location";
                    checkHasXrmDeviceGeoIOS();
                    return;
                }

                if (window.XrmDeviceGeo) { //使用设备本身的原生定位
                    var position;
                    try {
                        position = window.XrmDeviceGeo.getGeoLoaction();
                    } catch (e) {
                        that.showErrorToast(e);
                    }

                    if (this.isNull(position)) {
                        errorCb && errorCb();
                        return;
                    }
                    var l = JSON.parse(position);
                    success(l);
                    return;
                }


                //使用H5的定位
                var that = this;
                navigator.geolocation.getCurrentPosition(function(position) {
                    if (position === null || position.coords === null) {
                        that.showErrorToast("定位失败，正在重新定位");
                        return;
                    }

                    //调用百度的API将GPS坐标转换成百度的火星坐标
                    var l = { latitude: position.coords.latitude, longitude: position.coords.longitude };
                    that.convertGPS2BaiduLocation(l)
                        .success(function(d) {
                            if (d === undefined || d === null || d.status !== 0 || d.result === null || d.result.length === 0) {
                                that.showErrorToast("调用百度火星坐标转换的API错误,错误码：" + d.status);
                                return;
                            }

                            l.longitude = d.result[0].x;
                            l.latitude = d.result[0].y;

                            //var result = getSurroundingPois(l.longitude, l.latitude);
                            //l.address = result.address;
                            //l.surroundingPois = result.surroundingPois;

                            // 创建地理编码实例
                            var myGeo = new BMap.Geocoder();
                            // 根据坐标得到地址描述
                            myGeo.getLocation(new BMap.Point(l.longitude, l.latitude), function(result) {
                                if (result) {
                                    l.address = result.address;
                                    //l.surroundingPois = result.surroundingPois;
                                }
                                success(l);
                            }, { poiRadius: 500, numPois: 10 });

                        });
                }, function(error) {
                    switch (error.code) {
                        case 0:
                            that.showErrorToast("获取位置是发生一个错误,错误信息：" + error.message);
                            break;
                        case 1:
                            that.showErrorToast("无法获取当前位置，请打开定位服务后重新尝试!");
                            break;
                        case 2:
                            that.showErrorToast("无法确定设备的位置，请返回后重新尝试! ");
                            break;
                        case 3:
                            that.showErrorToast("获取位置超时，请返回后重新尝试!");
                            break;
                        default:
                            that.showErrorToast("定位失败，发生未知错误");
                            break;
                    }
                    if (errorCb) {
                        errorCb();
                    }
                }, { timeout: 10000 });

                function getSurroundingPois(longitude, latitude) {
                    var as = { address: "", surroundingPois: [] };
                    // 创建地理编码实例
                    var myGeo = new BMap.Geocoder();
                    // 根据坐标得到地址描述
                    myGeo.getLocation(new BMap.Point(longitude, latitude), function(result) {
                        if (result) {
                            as.address = result.address;
                            as.surroundingPois = result.surroundingPois;
                        }

                    }, { poiRadius: 500, numPois: 10 });

                    return as;
                }
            };

            this.takePhoto = function(px, kb, callback) {
                location.href = "app:take-photo?px=" + px + "&kb=" + kb;

                function checkHasXrmDeviceImageData() {
                    if (window.XrmImageData && window.XrmImageData.getXrmImageData && window.XrmImageData.getXrmImageData() !== "") {

                        var image = window.XrmImageData.getXrmImageData();

                        if (callback !== null) {
                            callback(image);
                        }
                        window.XrmImageData.clearImageData();

                        return;
                    }
                    $timeout(checkHasXrmDeviceImageData, 1500);
                }

                checkHasXrmDeviceImageData();
            };

            this.choosePhoto = function(px, kb, callback) {
                location.href = "app:choose-photo?px=" + px + "&kb=" + kb;

                function checkHasXrmDeviceImageData() {
                    if (window.XrmImageData && window.XrmImageData.getXrmImageData && window.XrmImageData.getXrmImageData() !== "") {

                        var image = window.XrmImageData.getXrmImageData();

                        if (callback !== null) {
                            callback(image);
                        }
                        window.XrmImageData.clearImageData();

                        return;
                    }
                    $timeout(checkHasXrmDeviceImageData, 1500);
                }

                checkHasXrmDeviceImageData();
            };

            /**
             * 选择图片/照片
             * @param config
             *  {
             *      count：1，
             *      px:800,     //图片的像素
             *      kb:100,,    //
             *      sourceType：['album', 'camera']，
             *      success:function(image){
             *          //
             *      }
             *  }
             */
            this.chooseImage = function(config) {
                if (config === null || config === undefined) {
                    return;
                }

                //处理图片的大小
                if ((config.px === null || config.px === undefined) &&
                    (config.kb === null || config.kb === undefined)) {
                    config.px = 800;
                    config.kb = 100;
                }

                var ALBUM = "album";
                var CAMERA = "camera";

                var px = config.px;
                var kb = config.kb;
                //处理图片的来源
                var sourceTypes = [];
                if (config.sourceType === null) {
                    sourceTypes = [ALBUM, CAMERA];
                } else if (!(config.sourceType instanceof Array)) {
                    throw new Error("sourceType必须为数组!");
                } else {
                    for (var i = 0; i <= config.sourceType.length; i++) {
                        if (config.sourceType[i] === ALBUM || config.sourceType[i] === CAMERA) {
                            sourceTypes.push(config.sourceType[i]);
                        }
                    }
                }

                var that = this;

                //获取图片
                if (sourceTypes.length === 1) {
                    if (sourceTypes[0] === ALBUM) {
                        that.choosePhoto(px, kb, config.success);
                    } else if (sourceTypes[0] === CAMERA) {
                        that.takePhoto(px, kb, config.success);
                    }
                } else {
                    var selectedButtons = [
                        { text: "拍照" },
                        { text: "从手机相册选择" }
                    ];
                    $ionicActionSheet.show({
                        buttons: selectedButtons,
                        titleText: '选择视图',
                        cancelText: '取消',
                        cancel: function() {
                        },
                        buttonClicked: function(index) {
                            if (index === 0) {
                                that.takePhoto(px, kb, config.success);
                            } else if (index === 1) {
                                that.choosePhoto(px, kb, config.success);
                            }
                            return true;
                        }
                    });
                }
            };

            /**
             * 扫码
             * @param config
             * {
             *     success:function(){}
             * }
             */
            this.scanQRCode = function(config) {
                location.href = "app:scan";

                function getScanResult() {
                    var result;
                    if (window.XrmScanData && window.XrmScanData.getResult() !== "") {
                        result = window.XrmScanData.getResult();
                    }

                    if (result === null || result.length === 0) {
                        $timeout(getScanResult, 1500);
                    }
                    else {
                        $timeout.cancel();
                        if (config && config.success) {
                            config.success(result);
                        }
                    }
                }

                getScanResult();
            };

            this.getUserId = function() {
                var userId;
                if (window.XrmDeviceData && window.XrmDeviceData.getUserId) {
                    userId = window.XrmDeviceData.getUserId();
                }
                else if (!this.isNullOrEmptyString(localStorage.UserId)) {
                    userId = localStorage.UserId;
                }
                else {
                    this.showErrorToast("没有获取到当前用户的id! ");
                }
                return userId;
            };

            this.getUserName = function() {
                var userName;
                if (window.XrmDeviceData && window.XrmDeviceData.getUserName) {
                    userName = window.XrmDeviceData.getUserName();
                }
                else if (!this.isNullOrEmptyString(localStorage.UserName)) {
                    userName = localStorage.UserName;
                }
                else {
                    this.showErrorToast("没有获取到当前用户的账号! ");
                }
                return userName;
            };

            /**
             * 获取页面文档显示区域的宽度
             * @returns {boolean}
             */
            this.getDocumentWidth = function() {
                return document.documentElement.clientWidth || document.body.clientWidth;
            };

            /**
             * 获取页面文档显示区域的高度
             * @returns {boolean}
             */
            this.getDocumentHeight = function() {
                return document.documentElement.clientHeight || document.body.clientHeight;
            };

            /**
             * 格式化echarts的坐标轴上文字过长的问题
             */
            this.formatAxisLabel = function(params) {
                var newParamsName = "";
                var paramsNameNumber = params.length;
                var provideNumber = 6;
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                if (paramsNameNumber > provideNumber) {
                    for (var p = 0; p < rowNumber; p++) {
                        var tempStr = "";
                        var start = p * provideNumber;
                        var end = start + provideNumber;
                        if (p == rowNumber - 1) {
                            tempStr = params.substring(start, paramsNameNumber);
                        } else {
                            tempStr = params.substring(start, end) + "\n";
                        }
                        newParamsName += tempStr;
                    }
                } else {
                    newParamsName = params;
                }
                return newParamsName
            };
        }]);
})();

/********************************************************
Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved. 
 创建人   : joe Song
 创建时间 : 2016-03-10
 说明     : 自定义的公用服务定义
*********************************************************/

(function () {
    'use strict';

    angular.module('xrmApp').service('entityService', ['$rootScope', '$ionicPopover', '$compile', '$q', '$state', '$stateParams', '$ionicActionSheet', '$ionicHistory', 'rt', entityService]);
    function entityService($rootScope, $ionicPopover, $compile, $q, $state, $stateParams, $ionicActionSheet, $ionicHistory, rt) {
        this.$q = $q;
        this.$compile = $compile;
        this.$state = $state;
        this.$stateParams = $stateParams;
        this.rt = rt;
        this.$ionicActionSheet = $ionicActionSheet;
        this.$ionicHistory = $ionicHistory;
        this.$ionicPopover = $ionicPopover;
        this.$rootScope = $rootScope;

        // 以下两个属性必须被Service重写，否则会出现继承的Service相互影响的问题。        
        this.controllerName = '';
        this.picklists = [];
        this.mutipleSelects = [];

        // getDefaultAutoHeight = Windows的高度 - 默认视图页面的表格高度
        this.getDefaultAutoHeight = function () {
            return 240;
        };

        this.getDefaultFormAutoHeight = function () {
            return 108;
        };

        this.getViewList = function (tag) {
            var url = 'api/' + this.controllerName + '/GetViewList?tag=' + (rt.isNull(tag) ? "" : tag);
            return rt.get(url);
        };

        this.getLookupViewList = function (tag) {
            var url = 'api/' + this.controllerName + '/GetLookupViewList?tag=' + (rt.isNull(tag) ? "" : tag);
            return rt.get(url);
        }

        this.getAssociatedGridViewList = function (tag) {
            var url = 'api/' + this.controllerName + '/GetAssociatedGridViewList?tag=' + (rt.isNull(tag) ? "" : tag);
            return rt.get(url);
        }

        this.getSubGridViewList = function (tag) {
            var url = 'api/' + this.controllerName + '/GetSubGridViewList?tag=' + (rt.isNull(tag) ? "" : tag);
            return rt.get(url);
        }

        this.getViewData = function (viewId, quickSearch, searchList, orderBy, pageSize, pageIndex) {
            var url = 'api/' + this.controllerName + '/GetViewData' +
                '?viewId=' + viewId +
                '&quickSearch=' + encodeURIComponent(quickSearch) +
                "&searchList=" + (rt.isNull(searchList) ? "" : encodeURIComponent(JSON.stringify(searchList))) +
                '&orderBy=' + orderBy +
                '&pageSize=' + pageSize +
                '&pageIndex=' + pageIndex;

            return rt.get(url);
        }

        this.getPickList = function () {
            var url = 'api/' + this.controllerName + '/GetPickListData?fieldCodes=' + encodeURIComponent(this.picklists)
            return rt.get(url);
        };

        this.getPrivilege = function (id) {
            if (rt.isNull(id)) {
                id = '';
            }

            var url = 'api/' + this.controllerName + '/GetPrivilege?id=' + id;
            return rt.get(url);
        };

        this.getData = function (id) {
            // 如果请求的Id为空，则直接返回承诺，不需要再请求服务器
            if (rt.isNull(id) || id.length === 0) {
                var deferred = $q.defer();
                deferred.resolve({ data: null });
                return deferred.promise;
            }

            var url = 'api/' + this.controllerName + '/GetData?id=' + id;
            return rt.get(url);
        };

        this.getAttachmentList = function (id) {
            // 如果请求的Id为空，则直接返回承诺，不需要再请求服务器
            if (rt.isNull(id) || id.length === 0) {
                var deferred = $q.defer();
                deferred.resolve({ data: null });
                return deferred.promise;
            }

            var url = 'api/' + this.controllerName + '/GetAttachmentList?id=' + id;
            return rt.get(url);
        };

        this.saveAttachmentList = function (attachments) {
            if (rt.isNull(attachments) || attachments.length === 0) {
                var deferred = $q.defer();
                deferred.resolve({ data: null });
                return deferred.promise;
            }

            var url = 'api/' + this.controllerName + '/SaveAttachmentList';
            return rt.post(url, attachments);
        };

        this.delAttachment = function (id) {
            if (rt.isNull(id) || id.length === 0) {
                var deferred = $q.defer();
                deferred.resolve({ data: null });
                return deferred.promise;
            }

            var url = 'api/' + this.controllerName + '/DelAttachment?id=' + id;
            return rt.get(url);
        };

        this.createData = function (model) {
            var url = 'api/' + this.controllerName + '/CreateData';
            return rt.post(url, JSON.stringify(model));
        };

        this.updateData = function (model) {
            var url = 'api/' + this.controllerName + '/UpdateData';
            return rt.post(url, JSON.stringify(model));
        };

        this.delData = function (idList) {
            var url = 'api/' + this.controllerName + '/DeleteData';
            return rt.post(url, JSON.stringify(idList));
        };

        this.activateData = function (idList) {
            var url = 'api/' + this.controllerName + '/ActivateData';
            return rt.post(url, JSON.stringify(idList));
        };

        this.deactivateData = function (idList) {
            var url = 'api/' + this.controllerName + '/DeactivateData';
            return rt.post(url, JSON.stringify(idList));
        };

        this.assignData = function (idList, userId) {
            var url = 'api/' + this.controllerName + '/AssignData?userId=' + userId;
            return rt.post(url, JSON.stringify(idList));
        };

        this.exportViewData = function (reqData) {
            var url = 'api/' + this.controllerName + '/ExportViewData';
            return rt.post(url, reqData);
        };

        this.flowSubmit = function (reqData) {
            var url = 'api/' + 'FlowApproval' + '/FlowSubmit';
            return rt.post(url, reqData);
        };

        this.flowApprove = function (reqData) {
            var url = 'api/FlowApproval/FlowApprove';
            return rt.post(url, reqData);
        };

        this.flowReject = function (reqData) {
            var url = 'api/FlowApproval/FlowReject';
            return rt.post(url, reqData);
        };

        this.flowRecall = function (reqData) {
            var url = 'api/FlowApproval/FlowRecall';
            return rt.post(url, reqData);
        };

        this.flowTransmit = function (reqData, userid) {
            var url = 'api/FlowApproval/FlowTransmit?userId=' + userid;
            return rt.post(url, reqData);
        };

        this.getApprovalList = function (id) {
            if (rt.isNull(id) || id.length === 0) {
                var deferred = $q.defer();
                deferred.resolve({ data: null });
                return deferred.promise;
            }

            var url = 'api/' + 'FlowApproval' + '/GetFlowApprovalListByObjectId?objectId=' + id;
            return rt.get(url);
        };

        this.getEditApprovalList = function (id, typename) {
            var url = 'api/FlowApproval/GetEditApprovalList?objectId=' + id + '&typename=' + typename;
            return rt.get(url);
        };

        this.getApprovalStatus = function (id) {
            if (rt.isNull(id) || id.length === 0) {
                var deferred = $q.defer();
                deferred.resolve({ data: null });
                return deferred.promise;
            }

            var url = 'api/FlowApproval/GetFormApprovalStatus?objectId=' + id;
            return rt.get(url);
        };

        //进入不同的只读页面
        var _objectFlowStates = {
            "absence": "absence-read",
            "common_application": "commonApplication-read",
            "business_trip": "businessTrip-read",
            "expense": "expense-read"
        };
        this.goFlowReadPage = function (formid, typename) {
            if (rt.isNull(typename)) {
                var typename = this.approvalTypeName;
            }

            var stateName = _objectFlowStates[typename];
            $state.go(stateName, { id: formid });
        };

        this.readerSubmit = function (reqData) {
            var url = 'api/' + 'WorkReportRead' + '/ReaderSubmit';
            return rt.post(url, reqData);
        };

        this.readerSubmitAtComment = function (reqData) {
            var url = 'api/' + 'WorkReportRead' + '/ReaderSubmitAtComment';
            return rt.post(url, reqData);
        };

        this.getEditReaderList = function (id) {
            var url = 'api/WorkReportRead/GetEditReaderList?objectId=' + id;
            return rt.get(url);
        };

        //进入不同的只读页面
        var _objectReportStates = {
            "daily_report": "dailyreport-read",
            "weekly_report": "weeklyreport-read",
            "monthly_report": "monthlyreport-read",
            "weekly_report_zl": "weeklyreportzl-read",
            "daily_plan": "dailyplan-read",
            "weekly_plan": "weeklyplan-read",
            "monthly_plan": "monthlyplan-read"
        };
        this.goReportReadPage = function (formid, typename) {
            if (rt.isNull(typename)) {
                var typename = this.reportTypeName;
            }

            var stateName = _objectReportStates[typename];
            $state.go(stateName, { id: formid });
        };

        //更改工作报告阅读状态
        this.updateReadState = function (objectId) {
            var url = 'api/WorkReportRead/UpdateReadState?objectId=' + objectId;
            return rt.get(url);
        };

        //发送评论
        this.sendComment = function (objectId, text) {
            var url = 'api/PostComment/SendComment?object_id=' + objectId + "&text=" + text;
            return rt.post(url);
        };

        //获取评论
        this.getCommentListById = function (objectId) {
            var url = 'api/PostComment/GetCommentListById?objectId=' + objectId;
            return rt.get(url);
        };

    }
})();
/********************************************************
 Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved.
 创建人   : joe Song
 创建时间 : 2016-03-10
 说明     : lookup选择的帮助函数
 *********************************************************/
(function () {
    'use strict';
    angular.module('xrmApp').service('rtLookup', ['$ionicModal', function ($ionicModal) {

        function _sLookup($s, lookupParams) {
            var url = 'component/lookup/singleLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            });
        };

        this.sLookup = _sLookup;

        //用户单选，有头像
        this.userLookup = function ($s, isFiltered, cb) {
            var lookupParams = {
                getDataName: 'UserInfo.GetAllUser',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: isFiltered,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/userLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //用户单选，有常用选择用户，有头像
        this.userWithFrequentLookup = function ($s, moduleName, isFiltered, cb) {
            var lookupParams = {
            	getDataName: 'userinfo.GetAllUserInfo',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: isFiltered,
                moduleName: moduleName,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/userWithFrequentLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //根据部门选择用户，单选，有常用选择用户，有头像
        this.userAccordingBULookup = function ($s, moduleName, isFiltered, buid, cb) {
            var lookupParams = {
                getDataName: 'UserInfo.GetUserByBu',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: isFiltered,
                moduleName: moduleName,
                paramslist: {'@businessunitid': buid},
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/userWithFrequentLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //用户多选，有常用选择用户，无头像，有重置按钮
        this.userMutiWithResetLookup = function ($s, moduleName, isFiltered,userIds, cb) {
            var lookupParams = {
                getDataName: 'UserInfo.GetAllUser',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                moduleName: moduleName,
                isFiltered: isFiltered,
                userIds:userIds,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/userMutiLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //用户多选，有常用选择用户，无头像，无重置按钮
        this.userMutiLookup = function ($s, moduleName, isFiltered, cb) {
            var lookupParams = {
                getDataName: 'UserInfo.GetAllUser',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                moduleName: moduleName,
                isFiltered: isFiltered,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/userMutiLookup2View.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        this.contactLookup = function ($s, cb, accountid) {
            var lookupParams = {
                getDataName: 'Contact.GetContact',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: true,
                paramslist: {'@accountid': accountid},
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/contactLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        this.contactLookup3 = function ($s, cb, accountid) {
            var lookupParams = {
                getDataName: 'Contact.GetContact',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: false,
                paramslist: {'@accountid': accountid},
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/contactLookup2View.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        this.contactLookup2 = function ($s, cb, departmentid) {
            var lookupParams = {
                getDataName: 'Contact.GetDepContact',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: true,
                paramslist: {'@departmentid': departmentid},
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/contactLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //医院拜访，医生lookup，包含代表负责的医生
        this.contactDeptLookup = function ($s, cb, departmentid) {
            var lookupParams = {
                getDataName: 'Contact.GetDepContact',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: true,
                paramslist: {'@departmentid': departmentid},
                departmentid: departmentid,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/contactDeptLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        this.contactLookupWithFiltered = function (filtered, $s, cb, accountid) {
            var lookupParams = {
                getDataName: 'Contact.GetContact',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: filtered,
                paramslist: {'@accountid': accountid},
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/contactLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        this.provinceLookup = function ($s, cb) {
            _sLookup($s, {
                getDataName: 'Province.GetProvince',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: false,
                onDataSelected: function (d) {
                    cb(d);
                }
            }).then(function (d) {
                d.show();
            });
        };

        this.buLookup = function ($s, cb) {
            _sLookup($s, {
                getDataName: 'TblBusinessUnit.BusinessUnitId',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: false,
                onDataSelected: function (d) {
                    cb(d);
                }
            }).then(function (d) {
                d.show();
            });
        };

        this.createCascadePickerDialog = function(config) {
            var $scope = config.scope;

            if (this.isNull($scope.cascadePicker)) {
                $scope.cascadePicker = {};
            }
            $scope.cascadePicker.title = config.title || '';
            $scope.cascadePicker.dataProvider = config.dataProvider || [];
            $scope.cascadePicker.selectedValue = config.selectedValue || [];
            $scope.cascadePicker.success = config.success;
            $scope.cascadePicker.close = function() {
                this.modal.hide();
            };

            return $ionicModal.fromTemplateUrl('component/lookup/cascadePickerDialog.html', function(ionicModal) {
                $scope.cascadePicker.modal = ionicModal;
            }, {
                scope: $scope,
                animation: 'slide-in-up'
            });
        }


        this.businessUnitLookup = function ($s, cb) {
            _sLookup($s, {
                getDataName: 'TblBusinessUnit.BuidBusinessUnitId',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: false,
                onDataSelected: function (d) {
                    cb(d);
                }
            }).then(function (d) {
                d.show();
            });
        };

        this.businessUnitChildLookup = function ($s, cb, parentid) {
            _sLookup($s, {
                getDataName: 'TblBusinessUnit.ChildBusinessUnitId',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: false,
                paramslist: {'@ParentBusinessUnitId': parentid},
                onDataSelected: function (d) {
                    cb(d);
                }
            }).then(function (d) {
                d.show();
            });
        };

        this.buCascadeSingleLookup = function ($s, cb) {
            var lookupParams = {
                getDataName: 'TblBusinessUnit.BuidBusinessUnitId',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: true,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/buSingleLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        this.buCascadeMultiLookup = function ($s, cb) {
            var lookupParams = {
                getDataName: 'TblBusinessUnit.BuidBusinessUnitId',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: true,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/buMultiLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };
        //业务部门级联选择
        this.buLookup2 = function ($s, multiple, cb) {
            var lookupParams = {
                getDataName: 'TblBusinessUnit.BuidBusinessUnitIdWithType',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: false,
                isMultiple: multiple,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/buReportLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //业务部门级联选择(只到业务线)
        this.buLookup3 = function ($s, cb) {
            var lookupParams = {
                getDataName: 'TblBusinessUnit.BuidBusinessUnitIdWithType',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: false,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/buReportLookupView2.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //拜访目的多选
        this.visitPurposeLookup = function (dataUrl, isMultiple, $s, cb) {
            var lookupParams = {
                getDataName: '',
                dataUrl: dataUrl,
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: false,
                isMultiple: isMultiple,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var selectedDataList = $s.vm.purposeList;
            var url = 'component/lookup/visitpurposeLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //药品信息选择lookup
        this.productLookup = function (isMultiple, isFiltered, $s, cb) {
            var lookupParams = {
                getDataName: 'Product.GetProduct_information',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: isFiltered,
                isMultiple: isMultiple,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/productLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //医生选择
        this.doctorLookup = function ($s, multiple, cb) {
            var lookupParams = {
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: false,
                isMultiple: multiple,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/doctorLookupView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        this.accountLookup = function ($s, accClass, initType, cb) {
            var lookupParams = {
                getDataName: 'Account.GetAllBusinessDetail',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: true,
                accClass: accClass,
                initType: initType,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
            var url = 'component/lookup/accountLookupAndOwnerView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        // 新增没有视图的客户选择lookup
        // 去掉医院和门店拜访时的视图选择
        this.accountLookup2 = function ($s, accClass, initType, cb) {
            var lookupParams = {
                getDataName: 'Account.GetAllBusinessDetail',
                orderby: 'name asc',
                fields: [],
                mainFieldCode: 'name',
                isShowLabel: false,
                isFiltered: true,
                accClass: accClass,
                initType: initType,
                onDataSelected: function (data) {
                    cb(data);
                }
            };
			
            var url = 'component/lookup/accountLookupAndOwner2View.html';

            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            }).then(function (d) {
                d.show();
            });
        };

        //商客户查找+地图页面
        this.sLookupAndMap = function ($s, lookupParams) {
            var url = 'component/lookup/accountLookupAndMapView.html';
            return $ionicModal.fromTemplateUrl(url, function ($ionicModal) {
                $s.dialog = $ionicModal;
                $s.closeDialog = function () {
                    $s.dialog.hide();
                };
                if (lookupParams !== undefined) {
                    $s.lookupParams = lookupParams;
                }
            }, {
                scope: $s, animation: 'slide-in-up'
            });
        };
    }]);
})();

/********************************************************
Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved. 
 创建人   : joe Song
 创建时间 : 2016-03-10
 说明     : 常用帮助函数，如是否是手机号等
*********************************************************/
(function () {
    'use strict';
    angular.module('xrmApp').service('rtMapLocation', ['$ionicModal', function ($ionicModal) {

        this.selectMapLocation = function (scope, cb) {
            var $s = scope;
            var url = 'component/map/mapLocationCheckView.html';
            $ionicModal.fromTemplateUrl(url,
                function ($ionicModal) {
                    $s.dialog = $ionicModal;
                    $s.closeDialog = function () {
                        $s.dialog.hide();
                        $s.dialog.remove();
                    };
                    $s.mapCb = cb;
                },
                {
                    scope: $s, animation: 'slide-in-up'
                })
                .then(function (d) {
                    return d.show();
                }).then(function () {
                    $s.$broadcast('rt-show-modal-map');
                });
        };

        
        this.showMapLocation = function (scope, pos) {
            var $s = scope;
            var url = 'component/map/mapLocationShowView.html';
            $ionicModal.fromTemplateUrl(url,
                function ($ionicModal) {
                    $s.dialog = $ionicModal;
                    $s.closeDialog = function () {
                        $s.dialog.hide();
                        $s.dialog.remove();
                    };
                    $s.sml = pos;
                },
                {
                    scope: $s, animation: 'slide-in-up'
                })
                .then(function (d) {
                    return d.show();
                }).then(function () {
                    $s.$broadcast('rt-show-modal-map');
                });
        };
    }]);
})();

/********************************************************
Copyright @ 苏州瑞泰信息技术有限公司 All rights reserved. 
 创建人   : joe Song
 创建时间 : 2016-03-10
说明     :  将所有的公用函数库合并到rt对象中
*********************************************************/
(function () {
    'use strict';
    angular.module('xrmApp')
        .service('rt', ['rtUtils', 'rtRestClient', 'rtFlow', 'rtPrivilege', 'rtData', 'rtFile','rtMapLocation','rtLookup',
            function (rtUtils, rtRestClient, rtFlow, rtPrivilege, rtData, rtFile,rtMapLocation,rtLookup) {
                _.extend(this, rtUtils, rtRestClient, rtFlow, rtPrivilege, rtData, rtFile,rtMapLocation,rtLookup);
            }]);
})();

