var wxlogincode = "";
var vmxFileSize = 0;
var ismoreupload = false;
var API_URL = "https://api.remeins.com/";
filemd5 = "";


if (remeins_plat == 'h5wx' || remeins_plat == 'pcwx') {
    $.post(API_URL + 'wx/getSignPackage', {
        url: window.location.href
    }, function(data, textStatus, xhr) {
        var json = jQuery.parseJSON(data);
        //配置微信信息  
        wx.config({
            debug: false, // true:调试时候弹窗  
            appId: json.appId, // 微信appid  
            timestamp: json.timestamp, // 时间戳  
            nonceStr: json.nonceStr, // 随机字符串  
            signature: json.signature, // 签名  
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中  
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'previewImage',
                'uploadImage',
                'chooseImage',
                'getLocation',
                'scanQRCode',
                'wx-open-launch-weapp'
            ]
        });

        wx.ready(function() {
            // 微信分享的数据  
            var shareData = {
                "imgUrl": 'https://p1.meituan.net/csc/6105e2ec03085048387461c364f0f3e015671.jpg', // 分享显示的缩略图地址  
                "link": window.location.href + "?from=sharewx", // 分享地址  
                "desc": '360多款实用小工具免费使用', // 分享描述  
                "title": document.title, // 分享标题   
            }
            wx.onMenuShareTimeline(shareData);
            wx.onMenuShareAppMessage(shareData);
        });

        $("body .pvimg").click(function(e) {

            wx.previewImage({
                current: $(this).attr('src'), // 当前显示图片的http链接
                urls: [$(this).attr('src')] // 需要预览的图片http链接列表
            });

        });

        wx.error(function(res) {

        });
    });
}



function login() {
    window.location.href = "https://remeins.com/login/index?url=" + window.location.href;
}




function isPc() {

    let userAgent = navigator.userAgent.toLowerCase();
    // 用 test 匹配浏览器信息
    if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(userAgent)) {
        return false;
    } else {
        return true;
    }

}


function unique() {
    let stamp = new Date().getTime();
    return (((1 + Math.random()) * stamp) | 0).toString(16);
}


function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function getVmxToken() {
    var prefix = "vmxtoken="
    var start = document.cookie.indexOf(prefix)
    if (start == -1) {
        return null;
    }
    var end = document.cookie.indexOf(";", start + prefix.length)
    if (end == -1) {
        end = document.cookie.length;
    }
    var value = document.cookie.substring(start + prefix.length, end)

    return unescape(value);
}


function mxpost(api, parm, callback) {
    var xiedaiParm = {
        vtoken: getVmxToken()
    }
    let newObj = {};
    Object.assign(newObj, xiedaiParm, parm);
    $.post(API_URL + api, newObj, callback);
}



var loginDsq;
var loginDsqIndex = 0;
var wxLoginMd5 = "";



$(function() {

    $("#searchbtn").click(function(e) {
        if ($("#search").val().length <= 0) {
            layer.msg("请输入关键词哦.")
        } else {
            window.location.href = "https://remeins.com/index/search?key=" + $("#search").val();
        }
    });

    $("#search").keydown(function(event) {
        // 检查是否按下了回车键
        if (event.keyCode === 13) {
            // 阻止默认的表单提交行为
            event.preventDefault();
            if ($("#search").val().length <= 0) {
                layer.msg("请输入关键词哦.")
            } else {
                window.location.href = "https://remeins.com/index/search?key=" + $("#search").val();
            }

        }
    });

    $("#reply").click(function(e) {
        mxpost('pub/reply', {
            alias: $(this).data("id"),
            content: $("#content").val()
        }, function(data, textStatus, xhr) {
            vmx.hideloading();
            var json = jQuery.parseJSON(data);
            if (json.status == 0) {
                setTimeout(() => {
                    window.location.reload();
                }, 300);
                layer.msg(json.msg);
            } else {
                layer.msg(json.msg);
            }
        });
    });

    $(".openrightmenu").click(function(e) {
        $(".mobilenavslist").show();
        $(".zz").show();
        e.preventDefault();
    });

    $(".zz").click(function(e) {
        $(".mobilenavslist").hide();
        $(".zz").hide();
        e.preventDefault();
    });


    $(".downloadfile").click(function() {
        if (remeins_plat == 'remeinsapp' || remeins_plat == 'uniapp') {
            rem.downfilepage(fileurl, '文件名称');
        }
    })




    $(".vmx-form").submit(function(event) {
        if ($(this).data('t') == undefined) {
            vmx.msg('开发接口未配置好，请提醒开发者。');
            return false;
        }
        var isOk = true;
        $(this).find('.vmx-test').each(function(index, el) {
            if ($(this).attr("data-vmx-test-value") == "must") {
                if ($(this).val() == "") {
                    $(this).css('border', 'solid 1px red');
                    $(this).css('background', 'rgba(255,0,0,0.3)');
                    isOk = false;
                    return;
                }
            }
        });
        if (isOk == false) {
            vmx.msg('没有填写完整');
            return false;
        }
        var url = $(this).data("url");
        vmx.loading();
        $.post(API_URL + $(this).data('t'), $(this).serialize() + "&vtoken=" + getVmxToken(), function(data, textStatus, xhr) {
            vmx.hideloading();
            if (!vmx.isJson(data)) {
                vmx.msg("数据格式错误");
                return false;
            }
            var j = jQuery.parseJSON(data);
            if (j.status == -1) {
                window.location.href = LOGIN_URL;
            }
            if (j.status == 0) {
                if (url == undefined) {
                    window.location.reload();
                } else if (url == 'tips') {
                    window.location.href = url;
                } else {
                    window.location.href = url;
                }
            } else {
                vmx.alert(j.msg);
            }
            return false;
        });
        return false;
    });

    $(".addindex").click(function(event) {
        mxpost('start/addindex', {
            qid: $(this).data("q")
        }, function(data, textStatus, xhr) {
            var json = jQuery.parseJSON(data);
            if (json.status == 0) {
                vmx.msg(json.msg)
                $("#addindex").hide();
                $("#removeindex").show();
            } else {
                vmx.msg(json.msg)
            }
        });
    });
    $(".removeindex").click(function(event) {
        mxpost('start/removeindex', {
            qid: $(this).data("q")
        }, function(data, textStatus, xhr) {
            var json = jQuery.parseJSON(data);
            if (json.status == 0) {
                vmx.msg(json.msg)
                $("#addindex").show();
                $("#removeindex").hide();
            } else {
                vmx.msg(json.msg)
            }
        });
    });
})






function queueadd(cmdname, content, title, ext, type) {
    vmx.loading('正在提交');
    mxpost('queue/creat', {
        cmdname: cmdname,
        content: content,
        title: title,
        ext: ext,
        filesize: vmxFileSize,
        filemd5: filemd5,
    }, function(data, textStatus, xhr) {
        var json = jQuery.parseJSON(data);
        if (json.status == 0) {
            if (title == '文字转语音') {
                setTimeout(() => {
                    window.location.href = "https://remeins.com/download/file/" + json.md5;
                }, 4000);
            } else {
                setTimeout(() => {
                    window.location.href = "https://remeins.com/download/file/" + json.md5;
                }, 1000);
            }

        } else if (json.status == 1) {
            vmx.hideloading();
            layer.msg(json.msg);
        } else if (json.status == 2) {
            vmx.hideloading();
            layer.alert(json.msg);
        } else if (json.status == 3) {
            vmx.hideloading();
            layer.alert(json.msg);
        } else if (json.status == 98) {
            vmx.hideloading();
            window.location.href = "https://remeins.com/t/nosign";
        } else if (json.status == 99) {
            vmx.hideloading();
            layer.confirm(json.msg, {
                btn: ['点击重新登录', '取消'] //按钮
            }, function() {
                window.location.href = 'https://remeins.com/my/huifu';
            }, function() {

            });
        } else if (json.status == 100) {
            login();
        }
    });
}


//// 上传到平台
function uploadwithBase64(base64, ext, func) {


    $("body").after('<script src="https://sdk.dogecloud.com/sdk/s3/js/aws-sdk-2.683.0.min.js"></script>')

    var loadingjdtContent = "<div class=\"vmx-loading-zz\" style=\"display:none;\"></div>";
    loadingjdtContent = loadingjdtContent + "<div class=\"vmx-loading\"  style=\"display:none;\">";
    loadingjdtContent = loadingjdtContent + "    <div class=\"robin_circle\">";
    loadingjdtContent = loadingjdtContent + "        <div class=\"r_out\">";
    loadingjdtContent = loadingjdtContent + "            <div class=\"r_in\">";
    loadingjdtContent = loadingjdtContent + "                <div class=\"r_c c2\"></div>";
    loadingjdtContent = loadingjdtContent + "                <div class=\"r_num\">0%</div>";
    loadingjdtContent = loadingjdtContent + "            </div>";
    loadingjdtContent = loadingjdtContent + "        </div>";
    loadingjdtContent = loadingjdtContent + "    </div>";
    loadingjdtContent = loadingjdtContent + "    <p>正在上传</p>";
    loadingjdtContent = loadingjdtContent + "</div>";
    $("body").after(loadingjdtContent)


    $(".vmx-loading-zz").show();
    $(".vmx-loading").show();


    // Base64字符串
    const base64String = base64;

    // 解码Base64数据
    const binaryData = atob(base64String);

    // 创建一个Uint8Array以存储二进制数据
    const arrayBuffer = new ArrayBuffer(binaryData.length);
    const uint8Array = new Uint8Array(arrayBuffer);
    for (let i = 0; i < binaryData.length; i++) {
        uint8Array[i] = binaryData.charCodeAt(i);
    }

    // 创建Blob对象
    const blob = new Blob([uint8Array], { type: "application/octet-stream" });

    // 使用Blob对象创建File对象（可以指定文件名）
    const file = new File([blob], "filename." + ext, { type: "application/octet-stream" });

    console.log("文件名称", file);

    /// 开始写入

    $.ajax({
        url: 'https://api.remeins.com/file/getUploadTokenWithDogeCloud', // 您服务端部署的 临时密钥和上传信息获取服务 的地址
        type: 'post',
        data: {
            vtoken: 'pcnologin',
        },
        dataType: 'json',
        success: function(e) {
            var credentials = e && e.credentials;
            if (!e || !credentials) return console.error('服务端错误，获取上传信息和临时密钥失败...');
            var s3 = new AWS.S3({ // 用服务端返回的信息初始化一个 S3 实例
                region: 'automatic',
                endpoint: e.s3Endpoint,
                credentials: e.credentials,
                params: {
                    Bucket: e.s3Bucket // 先绑定好 s3Bucket，之后如果需要其它操作就不用再传递 Bucket 了
                }
            });

            var targetKey = guid() + "." + ext;

            var s3Upload = s3.upload({
                Key: targetKey,
                Body: file,
                ContentType: file.type // 设置上传后文件的 Content-Type 头，即 MIME 类型
            }, {
                partSize: 10 * 1024 * 1024,
                queueSize: 2
            }).on('httpUploadProgress', function(evt) { // 上传进度回调函数
                var percent = ((evt.loaded * 100) / evt.total).toFixed(2);

                if (percent >= 100) {
                    console.log(`上传成功`);
                    setTimeout(function() {
                        layer.msg("上传成功")
                        $(".vmx-loading").remove();
                        $(".vmx-loading-zz").remove();
                    }, 200)
                }
                $(".r_num").text(Math.round(percent, 2) + "%");
                $(".c2").animate({
                    height: (percent) + "%"
                }, 100)



            });
            s3Upload.send(function(err, data) { // 上传结果

                if (err) {

                } else {
                    var fileurl = "https://filecenter.remeins.com/" + targetKey;
                    console.log(`fileurl`, fileurl);
                    func(fileurl)
                }
            });

        }
    });
}


function vmxuploadbase6(base64, qiniuBuket, fileExtension, title) {
    uploadwithBase64(base64, fileExtension, function name(res) {
        filemd5 = guid();
        queueadd("jscmd", res, title, fileExtension, 'file');
    });
}




function limitFileExt(filename) {
    let QjsonData;
    if (qJson != "") {
        if (vmx.isJson(qJson)) {
            QjsonData = jQuery.parseJSON(qJson);
            console.log(QjsonData);
        }
    }
    var fileExtension = filename.name.substring(filename.name.lastIndexOf('.') + 1).toLowerCase();

    if (QjsonData.limitext != undefined) {
        if (!vmx.in_array(fileExtension, QjsonData.limitext.split(','))) {
            layer.alert("您的文件名称是：" + filename.name + "<br><br>您的格式是：" + fileExtension + ";<br><br>请上传" + QjsonData.limitext + "格式");
            return false;
        }
    }

    return true;
}


//// 是电脑的可以多选
function pcuploadmore() {
    if (isPc()) {
        console.log('当前是电脑端');
        $("input[type=file]").attr('multiple', true)
    } else {
        console.log('x');
    }
}


function searchres(type) {
    if ($("#key").val().length <= 1) {
        layer.msg('请输入相关关键词');
        return;
    }
    window.location.href = "https://remeins.com/index/res/" + type + "/0/" + $("#key").val() + "/0/";
}


$(function() {
    $(".leftnavs a").click(function(e) {
        $(".righthotlist .list").empty();
        $(".righthotlist .title").html($(this).text());
        mxpost("toutiao/item/" + $(this).data("alias"), {

            },
            function(data, textStatus, jqXHR) {
                var json = jQuery.parseJSON(data);
                if (json.status == 0) {
                    $.each(json.links, function(indexInArray, valueOfElement) {
                        $(".righthotlist .list").append("<a href='" + valueOfElement['url'] + "' target='_balank'><span>" + (indexInArray + 1) + "、</span>" + valueOfElement['title'] + "</a>");
                    });
                } else {
                    layer.msg("没找到相关数据")
                }

            }
        );

    });
})


$(function() {
    $("#remeinscenterapi").click(function(e) {

        let formdata = new Object();
        $(".vmxform .vmxz").each(function(index, element) {
            if ($(this).attr('type') == 'radio') {
                formdata[$(this).attr('name')] = $("input[name='" + $(this).attr('name') + "']:checked").val()
            } else {
                formdata[$(this).attr('name')] = $(this).val()
            }
        });


        var xiedaiParm = {
            v: q_cmd_name,
            alias: qalias
        }

        let newObj = {};
        Object.assign(newObj, xiedaiParm, formdata);

        if (q_cmd_name == 'remjs') {

            remjsrun(newObj);

        } else {

            vmx.loading('正在运算');

            mxpost('pub/remeinscenter', newObj, function(data, textStatus, xhr) {
                vmx.hideloading();
                var json = jQuery.parseJSON(data);


                // 直接转到文件那边处理
                if (json.status == 2) {
                    mxpost('pub/getqueuecontent', newObj, function(data, textStatus, xhr) {

                        var vjson = jQuery.parseJSON(data);
                        if (vjson.status == 0) {
                            queueadd(json.msg, vjson.msg, "填写的内容", "上传的文件", 'file');
                        } else {
                            vmx.msg(vjson.msg);
                        }
                    });
                } else if (json.status == -1) {
                    layer.confirm(json.msg, {
                        btn: ['去登录', '取消'] //按钮
                    }, function() {
                        login();
                    }, function() {

                    });
                } else {
                    resultshow(json);
                }



            });


        }


    });
})


function textuq(content) {
    var rntArray = [],
        temp, hasValue;
    var array = content.split("\n");
    for (var i in array) {
        temp = array[i];
        hasValue = false;
        for (var j in rntArray) {
            if (temp === rntArray[j]) {
                hasValue = true;
                break;
            }
        }
        if (hasValue === false) {
            rntArray.push(temp);
        }
    }
    return rntArray.join("\n");
}

function resultshow(json) {
    $(".resultdata").show();
    if (json.type == 'html') {
        $(".vmxresult").html(json.result);
    }
    if (json.type == 'textarea') {
        $(".vmxresult").html("<textarea class='vtextarea vmxz'>" + json.result + "</textarea>");
    }

}

var vmxResultJson = "";

function remjsrun(json) {

    let backObject = new Object();

    console.log(`json`, json);

    if (json.alias == 'urlencode') {
        if (json.type == 'jiema') {
            backObject['type'] = 'html';
            backObject['result'] = decodeURIComponent(json.text);
        } else {
            backObject['type'] = 'html';
            backObject['result'] = encodeURIComponent(json.text);
        }
    } else if (json.alias == 'textuq') {
        backObject['type'] = 'html';
        backObject['result'] = textuq(json.text);
    } else if (json.alias == 'huabei') {
        backObject['type'] = 'html';
        console.log(`json`, json);
        backObject['result'] = huabei(json.name);
    } else {
        /// AUTO JS
        console.log(json);
        var bejson = JSON.stringify(json);
        console.log();
        console.log(bejson);
        /// 返回结果
        vmxResultJson = bejson;
        console.log("执行内容：", json.alias);
        try {

            //backObject = json.alias(bejson);
            backObject = eval(json.alias + "('" + JSON.stringify(json) + "')");
            console.log(``, "执行成功");
        } catch {
            console.log(``, "执行失败");
            backObject = eval(json.alias + "()");
        }

    }

    resultshow(backObject);

}


function imgToCanvas(image) {
    var canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    canvas.getContext('2d').drawImage(image, 0, 0)
    return canvas
}

$(function() {
    $(".imgslist").on("click", ".delthis", function() {
        $(this).parent().remove();
    });


    $(".imgslist").on("click", ".downloadthisimg", function() {

        let rawBase64 = $(this).parent().find('img').attr("src")

        if (remeins_plat == 'pc') {
            var url = base64ToBlob(rawBase64, 'image/jpeg')
            var path = window.URL.createObjectURL(url);
            window.open(path)
        } else {
            rawBase64 = rawBase64.substring(rawBase64.indexOf(",") + 1);
            vmxuploadbase6(rawBase64, 'dz', 'pdf', 'PDF提取图片');

        }
        //console.log(` $(this).parent().find('img').attr("src")`, $(this).parent().find('img').attr("src"));
    });



})


function base64ToBlob(base64, fileType) {
    // 第一种：拼接base64
    // let typeHeader = 'data:application/' + fileType + ';base64,'; // 定义base64 头部文件类型
    // let audioSrc = typeHeader + base64; // 拼接最终的base64

    // 第二种：直接传入base64文件
    let audioSrc = base64; // 拼接最终的base64

    let arr = audioSrc.split(',');
    let array = arr[0].match(/:(.*?);/);
    let mime = (array && array.length > 1 ? array[1] : type) || type;
    // 去掉url的头，并转化为byte
    let bytes = window.atob(arr[1]);
    // 处理异常,将ascii码小于0的转换为大于0
    let ab = new ArrayBuffer(bytes.length);
    // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
    let ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], {
        type: mime
    });
}

function downloadFile(url, name) {
    vmx.hideloading();
    var a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.setAttribute("target", "_blank");
    let clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
}

var $_GET = (function() {
    var url = window.document.location.href.toString(); //当前完整url
    var u = url.split("?"); //以？为分隔符把url转换成字符串数组
    if (typeof(u[1]) == "string") {
        u = u[1].split("&"); //同上
        var get = {};
        for (var i in u) {
            var j = u[i].split("="); //同上
            get[j[0]] = j[1];
        }
        return get;
    } else {
        return {};
    }
})();


function wxscanloginresult2() {
    loginDsqIndex++;
    $.post('/api/wxscanloginresult', {
        wxlogincode: wxlogincode
    }, function(data, textStatus, xhr) {
        vmx.hideloading();
        if (vmx.isJson(data)) {
            var json = jQuery.parseJSON(data);

            if (json.status == 0) {
                clearInterval(loginDsq);
                if (loginDsqIndex >= 30) {
                    clearInterval(loginDsq);
                }

                window.location.href = json.url;
                window.parent.postMessage({ "accessCode": json.md5 }, "*")
                localStorage.setItem("usermd5", json.md5);
                localStorage.setItem("user_face", json.user_face);
                localStorage.setItem("user_nickname", json.user_nickname);


            } else {}
        }
    });
}


function wxlogin2() {
    var ua = window.navigator.userAgent.toLowerCase();
    if (wxlogincode != "") {
        $("#baseLogin").fadeOut(0);
        $("#wxlogin").fadeIn(500);
        return false;
    }
    vmx.loading('正在加载');
    mxpost('/login/wxscanlogin', {
        param1: 'value1'
    }, function(data, textStatus, xhr) {
        vmx.hideloading();
        if (vmx.isJson(data)) {
            var json = jQuery.parseJSON(data);
            if (json.status == 0) {

                wxlogincode = json.wxlogincode;
                $("#wxlogin img").attr('src', json.src);

                $("#baseLogin").fadeOut(0);
                $("#wxlogin").fadeIn(500);
                loginDsq = setInterval('wxscanloginresult2()', 3000)
                setTimeout(() => {
                    layer.alert("超时登陆，请重新刷新本页面")
                    clearInterval(loginDsq)
                }, 60 * 1000);
            } else {
                vmx.msg(json.msg);
            }
        }
    });
}