/**
 * 外壳命令调用模块
 * User: yuwang@iflytek.com
 * Date: 13-6-20 上午9:36
 * Version: 1.0
 */
define(function (require, exports) {
    require('browserContext');
    var path = require('./path');
    var md5helper = require('./md5helper');

    /**
     * 拷贝文件
     * @param {string} src 原始文件路径
     * @param {string} dst 目标路径
     */
    function copyFile(src, dst) {
        src = src.replace(/\//g, '\\\\');
        dst = dst.replace(/\//g, '\\\\');

        var defer = $.Deferred();
        callClient('syscmd', 'cmd', 'copy /y "{0}" "{1}"'.format(src, dst), 0, function () {
            defer.resolve();
        });
        return defer.promise();
    }

    /**
     * 批量复制
     * @param args
     */
    function multiCopyFile(args) {
        var defered= $.Deferred();
        showLoading({tips: AppTips.OpenResLoadingTips});
        callClient('syscmd', 'batfilecopy', args, 0, function (ret) {
            hideLoading();
            defered.resolve(ret=='true');
        });
        return defered.promise();
    }

    /***
     * 异步copy目录
     * @param {string} src
     * @param {string} dst
     */
    function copyDir(src, dst) {
        var args = src + "|" + dst;

        var defer = $.Deferred();
        callClient('syscmd', 'dircpy', args, 0, function () {
            defer.resolve();
        });
        return defer.promise();
    }

    /***
     * 从TCH里抽取MP3(目前弃用)
     * @param tch
     * @param bookid
     * @param spotId
     * @param lan
     * @returns {*}
     */
    function extractMp3(tch, bookid, spotId, lan) {
        var str = [tch, bookid, spotId, lan].join('|');
        return callClient('syscmd', 'extractmp3', str, 0);
    }

    /**
     * 语音合成
     * @param {string} text
     * @param {string} speecher
     * @param {string} audioPath
     * @param {boolean} useCSSML
     * @returns {json}
     */
    function text2speech(text, speecher, audioPath, useCSSML) {

        var max = 30;
        var saveJSONtoFile = false;
        var isCnSpeecher = (speecher === "xiaoyan" || speecher === "xiaoyu" || speecher === "wangru");
        if (text.length > max && useCSSML != true && isCnSpeecher)
            saveJSONtoFile = true;

        var param = {"SynthText": text, "VoiceSpeecher": speecher, "WordSpeed": "5", "UseCSSML": "0", "AudioPath": audioPath};
        if (useCSSML) {
            param.UseCSSML = "1";
        }
        //因为CEF传输大数据有BUG,当合成出的JSON太大的时候,把JSON保存到硬盘,再同步读出.
        if (saveJSONtoFile)
            param.SavePath = Config.tmpPath + "/ttsresult.txt";

        var dtd = $.Deferred();
        var callback = function (args) {
            var data = args || '';
            if (data.length > 2) {
                if (saveJSONtoFile) {
                    var json = readFile(param.SavePath);
                    dtd.resolve(json, param);
                } else {
                    //合成结果是个很长的json串
                    dtd.resolve(data, param);
                }
            }
            else {
                console.error('text2speech failed');
                dtd.resolve(data, param);
            }
        };
        callClient('syscmd', 'text2speech', JSON.stringify(param), 0, callback);
        return dtd.promise();
    }

    /**
     * 手写识别
     * @param {json} jsonStr
     * @returns {string}
     */
    function hcr(jsonStr) {
        var def = $.Deferred();
        callClient('syscmd', 'hcr', jsonStr, 0, function (wordStr) {
            def.resolve(wordStr);
        });
        return def.promise();
    }

    /**
     * 初始化合成引擎
     * @returns {boolean}
     */
    function initTTS() {
        var def = $.Deferred();
        callClient('syscmd', 'inittts', '', 0, function (initResult) {
            def.resolve(initResult == "true");
        });
        return def.promise();
    }

    /**
     * 逆初始化引擎
     * @returns {boolean}
     */
    function UninitTTS() {
        var def = $.Deferred();
        callClient('syscmd', 'finitts', '', 0, function () {
            def.resolve();
        });
        return def.promise();
    }

    function playVideo(src, playerState) {
        src = path.toWindows(path.trimPosix(src));

        var player = path.trimPosix(Config.binPath + "splayer/splayer.exe");
        src = '"' + src + '"';

        var cmdArgs = player + '|' + src + '|' + playerState;
        //console.log(cmdArgs);

        var defer = $.Deferred();
        callClient('syscmd', 'shellexecute', cmdArgs, 0, function () {
            defer.resolve();
        });
        return defer.promise();

    }

    /**
     * 播放音频
     * @param audioPath {string} 音频地址
     */
    function sndPlay(audioPath) {
        callClient('syscmd', 'sndplay', audioPath, 2);
    }

    /**
     * 暂停播放
     */
    function sndPause() {
        callClient('syscmd', 'sndpause', '', 0);
    }

    /**
     * 停止播放
     */
    function sndStop() {
        callClient("syscmd", "sndstop", "", 0);
    }

    /**
     * 继续播放
     */
    function sndResume() {
        callClient("syscmd", "sndresume", "", 2);
    }

    /**
     *
     * 保存文件异步
     * @param {string} content 文件文本类容
     * @param {string} filePath 文件路径
     */
    function saveFilAsync(content, filePath) {
        var def = $.Deferred();
        callClient('syscmd', 'savefile', '{0}|{1}'.format(filePath, content), 0, function (ret) {
            if (!ret) {
                console.error('shellcmd::saveFile return fail');
            }
            def.resolve(ret);
        });
        return def.promise();
    }

    /**
     * 将html 5 拍照的base64 保存成图片，插入到书本中
     * @param content
     * @returns {*}
     */
    function saveBase64AsImage(content) {
        var def = $.Deferred();
        callClient('syscmd', 'savebaseimage', content, 0, function (ret) {
            if (!ret) {
                console.error('shellcmd::saveFile return fail');
            }
            def.resolve(ret);
        });
        return def.promise();
    }


    /**
     * 读取文件类容异步
     * @param {string} filePath  文件路径
     * @return {string}
     */
    function readFileAsync(filePath) {
        var def = $.Deferred();
        if (AppCfg.useAjax) {
            //这里是同步的
            var fileObj = $.ajax({url: filePath, async: false});
            def.resolve(fileObj.responseText);
        }
        else {
            callClient('syscmd', 'readfile', filePath, 0, function (ret) {
                def.resolve(ret);
            });
        }
        return def.promise();
    }

    /**
     * 判断文件是否存在
     * @param {string} filePath 文件路径
     * @returns {boolean}
     */
    function isFileExist(filePath) {
        //console.log('%c isFileExists start %s', 'color:green', filePath);
        var defer = $.Deferred();
        if(!filePath) return defer.resolve(false);
        filePath = path.trimPosix(filePath);
        callClient('syscmd', 'fileexists', filePath, 0, function (ret) {
            // console.log('%c isFileExists end %s %s','color:brown',filePath,ret);

            defer.resolve(ret === 'true');
        });
        return defer.promise();
    }


    /**
     * 判断文件是否存在 (同步方法)
     * @param {string} filePath 文件路径
     * @returns {boolean}
     */
    function isFileExistSync(filePath) {
        return cef.fs.fileExists(filePath);
    }


    /***
     * 判断目录是否存在
     * @param dir
     * @returns promise对象
     */
    function isDirExist(dir) {
        if (!isShellRunning()) {
            console.warn("application is not running shell!");
            return true;
        }
        dir = path.trimPosix(dir);
        var defer = $.Deferred();
        callClient('syscmd', 'isdirexist', dir, 0, function (ret) {
            defer.resolve(ret === 'true');
        });
        return defer.promise();
    }

    /***
     * 判断目录是否存在
     * @param dir
     * @returns promise对象
     */
    function isDirExistSync(dir) {
        return cef.fs.dirExists(dir);
    }

    /***
     * 创建目录
     * @param dir
     * @returns promise对象
     */
    function createDir(dir) {
        dir = path.trimPosix(dir);
        var defer = $.Deferred();
        callClient('syscmd', 'createdir', dir, 0, function (ret) {
            defer.resolve(ret === 'true');
        });
        return defer.promise();
    }

    /***
     * 删除目录
     * @param dir
     * @returns promise对象
     */
    function deleteDir(dir) {
        dir = path.trimPosix(dir);
        var defer = $.Deferred();
        callClient('syscmd', 'deletedir', dir, 0, function (ret) {
            defer.resolve(ret === 'true');
        });
        return defer.promise();
    }


    function createDirIfNotExist(dir) {
        if (!isDirExistSync(dir))
            createDir(dir);
    }

    /**
     * 读取文件类容(同步方法!!)
     * @param {string} filePath  文件路径
     * @return {string}
     */
    function readFile(filePath) {
        if (!isShellRunning()) {
            console.warn("application is not running shell!");
            return "";
        }
        filePath = path.trimPosix(filePath);
        var retval;
        var file = cef.fs;
        try {
            retval = file.readAll(filePath);
        } catch (e) {
            console.error(e);
            retval = null;
        }
        return retval;
    }

    /**
     * 保存文件 (同步方法!!!)
     * @param {string} content 文件文本类容
     * @param {string} filePath 文件路径
     */
    function saveFile(content, filePath) {
        if (!isShellRunning()) {
            console.warn("application is not running shell!");
            return;
        }
        filePath = path.trimPosix(filePath);
        var retval;
        var file = cef.fs;
        try {
            file.writeAll(filePath, content);
        } catch (e) {
            console.error(e);
        }
    }

    /**
     * 删除文件
     * @param filePath
     */
    function deleteFile(filePath) {
        if (!isShellRunning()) {
            console.warn("application is not running shell!");
            return false;
        }
        filePath = path.trimPosix(filePath);
        //console.log("delete file:" + filePath);
        var defer = $.Deferred();
        callClient('syscmd', 'deletefile', filePath, 0, function (ret) {
            defer.resolve(ret === 'true');
        });
        return defer.promise();
    }

    /***
     * 读取DRM加密资源
     * @param token
     * @param zip
     * @param lic
     * @param file
     * @param savepath
     * @returns {*}
     */
    function readEncryptFile(token, zip, lic, file, savepath) {
        var param = {"token": "", "zip": "", "lic": "", "file": "", "savepath": ""};
        param.token = token;
        param.zip = zip;
        param.lic = lic;
        param.file = file;
        param.savepath = savepath;

        console.time('readdrmres:' + file);
        var defer = $.Deferred();
        callClient('syscmd', 'drmunpacker', JSON.stringify(param), 0, function (ret) {
            defer.resolve(ret);
            console.timeEnd('readdrmres:' + file);
        });
        return defer.promise();
    }


    /**
     * 获取硬件号
     * @returns {string}
     */
    function getHardwareInfo(userAccount) {
        var defer = $.Deferred();
        callClient('syscmd', 'getsn', '', 0, function (ret) {
            var md5encode = md5helper.hex_md5(ret + userAccount);
            defer.resolve(md5encode);
        });
        return defer.promise();
    }

    /**
     * 获取硬件类型
     * @returns {string}  0:计算机，1：平板
     */
    function getHardwareType() {
        var defer = $.Deferred();
        callClient('syscmd', 'checkhardware', '', 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /**
     * 获取硬件名称
     * @returns {string}
     */
    function getHardwareName() {
        var defer = $.Deferred();
        callClient('syscmd', 'getcomptname', '', 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /**
     * 环境检查
     * @returns {boolean}
     */
    function checkEnvironment() {
        var defer = $.Deferred();
        callClient('syscmd', 'getsn', '', 0, function (ret) {
            defer.resolve(ret != null);
        });
        return defer.promise();
    }

    /**
     * 联网检查
     * 一般联网检测检查的都是这个页面，书库例外
     * @returns {boolean}
     */
    function checkOnline() {
        var defer = $.Deferred();
        checkUrlAccess(AppRemoteSvcCfg.OnlineCheckUrl).done(function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /**
     * 书库页面检查
     * @returns {*}
     */
    function checkUrlAccess(url) {
        var defer = $.Deferred();
        if (AppCfg.useAjax) {
            var param = {};
            if (AppCfg.ajaxTimeOut > 0) {
                param = {type: "GET", url: url, timeout: AppCfg.ajaxTimeOut};
            } else {
                param = {type: "GET", url: url};
            }
            $.ajax(param)
                .done(function (data) {
                    defer.resolve(true);
                })
                .error(function(XMLHttpRequest, textStatus, errorThrown){
                    console.log(XMLHttpRequest.status);
                    defer.resolve(false);
                });
        } else {
            callClient('syscmd', 'checkurlaccess', url, 0, function (ret) {
                defer.resolve(ret === 'true');
            });
        }
        return defer.promise();
    }


    function postHttpRequest(msg) {
        var defer = $.Deferred();
        msg["version"] = AppCfg.version;
        msg["product"]=AppCfg.product;
        var msgStr = JSON.stringify(msg);
        if (AppCfg.useAjax) {
            var param = {};
            if (AppCfg.ajaxTimeOut > 0) {
                param = {type: "POST", url: msg.url, data: msg, timeout: AppCfg.ajaxTimeOut};
            } else {
                param = {type: "POST", url: msg.url, data: msg};
            }
            $.ajax(param)
                .done(function (data) {
                    defer.resolve(data);
                })
                .fail(function () {
                    console.log("http post ajax failed");
                    defer.resolve("");
                });
        } else {
            callClient('syscmd', 'httppost', msgStr, 0, function (ret) {
                defer.resolve(ret);
            });
        }
        return defer.promise();
    }

    /**
     * 异步联网检查
     * @returns {boolean}
     */
    function checkOnlineAsyn() {
        var ret = callClient('syscmd', 'sychisnetworking', "http://www.baidu.com/", 2);
    }


    /**
     * 调用外部浏览器打开页面
     * @param url
     * @private
     */
    function openPageOutside(url) {
        callClient('syscmd', 'shellexecute', url, 0);
    }

    /**
     * 文件下载
     * @param fileMetadata
     */
    function fileDownload(fileMetadata) {
        // if (AppCfg.useDownloader) {
        callClient("syscmd", "download", fileMetadata, 2);
//        }
//        else {
//            callClient("syscmd", "filedownload", fileMetadata, 2);
//        }
    }

    function getMetaMap(url) {
        if (url == null || url == "") {
            return;
        }
        var def = $.Deferred();
        callClient('syscmd', 'getbookmap', url, 0, function (ret) {
            def.resolve(ret);
        });
        return def.promise();
    }

    /**
     * 获取书本lic
     * @param url
     * @param bookId
     * @param userAccount
     * @param hdInfo
     * @param hdType
     * @returns {*}
     */
    function getBookLic(url, bookId, userAccount, hdInfo, hdType, savePath) {
        var defer = $.Deferred();
        var httpurl = AppRemoteSvcCfg.BookLicenseGetUrl;
        var msgJson = {
            url: httpurl,
            account: userAccount,
            resid: bookId,
            hardware: hdInfo,
            hdtype: hdType,
            savepath: savePath,
            version: AppCfg.version,
            product:AppCfg.product,
        };
        var msg = JSON.stringify(msgJson);
        //console.log(msg);
        callClient('syscmd', 'getbooklic', msg, 0, function (ret) {
            defer.resolve(ret);
        });
//        postHttpRequest(msg).done(function(ret){
//            defer.resolve(ret);
//        });
        return defer.promise();
    }

    /**
     * 连接数据库
     * @param dbPath
     * @returns {boolean}
     */
    function connectDb(dbPath) {
        var defer = $.Deferred();
        callClient("syscmd", "connectdb", dbPath, 0, function (ret) {
            defer.resolve(ret == 1);
        });
        return defer.promise();
    }

    /**
     * 读数据库
     * @param sql
     * @returns {*}
     */
    function retriveDbAsyn(dbPath, sql) {
        var defer = $.Deferred();
        callClient("syscmd", "connectdb", dbPath, 0, function (ret) {
            if (ret == 1) {
                callClient("syscmd", "opensql", sql, 0, function (ret2) {
                    //console.log(ret2);
                    defer.resolve(ret2);
                });
            } else {
                defer.resolve(null);
            }
        });
        return defer.promise();
    }

    /**
     * 写数据库
     * @param sql
     * @returns {boolean}
     */
    function executeDbAsyn(dbPath, sql) {
        var defer = $.Deferred();
        callClient("syscmd", "connectdb", dbPath, 0, function (ret) {
            if (ret == 1) {
                callClient("syscmd", "execsql", sql, 0, function (ret2) {
                    defer.resolve(ret2 === 'true');
                });
            } else {
                defer.resolve(false);
            }
        });
        return defer.promise();
    }

    /**
     * 获取首条记录
     * @param sql
     * @returns {*}
     */
    function getFirstItem(sql) {
        var defer = $.Deferred();
        callClient("syscmd", "opensqlandgetfirst", sql, 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }


    function getFirstItemAsyn(dbPath, sql) {
        var defer = $.Deferred();
        callClient("syscmd", "connectdb", dbPath, 0, function (ret) {
            if (ret == 1) {
                callClient("syscmd", "opensqlandgetfirst", sql, 0, function (ret) {
                    defer.resolve(ret);
                });
            } else {
                defer.resolve();
            }
        });
        return defer.promise();
    }

    /**
     * 导出资源
     * @param value
     * @returns {*}
     */
    function resExport(value) {
        var defer = $.Deferred();
        callClient('syscmd', 'resexport', value, 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /**
     * 导入资源的对话框
     */
    function resImport() {
        var defer = $.Deferred();
        callClient('syscmd', 'resimport', '', 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /**
     * 获得导入资源的内容
     * @param importPath
     * @returns {*}
     */
    function getZipInnercode(importPath) {
        var defer = $.Deferred();
        callClient('syscmd', 'getzipinnercode', importPath, 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /**
     * 删除目录下的所有文件但不删除目录和子目录
     * @param dir
     * @returns {*}
     */
    function clearDir(dir) {
        var defer = $.Deferred();
        callClient("syscmd", "cleardir", dir, 0, function (ret) {
            defer.resolve(ret === 'true');
        });
        return defer.promise();
    }

    /**
     * 解压
     * @param args  格式为：'{"zippath":"' + importPath + '","despath":"' + pathDir + '"}'
     * @returns {*}
     */
    function unzip(args) {
        var defer = $.Deferred();
        callClient('syscmd', 'unzip', args, 0, function (ret) {
            defer.resolve(ret === 'true');
        });
        return defer.promise();
    }

    function isDirEmpty(dir) {
        var defer = $.Deferred();
        callClient('syscmd', 'isdirempty', dir, 0, function (ret) {
            defer.resolve(ret === 'true');
        });
        return defer.promise();
    }

    /**
     * 选择目录
     * @returns {*}
     */
    function dirSelect() {
        var defer = $.Deferred();
        callClient('syscmd', 'dirselect', '', 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /**
     * 程序最小化
     */
    function ebookMin() {
        callClient('syscmd', 'ebookmin', '', 0);
    }

    /**
     * 关闭程序
     */
    function closeApp() {
        var defer = $.Deferred();
        callClient('syscmd', 'ebookclose', '', 0, function (ret) {
            defer.resolve();
        });
        return defer.promise();
    };

    function checkLocalAuthorization(msg) {
        var defer = $.Deferred();
        callClient('syscmd', 'checkauthor', msg, 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    };

    function desEncrpty(content, key) {
        var defer = $.Deferred();
        var argsJson = '{"content":"' + content + '","key":"' + key + '"}';
        callClient('syscmd', 'desencode', argsJson, 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }


    /**
     * 密码解密
     * @param content
     * @param key
     * @returns {*|string}
     */
    function desDecrpty(content, key) {
        var des = $.Deferred();
        var argsJson = '{"content":"' + content + '","key":"' + key + '"}';
        callClient('syscmd', 'desdecode', argsJson, 0, function (ret) {
            des.resolve(ret);
        })
        return des.promise();
    }

    /**
     * 读取书本许可证
     * @param msg
     */
    function getBookLicNode(msg) {
        var des = $.Deferred();
        callClient('syscmd', 'getresliccontent', msg, 0, function (ret) {
            console.log('getresliccontent: ' + ret);
            des.resolve(ret);
        });
        return des.promise();
    }

    function getImageFromUrl(imgUrl, savePath) {
        var des = $.Deferred();
        callClient('syscmd', 'saveimagefromurl', imgUrl + '|' + savePath, 0, function (ret) {
            des.resolve(ret);
        });
        return des.promise();
    }

    /**
     * 打开文件对话框
     * @param options
     * @returns {*}
     */
    function openDialog(options) {
        var defer = $.Deferred();
        callClient('syscmd', 'opendialog', options, 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /***
     * CEF 自已的文件打开功能,见clienttest.html 示例
     * @param options
     * @returns {*}
     */
    function openFileDialog(options) {
        var defer = $.Deferred();
        options.ext.unshift('');
        if (options.multi) {
            sendCefMsg('dialog.multifileopen', options.ext, function (ret) {
                defer.resolve(ret);
            });
        } else {
            sendCefMsg('dialog.fileopen', options.ext, function (ret) {
                defer.resolve(ret);
            });
        }
        return defer.promise();
    }

    /**
     * 获取系统System32目录
     * @returns {*}
     */
    function getSystemDir() {
        var defer = $.Deferred();
        callClient('syscmd', 'getsystem32', '', 0, function (ret) {
            //console.log(ret);
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /**
     * 取消下載
     * @param id 下載資源的ID
     */
    function cancleDownload(id) {
        var defer = $.Deferred();
        callClient('syscmd', 'canceldownload', id, 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }


    function shellExecute(src) {
        var defer = $.Deferred();
        callClient('syscmd', 'shellexecute', path.trimPosix(src), 0, function (ret) {
            defer.resolve(ret);
        });
        return defer.promise();
    }

    /**
     * 隐藏客户端外壳
     * @returns {*}
     */
    function shellHide() {
        var def = $.Deferred();
        callClient('syscmd', 'ebookhide', "", 0, function (ret) {
            def.resolve(ret);
        });
        return def.promise();
    }

    /**
     * 文件上传
     * @returns {*}
     */
    function uploadFile(msg) {
        var def = $.Deferred();
        callClient('syscmd', 'upload', msg, 0, function () {
            def.resolve(eval('(' + msg + ')'));
        });
        return def.promise();
    }

    function saveAsDlg(title) {
        var def = $.Deferred();
        callClient('syscmd', 'saveasdlg', title, 0, function (ret) {
            def.resolve(ret);
        });
        return def.promise();
    }

    function chaptersExport(args) {
        var def = $.Deferred();
        callClient('syscmd', 'chaptersexport', args, 0, function (ret) {
            def.resolve(ret);
        });
        return def.promise();
    }

    /**
     * 重命名文件
     * @param src
     * @param newname
     */
    function rename(src, newname) {
        //  callClient('syscmd', 'cmd', 'rename "{0}" "{1}"'.format(src, newname), 0);
        //console.log(src, newname)
        callClient('syscmd', 'filerename', src + "|" + newname, 0);
    }

    /**
     * 调用输入法
     * @param type
     * @param focusElem
     */
    function callIme(type, focusElem) {
        var def = $.Deferred();
        var exePath = "";
        if (type == "write") {
            exePath = path.trimPosix(Config.binPath) + "iFlyIme/iFlyInk.exe";
        }
        else if (type == "voice") {
            exePath = path.trimPosix(Config.binPath) + "iFlyIme/iFlyVoice.exe";
        }
        else if (type == "keyboard") {
            openOsk(exePath);
            def.resolve();
            return def.promise();
        }
        shellExecute(exePath);
        focusElem.focus();
        def.resolve();
        return def.promise();
    }

    /**
     * 调用软键盘(屏幕输入法)
     * @param exePath
     * @returns {*}
     */
    function openOsk(exePath) {
        var def = $.Deferred();
        callClient('syscmd', 'openosk', exePath, 0, function () {
            def.resolve();
        });
        return def.promise();
    }

    /**
     * 关闭进程
     * @param exeName
     * @returns {*}
     */
    function killProcess(exeName) {
        var def = $.Deferred();
        callClient('syscmd', 'killprocess', exeName, 0, function () {
            def.resolve();
        });
        return def.promise();
    }

    function asynLogin(msg) {
        callClient('syscmd', 'asynlogin', msg, 0);
    }

    /**
     * 查找进程是否存在
     * @param exeName
     * @returns {*}
     */
    function findProcess(exeName) {
        var def = $.Deferred();
        callClient('syscmd', 'findprocess', exeName, 0, function (num) {
            //console.log("! " + num);
            def.resolve(num);
        });
        return def.promise();
    }

    /**
     * 单例调用输入法程序
     * @param exeName
     * @param type
     * @param focusElem
     */
    function callSingleton(exeName, type, focusElem) {
        var def = $.Deferred();
        findProcess(exeName).done(function (ret) {
            if (ret > 0) {
                def.resolve(false);
                return;
            }
            console.log("Singleton process call");
            callIme(type, focusElem).done(function () {
                //执行reiv程序 将输入法程序窗口置顶
                callClient('syscmd','runreiv','',0,function(ret){
                    def.resolve(ret=='true');
                });
                def.resolve(false);
            });
            def.resolve(false);
        });
        return def.promise();
    }

    function checkRunningDiskSpace() {
        var def = $.Deferred();
        callClient('syscmd', 'getdiskfreespace', '', 0, function (freeSpace) {
            var temp = parseInt(freeSpace);
            def.resolve(temp);
        });
        return def.promise();
    }

    function checkUnzip() {
        var def = $.Deferred();
        callClient('syscmd', 'checkunzip', '', 0, function (num) {
            var temp = parseInt(num);
            def.resolve(num>0);
        });
        return def.promise();
    }



    exports.findProcess = findProcess;

    exports.copyFile = copyFile;
    exports.extractMp3 = extractMp3;
    exports.text2speech = text2speech;
    exports.hcr = hcr;
    exports.initTTS = initTTS;
    exports.playVideo = playVideo;
    exports.sndPlay = sndPlay;
    exports.sndPause = sndPause;
    exports.sndStop = sndStop;
    exports.sndResume = sndResume;
    exports.copyDir = copyDir;
    exports.multiCopyFile = multiCopyFile;
    exports.isFileExist = isFileExist;
    exports.isFileExistSync = isFileExistSync;
    exports.isDirExist = isDirExist;
    exports.isDirExistSync = isDirExistSync;
    exports.createDir = createDir;
    exports.deleteDir = deleteDir;
    exports.createDirIfNotExist = createDirIfNotExist;

    exports.saveFile = saveFile;
    exports.saveFilAsync = saveFilAsync;
    exports.readFile = readFile;
    exports.readFileAsync = readFileAsync;
    exports.deleteFile = deleteFile;
    exports.readEncryptFile = readEncryptFile;
    exports.rename = rename;

    exports.getHardwareInfo = getHardwareInfo;
    exports.getHardwareType = getHardwareType;
    exports.getHardwareName = getHardwareName;
    exports.checkEnvironment = checkEnvironment;

    exports.checkOnline = checkOnline;
    exports.checkOnlineAsyn = checkOnlineAsyn;
    exports.getBookLic = getBookLic;
    exports.postHttpRequest = postHttpRequest;

    exports.openPageOutside = openPageOutside;

    exports.fileDownload = fileDownload;

    exports.connectDb = connectDb;

    exports.retriveDbAsyn = retriveDbAsyn;

    exports.executeDbAsyn = executeDbAsyn;
    exports.getFirstItem = getFirstItem;
    exports.getFirstItemAsyn = getFirstItemAsyn;

    exports.resExport = resExport;
    exports.resImport = resImport;
    exports.getZipInnercode = getZipInnercode;
    exports.isDirEmpty = isDirEmpty;
    exports.clearDir = clearDir;
    exports.dirSelect = dirSelect;
    exports.unzip = unzip;
    exports.saveAsDlg = saveAsDlg;
    exports.chaptersExport = chaptersExport;

    exports.ebookMin = ebookMin;
    exports.closeApp = closeApp;
    exports.checkLocalAuthorization = checkLocalAuthorization;
    exports.desEncrpty = desEncrpty;
    exports.desDecrpty = desDecrpty;
    exports.getBookLicNode = getBookLicNode;
    exports.getImageFromUrl = getImageFromUrl;

    exports.getMetaMap = getMetaMap;
    exports.openDialog = openDialog;
    exports.openFileDialog=openFileDialog;
    exports.getSystemDir = getSystemDir;
    exports.cancleDownload = cancleDownload;
    exports.shellExecute = shellExecute;
    exports.shellHide = shellHide;
    exports.uploadFile = uploadFile;

    exports.callIme = callIme;
    exports.killProcess = killProcess;
    exports.checkUrlAccess = checkUrlAccess;
    exports.asynLogin = asynLogin;
    exports.callSingleton = callSingleton;
    exports.checkRunningDiskSpace = checkRunningDiskSpace;
    exports.saveBase64AsImage = saveBase64AsImage;
    exports.checkUnzip=checkUnzip;
})