// var userlisturl = 'http://61.177.28.246:8100/acc/ProductReport/GetUsers';
var isdebug = false;
var timestamp, time, nonce, sign, access_token;
var camera, imageFilter, trans, photoBrowser, FNPhotograph, userSelect, equipSelect;
var mostW = 800;
var mostH = 1200;

/**
 *对Date的扩展，将 Date 转化为指定格式的String
 *月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 *年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 *例子：
 *(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 *(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 */
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function fnReady() {

    fnReadyKeyback();
    fnReadyOpenWin();
    fnReadyOpenFrame();
    fnReadyHeader();
    fnReadyNav();
    fnReadyFooter();
};


function initRequire() {
    FNPhotograph = api.require('FNPhotograph');
    imageFilter = api.require('imageFilter');
    trans = api.require('trans');
    photoBrowser = api.require('photoBrowser');
    userSelect = api.require('UIListCheck');
    // equipSelect = api.require('zjCartList');
}

function fnReadyKeyback() {
    var keybacks = $api.domAll('.event-back');
    for (var i = 0; i < keybacks.length; i++) {
        $api.attr(keybacks[i], 'tapmode', 'highlight');
        keybacks[i].onclick = function () {
            // api.closeWin();
            // console.log('back');
            api.historyBack({}, function (ret, err) {
                if (!ret.status) {
                    // api.closeWin();
                    api.closeFrame();
                }
            });
        };


    }

    api.parseTapmode();
};

function fnReadyOpenWin() {
    var buttons = $api.domAll('.open-win');

    for (var i = 0; i < buttons.length; i++) {
        $api.attr(buttons[i], 'tapmode', 'highlight');
        buttons[i].onclick = function () {
            var target = $api.closest(event.target, '.open-win');
            var winName = $api.attr(target, 'win'),
                isNeedLogin = $api.attr(target, 'login'),
                param = $api.attr(target, 'param');

            if (isNeedLogin && !$api.getStorage('accessToken')) {
                winName = 'login';
            }

            if (param) {
                param = JSON.parse(param);
            }

            api.openWin({
                name: winName.replace('html/', ''),
                url: './' + winName + '.html',
                pageParam: param
            });

            // api.openTabLayout({
            //     name: winName.replace('html/', ''),
            //     url: './' + winName + '.html',
            //     pageParam: param,
            //     useWKWebView: true,
            //     bgColor: '#F1F6FD',
            //     navigationBar: {
            //         background: '#F1F6FD'
            //     }
            // });

        };
    }
    api.parseTapmode();
};

function fnReadyOpenFrame() {
    var buttons = $api.domAll('.open-frame');
    for (var i = 0; i < buttons.length; i++) {
        $api.attr(buttons[i], 'tapmode', 'highlight');
        buttons[i].onclick = function () {
            var target = $api.closest(event.target, '.open-frame');
            if (!target) {
                return;
            }
            var winName = $api.attr(target, 'frame');
            var param = $api.attr(target, 'param');
            // console.log('打开Frame:'+winName.replace('html/', ''));
            api.openFrame({
                name: winName.replace('html/', ''),
                url: './' + winName + '.html',
                pageParam: JSON.parse(param), //传json对象
                bounces: false,
                // bgColor: 'rgba(0,0,0,0)',
                bgColor: '#F1F6FD' //设置背景色
            });
            // loading('加载中...');

        };
    }
    api.parseTapmode();
};

var header, subheader, container, headerHeight = 0,
    subheaderHeight = 0;

function fnReadyHeader() {
    header = $api.byId('header');
    subheader = $api.byId('subheader');

    if (header) {
        $api.fixStatusBar(header);
        headerHeight = $api.offset(header).h;
    }
    if (subheader) {
        $('#subheader').css('top', headerHeight);
        subheaderHeight = $api.offset(subheader).h;

    }
    $('.container').css('margin-top', headerHeight + subheaderHeight + 10);
};

function fixLayout() {
    var headerHeight = $('#header').height();

    $('.container').css('margin-top', headerHeight + 10);
}
var nav, navHeight = 0;

function fnReadyNav() {
    nav = $api.byId('nav');
    if (nav) {
        navHeight = $api.offset(nav).h;
    }
};

var footer, footerHeight = 0;

function fnReadyFooter() {
    footer = $api.byId('footer');
    if (footer) {
        // $api.fixTabBar(footer)
        footerHeight = $api.offset(footer).h;
    }
    $('.container').css('margin-bottom', footerHeight);
    $('.lastcont').css('margin-bottom', footerHeight);
};

function fnReadyFrame() {
    var frameName = api.winName + '_frame';
    api.openFrame({
        name: frameName,
        url: './' + frameName + '.html',
        bounces: true,
        bgColor: '#f0f0f0',
        rect: {
            x: 0,
            y: headerHeight + navHeight,
            w: 'auto',
            h: api.winHeight - headerHeight - footerHeight - navHeight
        },
        pageParam: api.pageParam
    });
};

/**
 * 调用出自定义显示图标、内容和显示时间
 * @param {*} title 标题 提示信息
 * @param {*} time 提示时间 毫秒为单位
 * @param {*} iconfontUrl 图标
 */
function customToast(title, time, iconfontUrl) {
    // 使用aui弹窗
    var toast = new auiToast({});
    // 创建一个div设置遮罩的效果，添加aui遮罩的样式
    var tostdiv = document.createElement("div");
    tostdiv.classList.add("aui-mask");
    tostdiv.classList.add("aui-mask-in");
    document.body.appendChild(tostdiv);
    // 自定义弹窗的内容
    toast.custom({
        title: title,
        html: '<i class="aui-iconfont  aui-icon-info"></i>',
        duration: time,
    });
    // 设置弹窗和遮罩的显示时间
    setTimeout(function () {
        tostdiv.classList.remove("aui-mask");
        tostdiv.classList.remove("aui-mask-in");
        toast.hide();
    }, time);
}


/*
打开二维码扫描界面
使用方法: 在容器中添加以下内容
参数说明:
data-page       扫描成功后打开的页面名称
data-qr-title   扫描界面的标题
示例:
<div data-page="shangliaobaogong" data-qr-title="请刷AAA" onclick="openQRcode(this)" tapmod="">链接</div>
 */
function openQRcode(obj) {
    // console.log('xxxxxx');
    var page = $api.attr(obj, 'data-page');
    var selfpage = $api.attr(obj, 'data-self');

    setTimeout(function () {
        api.closeWin({
            name: 'inputcode'
        });
        if (selfpage) {
            api.closeWin({
                name: selfpage
            });
        }
    }, 500);


    // console.log('page: '+page);
    var qrtitle = $api.attr(obj, 'data-qr-title');
    var params = $api.attr(obj, 'data-params');
    api.execScript({
        name: 'root',
        script: 'fnOpenCustomQRCode("' + page + '","' + qrtitle + '","' + params + '");'
    });
}


function openQRcodetpm(obj) {
    var page = $api.attr(obj, 'data-page');
    // var selfpage = $api.attr(obj,'data-self');

    // setTimeout(function(){
    //     api.closeWin();
    //     // if (selfpage) {
    //     //     api.closeWin({name:selfpage});
    //     // }
    // },100);


    // console.log('page: '+page);
    var qrtitle = $api.attr(obj, 'data-qr-title');
    var params = $api.attr(obj, 'data-params');
    // console.log('xxxxxx');
    // console.log(qrtitle);
    // console.log(params);
    api.execScript({
        name: 'root',
        script: 'fnOpenTpmQRCode("' + page + '","' + qrtitle + '","' + params + '");'
    });
}

/*
加载下拉框选择
使用方法: getSelectOptions(url,"#userid");
参数说明:
url       数据接口地址
e         下拉框对象选择器
*/
function getSelectOptions(url, e) {
    // console.log(url);
    $.ajax({
        url: url,
        type: 'get',
        success: function (result) {
            console.log(JSON.stringify(result));
            var options = "";
            $.each(result.data, function (index, val) {
                options += " <option value='" + val.userID + "'>" + val.userName + "</option>"
            });
            $(e).html(options);
        },
        error: function (error) {
            console.log(error)
        }
    })
}

function getSelectOptions2(url, e, key, value, callback) {
    // console.log(url);
    $.ajax({
        url: url,
        type: 'get',
        success: function (result) {
            // console.log(JSON.stringify(result));
            var options = "";
            $.each(result.data, function (index, val) {
                options += " <option value='" + val[key] + "'>" + val[value] + "</option>"
            });
            $(e).html(options);
            return (typeof callback === 'function') && callback.call();
        },
        error: function (error) {
            console.log(JSON.stringify(error));
        }
    })
}

function random() {
    var min = 10000000;
    var max = 99999999;
    return Math.floor(Math.random() * (max - min)) + min;
}


function ajaxsetup(argument) {

    timestamp = Date.parse(new Date());
    time = timestamp;
    nonce = random();
    sign = hex_md5("timestamp=" + time + "&nonce=" + nonce);
    access_token = $api.getStorage('access_token');
    // console.log('time is : ' + time);
    // console.log('nonce is : ' + nonce);
    // console.log('sign is : ' + sign);
    // console.log('access_token is : ' + access_token);

    $.ajaxSetup({
        global: true,
        type: "POST",
        contentType: "application/json;charset=utf-8",
        timeout: 60000,
        dataType: 'json',
        async: true,
        xhrFields: {
            withCredentials: true
        },
        headers: {
            "token": access_token,
            "timestamp": time,
            "nonce": nonce,
            "sign": sign
        },
        crossDomain: true,
        statusCode: {
            403: function () { //未登录
                if (window.location.href.indexOf("/login.html") == -1) {
                    if (self != top) {
                        window.top.location.href = '/login.html';
                    } else {
                        window.location.href = '/login.html';
                    }
                }
                api.hideProgress();
            },
            311: function () {
                api.hideProgress();
                // layer.msg("未授权，请联系管理员");
            },
            404: function () {
                // layer.msg("请求路径错误");
                api.hideProgress();
            },
            500: function () {
                // layer.msg("服务器出了点问题");
                api.hideProgress();
            },
            503: function () {
                // layer.msg("服务器出了点问题");
                // window.location.href='/login.html';
                api.hideProgress();
            }
        },
        success: function (result) {
            api.hideProgress();
        },
        error: function (xhr, textStatus) {
            // api.toast({
            //     msg: '网络错误',
            //     duration: 20,
            //     location: 'bottom'
            // });
            // console.log(JSON.stringify(this.url));
            // console.log(JSON.stringify(xhr));
            // console.log(JSON.stringify(textStatus));
            // customToast('系统未知异常', 2000);

            api.hideProgress();
        },
        complete: function (XMLHttpRequest, status) {
            api.hideProgress();
            if (status == 'timeout') {
                // customToast('处理超时，请稍后再试！', 2000);　　　　
            }
        }
    });

}


// function fnGetLocation(callback) {
//     // var bmap = api.require('bMap');
//     // bmap.getLocation({
//     //     autoStop: true
//     // }, function(ret, err) {
//     //     // console.log(JSON.stringify(ret));
//     //     if (ret.status) {
//     //         // console.log(JSON.stringify(ret));
//     //         // customToast(JSON.stringify(ret), 2000);
//     //         $api.setStorage('LBS', ret);
//     //         api.sendEvent({
//     //             name: 'custom_lbs'
//     //         });
//     //     }
//     //
//     //     callback();
//     // });
// };

function closeWinBack() {
    // console.log('关闭窗口');
    api.closeFrame();
    api.closeFrame({ // 关闭扫描样式页
        name: 'qrcode'
    });
    api.closeFrame({ // 关闭扫描样式页
        name: 'tpmqrcode'
    });
    setTimeout(function () {
        api.closeWin({
            name: 'inputcode'
        });
    }, 500);
    api.closeWin();
}

function closeFrame() {
    // console.log('关闭窗口');
    api.closeFrame();
    // api.hideProgress();

}

function backToMain() {
    api.closeFrame();
    api.closeFrame({
        name: 'inputcode'
    });
}

function getHost(callback) {
    $.ajax({
        type: "GET",
        // url: "http://siger.rc3cr.com/hs.json",
        dataType: 'json',
        async: true,
        contentType: 'application/json',
        url: "https://cloud.siger-data.com/hs.json?timeout=" + new Date().getTime(),
        success: function (data) {
            // console.log(JSON.stringify(data));
            $api.setStorage('hs', data);
            return (typeof callback === 'function') && callback.call(this, data);
        },
        error: function (error) {
            // customToast(lang['9999999'], 2000);
            if ($api.getStorage('hs')) {
                return (typeof callback === 'function') && callback.call(this, $api.getStorage('hs'));
            } else {
                api.readFile({
                    path: api.wgtRootDir + '/res/hs.json'
                }, function (ret, err) {
                    if (ret) {
                        // console.log(eval(ret.data));
                        $api.setStorage('hs', eval(ret.data));
                        return (typeof callback === 'function') && callback.call(this, $api.getStorage('hs'));
                    } else {
                        alert(JSON.stringify(err));
                    }
                });
            }
        }
    });
}


function getRemoteConfig(callback) {
    $.ajax({
        type: "get",
        // url: "http://siger.rc3cr.com/appconfig.json",
        url: "http://61.177.28.246:8100/Files/appconfig.json",
        success: function (data) {
            // console.log(JSON.stringify(data));

            $api.setStorage('appconfig', data);
            // if (data.isdebug===1){console.log('调试状态');}else{console.log('非调试状态');}
            return (typeof callback === 'function') && callback.call(this, data);
        },
        error: function (error) {
            console.log(JSON.stringify(error));
            // customToast(lang['9999999'], 2000);
            if ($api.getStorage('appconfig')) {
                return (typeof callback === 'function') && callback.call(this, $api.getStorage('appconfig'));
            }
        }
    });
}

function getToken(callback) {

    var hosts = $api.getStorage('hs');
    if (!hosts) {
        customToast("没有加载公司", 2000);
    }

    // var client = '测试公司';
    // var client = $("input[name=client]").val();
    if (isWorkcode) {
        client = $("input[name=client1]").val();
    } else {
        client = $("input[name=client2]").val();
    }

    if (client) { } else {
        customToast("请输入公司名称", 2000);

    }

    $.each(hosts, function (index, val) {
        if (client == val.name) {
            host = val.url;
            // $api.setStorage('host', val.url);
        }
    });

    $.ajax({
        type: "GET",
        async: true,
        contentType: "application/json;charset=utf-8",
        dataType: 'json',
        url: host + "/config/token/get",
        success: function (data) {
            console.log(JSON.stringify(data))
            if (data.ret) {
                // $api.setStorage('host', host)
                $api.setStorage('access_token', data.data.toString());
                $api.setStorage('expire_in', new Date().getTime());

                return (typeof callback === 'function') && callback.call(this, data.data.toString());
            } else {
                customToast(lang(data.msg), 2000);
            }
        },
        error: function (data) {
            // console.log('网络错误：' + host + "/config/token/get");
            // customToast(lang('9999999'), 2000);
        },
        complete: function (result, textStatus) {
            // console.log('获得token3');
            // console.log(result);
        }
    });
}

function autologin() {

    getToken(function (token) {
        var post = {};
        // post.mobile = $("input[name=mobile]").val();
        // post.password = $("input[name=password]").val();
        // post.mobile = '17012345680';//生产人员
        post.mobile = '17012345687'; //维修人员
        // post.mobile = 'lida';
        post.password = '123456';
        $.ajax({
            url: host + "/config/login/login",
            type: 'POST',
            async: true,
            data: JSON.stringify(post),
            timeout: 60000,
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("token", token);
                xhr.setRequestHeader("timestamp", timestamp);
                xhr.setRequestHeader("nonce", nonce);
                xhr.setRequestHeader("sign", sign);
            },
            success: function (data, textStatus, jqXHR) {
                // console.log('登录成功');
                if (data.ret == 1) {

                    var key = CryptoJS.enc.Utf8.parse("asdfn*(&Hasfasf34fM(h&GBDe6df018");
                    var iv = CryptoJS.enc.Utf8.parse("1234567890000000"); //16位
                    var encryptedData = CryptoJS.AES.encrypt(post.mobile + ',' + hex_md5(post.password), key, {
                        iv: iv,
                        mode: CryptoJS.mode.ECB,
                        padding: CryptoJS.pad.Pkcs7
                    });


                    $.ajax({
                        type: "get",
                        url: host + "/config/ProjectUser/GetCurrentUserInfo",
                        contentType: "application/json;charset=utf-8",
                        async: false,
                        dataType: 'json',
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("token", token);
                            xhr.setRequestHeader("timestamp", timestamp);
                            xhr.setRequestHeader("nonce", nonce);
                            xhr.setRequestHeader("sign", sign);
                        },
                        success: function (res) {
                            // console.log(JSON.stringify(res));
                            $api.setStorage('current_user', JSON.stringify(res.data));
                        }

                    });

                    $api.setStorage('user_secret', encryptedData.ciphertext.toString());

                } else {
                    customToast(lang[data.msg], 2000);

                }
            },
            complete: function (result, textStatus) {
                // console.log(result);
            },
            error: function (result, textStatus) {
                // console.log(result);
            }

        });

    });


}

function genTPMFooterBtn(status, beijian_isSelect, callback) {

    var user = JSON.parse($api.getStorage('current_user'));

    switch (status) {
        case 1:
            if (user.sectiontype == 1) {
                $('#yjwx_btns').html('<div class="aui-btn aui-btn-block aui-btn-sm">' + lang('200032') + '</div>');
            } else if (user.sectiontype == 2) {
                $('#yjwx_btns').html('<div class="aui-btn aui-btn-info aui-btn-block aui-btn-sm btn_submit">' + lang('6660107') + '</div>');
            }
            break;
        case 2:
            if (user.sectiontype == 1) {
                $('#yjwx_btns').html('<div class="aui-btn aui-btn-block aui-btn-sm">' + lang('200033') + '</div>');
            } else if (user.sectiontype == 2) {
                $('#yjwx_btns').html('<div class="aui-btn aui-btn-info aui-btn-block aui-btn-sm btn_submit">' + lang('6660108') + '</div>');
            }
            break;
        case 3:
            //维修完成之前先选择备件
            if (beijian_isSelect == 1) {
                if (user.sectiontype == 1) {
                    $('#yjwx_btns').html('<div class="aui-btn  aui-btn-block aui-btn-sm">' + lang('8000001') + '</div>');
                } else if (user.sectiontype == 2) {
                    $('#yjwx_btns').html('<div class="aui-btn aui-btn-info aui-btn-block aui-btn-sm beijian_search">' + lang('8000002') + '</div>');
                }
            } //选择完成页面
            else if (beijian_isSelect == 2) {
                if (user.sectiontype == 1) {
                    $('#yjwx_btns').html('<div class="aui-btn  aui-btn-block aui-btn-sm">' + lang('8000003') + '</div>');
                } else if (user.sectiontype == 2) {
                    $('#yjwx_btns').html('<div class="aui-btn aui-btn-info aui-btn-block aui-btn-sm beijian_submit">' + lang('8000003') + '</div>');
                }
            } //跳转到维修完成页面
            else {
                if (user.sectiontype == 1) {
                    $('#yjwx_btns').html('<div class="aui-btn  aui-btn-block aui-btn-sm">' + lang('200034') + '</div>');
                } else if (user.sectiontype == 2) {
                    $('#yjwx_btns').html('<div class="aui-btn aui-btn-info aui-btn-block aui-btn-sm btn_submit">' + lang('6660109') + '</div>');
                }
            }

            break;
        case 4:
            if (user.sectiontype == 1) {
                var htmlcont = '';
                htmlcont += '<div class="aui-row">';
                htmlcont += '<div class="aui-col-xs-4 aui-padded-r-10">';
                htmlcont += '<div class="aui-btn aui-btn-danger aui-btn-block aui-btn-sm btn_submit" data-checkstatus="0">';
                htmlcont += lang('200089');
                htmlcont += '</div>';
                htmlcont += '</div>';
                htmlcont += '<div class="aui-col-xs-4 aui-padded-r-10">';
                htmlcont += '<div class="aui-btn aui-btn-warning aui-btn-block aui-btn-sm btn_submit" data-checkstatus="2">';
                htmlcont += lang('6660121');
                htmlcont += '</div>';
                htmlcont += '</div>';
                htmlcont += '<div class="aui-col-xs-4">';
                htmlcont += '<div class="aui-btn aui-btn-info aui-btn-block aui-btn-sm btn_submit" data-checkstatus="1">';
                htmlcont += lang('900343');
                htmlcont += '</div>';
                htmlcont += '</div>';
                htmlcont += '</div>';
                $('#yjwx_btns').html(htmlcont);
            } else if (user.sectiontype == 2) {
                $('#yjwx_btns').html('<div class="aui-btn aui-btn-block aui-btn-sm ">' + lang('200035') + '</div>');
            }
            break;
        case 5:
            if (user.sectiontype == 1) {
                $('#yjwx_btns').html('<div class="aui-btn  aui-btn-block aui-btn-sm">' + lang('900704') + '</div>');
            } else if (user.sectiontype == 2) {
                $('#yjwx_btns').html('<div class="aui-btn aui-btn-info aui-btn-block aui-btn-sm btn_openfankui">' + lang('6660110') + '</div>');
            }
            break;
        case 6:
            // if (user.sectiontype == 1) {
            //     $('#yjwx_btns').html('<div class="aui-btn  aui-btn-block aui-btn-sm btn_submit">' + lang('900704') + '</div>');
            // } else if (user.sectiontype == 2) {
            $('#yjwx_btns').html('<div class="aui-btn  aui-btn-block aui-btn-sm ">' + lang('6660035') + '</div>');
            // }
            break;
    }

    return (typeof callback === 'function') && callback.call();

}



function getQueryString(location, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

function closethisWin(argument) {
    api.closeFrame();
    api.historyBack({}, function (ret, err) {
        if (!ret.status) {
            api.closeWin();
            api.closeFrame();
        }
    });
}

function closethisWinReload(argument) {
    console.log(isfankui);
    if (isfankui == 1) {
        $(".maincontent").show();
        $(".subfankuiform").hide();
        $('#yjwx_btns').html('<div class="aui-btn aui-btn-info aui-btn-block aui-btn-sm btn_openfankui">' + lang('6660110') + '</div>');
        lisOpenFankui();
        isfankui = 0;
        return;

        // listen_submitfankui();
    }
    api.closeFrame();
    api.execScript({
        name: 'root',
        frameName: 'tpm_yjwx',
        script: 'reloadMe();'
    });
    api.historyBack({}, function (ret, err) {
        api.execScript({
            name: 'root',
            frameName: 'tpm_yjwx',
            script: 'reloadMe();'
        });
        if (!ret.status) {
            api.closeWin();
            api.closeFrame();
        }
    });
}
var maskText = function (text) {
    var test = lang[text];
    return test;

};


/*
 * 图片压缩
 * path：要压缩图片的路径
 */
function compress(path, callback) {
    api.showProgress({
        style: 'default',
        animationType: 'fade',
        title: lang('6660106'),
        text: lang('6660111'),
        modal: true
    });

    /*
     * 缩放比例
     * 获取图片的高、宽信息
     */
    imageFilter.getAttr({
        path: path
    }, function (ret, err) {

        var imgAttr = changeImg(ret.width, ret.height);
        var suffix = getSuffix(path);
        var tempFolder = "fs://temp/"
        var tempFileName = Math.floor(1000) + "." + suffix;

        imageFilter.compress({
            img: path,
            size: {
                w: imgAttr.width,
                h: imgAttr.height
            },
            save: {
                album: true,
                imgPath: tempFolder,
                imgName: tempFileName
            }
        }, function (ret, err) {
            api.hideProgress();
            if (ret) {
                api.showProgress({
                    style: 'default',
                    animationType: 'fade',
                    title: lang('6660106'),
                    text: lang('6660112'),
                    modal: true
                });
                convert2Base(tempFolder + tempFileName, callback);
            } else {
                alert(JSON.stringify(err));
            }
        });
    });
}

function convert2Base(photoPath, callback) {
    trans.decodeImgToBase64({
        imgPath: photoPath
    }, function (ret, err) {
        if (ret.status) {
            var Base64Data = ret.base64Str;
            return (typeof callback === 'function') && callback.call(this, Base64Data);

            // uploadimg(Base64Data);
        } else { }
    });
}

/*
 * 传入图片宽和高，如果宽度大于高度，并且宽度大于最大宽度，就以宽度为基准计算缩小比例
 * 返回值：json类型，缩放后的高、宽
 */
function changeImg(w, h) {
    var retW = 0;
    var retH = 0;
    if (w > h) {
        if (w > mostW) {
            var scaling = 1 - (w - mostW) / w;
            //计算缩小比例
            retW = w * scaling;
            retH = h * scaling;
        } else {
            retW = w;
            retH = h;
        }
    } else {
        if (h > mostH) {
            var scaling = 1 - (h - mostH) / h;
            //计算缩小比例
            retW = w * scaling;
            retH = h * scaling;
        } else {
            retW = w;
            retH = h;
        }
    }

    return {
        'width': retW,
        'height': retH
    };
}

function getSuffix(filePath) {
    var pos = filePath.lastIndexOf(".");
    return filePath.substring(pos + 1);
}

function fnOpenLightBox(imgarr) {
    // console.log(imgarr.split(","));
    photoBrowser.open({
        images: imgarr.split(","),
        activeIndex: 0,
        placeholderImg: 'widget://image/apicloud.png',
        bgColor: '#000'
    }, function (ret) {
        if (ret.eventType == 'click') {
            photoBrowser.close();
        }
        api.bringFrameToFront({
            from: 'TEST'
        });
    });
}

function fnOpenLightBoxThisCon(e) {
    var img = $(e).find('img').attr('src');
    // console.log(img);
    var imgarr = [img];
    photoBrowser.open({
        images: imgarr,
        activeIndex: 0,
        placeholderImg: 'widget://image/apicloud.png',
        bgColor: '#000'
    }, function (ret) {
        // console.log('xxxxxx');
        if (ret.eventType == 'click') {
            photoBrowser.close();
        }
        api.bringFrameToFront({
            from: 'TEST'
        });
    });
}

function GetFilename(url) {
    if (url) {
        return url.split('/').pop().split('?')[0];
    }
    return "";
}

var dateUtil = {
    // 获得当前日期,格式:yyyy-MM-dd
    getNow: function () {
        var date = new Date();
        var y = date.getFullYear();
        var m = addZero(date.getMonth() + 1); // 获取当前月份的日期
        var d = addZero(date.getDate());
        return y + "-" + m + "-" + d;
    },
    // 获得当前日期前X天的日期,格式:yyyy-MM-dd
    getBeforeDate: function (dayCount) {
        var date = new Date();
        date.setDate(date.getDate() - dayCount); //获取dayCount天前的日期
        var y = date.getFullYear();
        var m = addZero(date.getMonth() + 1);
        var d = addZero(date.getDate());
        return y + "-" + m + "-" + d;
    },
    // 获得当前日期后X天的日期,格式:yyyy-MM-dd
    getAfterDate: function (dayCount) {
        var date = new Date();
        date.setDate(date.getDate() + dayCount); //获取dayCount天后的日期
        var y = date.getFullYear();
        var m = addZero(date.getMonth() + 1);
        var d = (date.getDate());
        return y + "-" + m + "-" + d;
    },
    // 获得当前月,格式:yyyy-MM
    getNowMonth: function () {
        var date = new Date();
        date.setMonth(date.getMonth() + 1);
        var y, m;
        if (0 == date.getMonth()) {
            y = date.getFullYear() - 1;
            m = 12;
        } else {
            y = date.getFullYear();
            m = addZero(date.getMonth());
        }
        return y + "-" + m;
    },
    // 获得当前月前X月的年月,格式:yyyy-MM
    getBeforeMonth: function (monthCount) {
        var date = new Date();
        date.setMonth(date.getMonth() + 1 - monthCount); //获取dayCount天前的月
        var y, m;
        if (0 == date.getMonth()) {
            y = date.getFullYear() - 1;
            m = 12;
        } else {
            y = date.getFullYear();
            m = addZero(date.getMonth());
        }
        return y + "-" + m;
    },
    // 获得当前月后X月的年月,格式:yyyy-MM
    getAfterMonth: function (monthCount) {
        var date = new Date();
        date.setMonth(date.getMonth() + 1 + monthCount); //获取dayCount天后的日期
        var y, m;
        if (0 == date.getMonth()) {
            y = date.getFullYear() - 1;
            m = 12;
        } else {
            y = date.getFullYear();
            m = addZero(date.getMonth());
        }
        return y + "-" + m;
    },
    daysDiff: function (dt1, dt2) {
        return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) - Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate())) / (1000 * 60 * 60 * 24));
    }
};

function addZero(number) {
    if (number < 10) {
        number = '0' + number;
    }
    return number;
}

function loading(txt) {
    api.showProgress({
        style: 'default',
        animationType: 'fade',
        title: '请稍后...',
        text: txt,
        modal: false
    });
}

function closeThisFrame() {
    api.closeFrame();
}

function maskTime(time) {
    var timetxt = "";
    if (time == 0) {
        timetxt = "";
    } else if (time > 0 && time < 60) {
        timetxt = lang('6660042') + time + lang('200028');
    } else if (time >= 60 && time < 1440) {
        timetxt = lang('6660042') + Math.round(time / 60) + lang('1102');
    } else if (time >= 4320 && time < 10080) {
        timetxt = lang('6660042') + Math.round(time / 1440) + lang('1101');
    } else if (time >= 10080 && time < 43200) {
        timetxt = lang('6660042') + Math.round(time / 10080) + lang('1136');
    } else if (time >= 43200 && time < 525600) {
        timetxt = lang('6660042') + Math.round(time / 43200) + lang('1138');
    } else if (time >= 525600) {
        timetxt = lang('6660042') + Math.round(time / 525600) + lang('1142');
    }

    return timetxt;
}

function maskTime3(datestr) {
    console.log(datestr);
    var timetxt = "";
    var dt = datestr.split(' ')[0];
    var date = new Date();
    var dd = datestr.toDate("yyyy-mm-dd hh:ii:ss");
    var diff = dateUtil.daysDiff(dd, date);
    if (dt == dateUtil.getNow()) {
        timetxt = datestr.split(' ')[1];
    } else if (diff == 1) {
        timetxt = lang('900390');
    } else if (diff == 2) {
        timetxt = lang('6660037');
    } else if (diff > 2 && diff <= 7) {
        timetxt = diff + lang('6660038');
    } else if (diff > 7 && diff <= 30) {
        timetxt = Math.round(diff / 7) + lang('6660039');
    } else if (diff > 30 && diff <= 365) {
        timetxt = Math.round(diff / 30) + lang('6660040');
    } else if (diff > 365) {
        timetxt = Math.round(diff / 365) + lang('6660041');
    }
    console.log(timetxt);
    return timetxt;
}


function maskTime2(days) {
    var timetxt = "";
    if (days == 0) {
        timetxt = "";
    } else if (days > 0 && days < 30) {
        timetxt = lang('6660036') + days + lang('1101');
    } else if (days >= 7 && days < 30) {
        timetxt = lang('6660036') + Math.round(days / 7) + lang('1136');
    } else if (days >= 30 && days < 365) {
        timetxt = lang('6660036') + Math.round(days / 30) + lang('1138');
    } else if (days >= 365) {
        timetxt = lang('6660036') + Math.round(days / 365) + lang('1142');
    }

    return timetxt;
}

function maskPhoto(pstr) {
    var html = "";
    // console.log(pstr);
    if (pstr && pstr.length > 0) {
        var photoarr = pstr.split(",");

        $.each(photoarr, function (index, val) {
            html += '<div class="imgthumb"> <div class="photo-badge deletephoto" data-value="' + val + '">x</div> <div class="imgin"><img src="' + val + '" style="width:100%;height:100%;"></div> </div>';
        });
        // console.log(html);
    }
    return html;
}

function maskEquip(estr) {
    var timetxt = "";
    var htmlstr = "";
    if (estr && estr.length > 0) {
        var estrarr = estr.split(",");


        $.each(estrarr, function (index, val) {
            // htmlstr += '<div class="imgthumb"> <div class="photo-badge deletephoto" data-value="'+val+'">x</div> <div class="imgin"><img src="'+val+'" style="width:100%;height:100%;"></div> </div>';
            htmlstr += ' <div class="tag"><div class="m-badge deleteuser">x</div>' + val + '</div>';
        });
        // console.log(htmlstr);
    }
    return htmlstr;
}
String.prototype.myReplace = function (f, e) { //吧f替换成e
    var reg = new RegExp(f, "g"); //创建正则RegExp对象
    return this.replace(reg, e);
}



String.prototype.toDate = function (format) {
    var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
    var normalizedFormat = format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
    var formatItems = normalizedFormat.split('-');
    var dateItems = normalized.split('-');

    var monthIndex = formatItems.indexOf("mm");
    var dayIndex = formatItems.indexOf("dd");
    var yearIndex = formatItems.indexOf("yyyy");
    var hourIndex = formatItems.indexOf("hh");
    var minutesIndex = formatItems.indexOf("ii");
    var secondsIndex = formatItems.indexOf("ss");

    var today = new Date();

    var year = yearIndex > -1 ? dateItems[yearIndex] : today.getFullYear();
    var month = monthIndex > -1 ? dateItems[monthIndex] - 1 : today.getMonth() - 1;
    var day = dayIndex > -1 ? dateItems[dayIndex] : today.getDate();

    var hour = hourIndex > -1 ? dateItems[hourIndex] : today.getHours();
    var minute = minutesIndex > -1 ? dateItems[minutesIndex] : today.getMinutes();
    var second = secondsIndex > -1 ? dateItems[secondsIndex] : today.getSeconds();

    return new Date(year, month, day, hour, minute, second);
};
String.prototype.replaceAll = function (FindText, RepText) {
    regExp = new RegExp(FindText, "g");
    return this.replace(regExp, RepText);
}

function getWmsPandianStatus(pstatus) {
    if ('1' == pstatus) {
        return '待审核';
    } else if ('2' == pstatus) {
        return '待盘点';
    } else if ('3' == pstatus) {
        return '盘点中';
    } else if ('4' == pstatus) {
        return '盘点完成';
    } else {
        return '';
    }
}

function sleepcom(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}

function initProductLevels() {
    var ttllevels = $api.getStorage('levelname');
    if (!ttllevels) {
        getProductLevel();
    }
    // ttllevels = $api.getStorage('levelname');
    // var toplevels = $api.getStorage('toplevels');
    // if (!toplevels && ttllevels) {
    //     getLevelByid(ttllevels[0]['id']);
    // }
    // alert(JSON.stringify($api.getStorage('levelname')));
    // alert(JSON.stringify($api.getStorage('toplevels')));
}

function getProductLevel() {
    $.ajax({
        url: host + '/config/UserLevel/getCurrentUserProjectLevel',
        //  data:JSON.stringify({
        //     "machineCode":qrcode
        // }),
        type: 'GET',
        success: function (result) {
            // console.log(JSON.stringify(result));
            if (result.ret == 1) {
                // alert(result.data[0]['id']);
                $api.setStorage('levelname', result.data);
                getLevelByid(result.data[0]['id'])
                // console.log(JSON.stringify($api.getStorage('levelname')));
            }
        },
        error: function (error) {
            console.log(JSON.stringify(error));
            // customToast(lang['9999999'], 2000);
        }
    })
}

function getLevelChildren(plevelid) {
    $.ajax({
        url: host + '/config/UserLevel/getLevelChildrenById?id=' + plevelid,
        //  data:JSON.stringify({
        //     "machineCode":qrcode
        // }),
        type: 'GET',
        success: function (result) {
            // console.log(JSON.stringify(result));
            if (result.ret == 1) { } else {
                // customToast(lang[result.msg], 2000);
            }
        },
        error: function (error) {
            console.log(JSON.stringify(error));
            // customToast(lang['9999999'], 2000);
        }
    })
}

function getLevelByid(plevelid) {
    $.ajax({
        url: host + '/config/UserLevel/getLevelById?id=' + plevelid,
        //  data:JSON.stringify({
        //     "machineCode":qrcode
        // }),
        type: 'GET',
        success: function (result) {
            // console.log(JSON.stringify(result));
            if (result.ret == 1) {
                // getLevelChildren(result.data[0]['id']);
                $api.setStorage('toplevels', result.data);
                doDevstsFiltInit();
                // console.log(JSON.stringify($api.getStorage('toplevels')));
            } else {
                // customToast(lang[result.msg], 2000);
            }
        },
        error: function (error) {
            console.log(JSON.stringify(error));
            // customToast(lang['9999999'], 2000);
        }
    })
}

function getTimePeriodInfo(pperiodType) {
    {
        // 近7天
        if (pperiodType == '1') {
            var currday = new Date();
            var endday = currday.format("yyyy-MM-dd");
            currday.setDate(currday.getDate() - 6);
            var startday = currday.format("yyyy-MM-dd");
            return startday + '|' + endday;
        }
        // 今天
        if (pperiodType == '2') {
            var currday = new Date();
            var endday = currday.format("yyyy-MM-dd");
            var startday = currday.format("yyyy-MM-dd");
            return startday + '|' + endday;
        }
        // 近7周
        if (pperiodType == '3') {
            var currday = new Date();
            var endday = currday.format("yyyy-MM-dd");
            currday.setDate(currday.getDate() - 48);
            var startday = currday.format("yyyy-MM-dd");
            return startday + '|' + endday;
        }
        // 近14天
        if (pperiodType == '5') {
            var currday = new Date();
            var endday = currday.format("yyyy-MM-dd");
            currday.setDate(currday.getDate() - 13);
            var startday = currday.format("yyyy-MM-dd");
            return startday + '|' + endday;
        }
        // 本月
        if (pperiodType == '6') {
            var currday = new Date();
            var endday = currday.format("yyyy-MM-dd");
            var startday = endday.substring(0, endday.length - 2) + '01';
            return startday + '|' + endday;
        }
    }
}

var maxlevelcnt;
var comlevelconts;

function doDevstsFiltInit() {
    comlevelconts = [];
    maxlevelcnt = $api.getStorage('levelname').length;
    initLevelsOptions($api.getStorage('toplevels')[0]['id'], $api.getStorage('toplevels')[0]['title']);
}

function initLevelsOptions(plevelid, pnamedisped) {
    var srchobj = plevelid;
    var srchobjlent = 1;
    try {
        var levelarrs = plevelid.split('-');
        srchobj = levelarrs[levelarrs.length - 1];
        srchobjlent = levelarrs.length;
    } catch (e) {

    }

    $.ajax({
        url: host + '/config/UserLevel/getLevelChildrenById?id=' + srchobj,
        //  data:JSON.stringify({
        //     "machineCode":qrcode
        // }),
        type: 'GET',
        success: function (result) {
            // console.log(JSON.stringify(result));
            if (result.ret == 1) {
                if (result.data.length > 0) {
                    for (var i = 0; i < result.data.length; i++) {
                        if (srchobjlent < maxlevelcnt - 2) {
                            initLevelsOptions(plevelid + '-' + result.data[i]['id'], pnamedisped + '-' + result.data[i]['title']);
                        } else {
                            var tempobst = {};
                            tempobst.code = plevelid + '-' + result.data[i]['id'];
                            tempobst.name = pnamedisped + '-' + result.data[i]['title'];
                            comlevelconts.push(tempobst);
                            $api.setStorage('statusFiltsObjs', comlevelconts);
                        }
                    }
                } else {
                    var tempobst = {};
                    tempobst.code = plevelid;
                    tempobst.name = pnamedisped;
                    comlevelconts.push(tempobst);
                    $api.setStorage('statusFiltsObjs', comlevelconts);
                }
            } else {
                // customToast(lang[result.msg], 2000);
            }
        },
        error: function (error) {
            console.log(JSON.stringify(error));
            // customToast(lang['9999999'], 2000);
        }
    })
}


function getDevStatusDisp(pstatus) {
    // 0关机 1运行 2调试 3空闲 4故障 5换线调试
    if ('0' == pstatus) {
        return '关机';
    } else if ('1' == pstatus) {
        return '运行';
    } else if ('2' == pstatus) {
        return '调试';
    } else if ('3' == pstatus) {
        return '空闲';
    } else if ('4' == pstatus) {
        return '故障';
    } else if ('5' == pstatus) {
        return '换线调试';
    } else {
        return '';
    }
}

function addZero(pval) {
    if (!pval) {
        return '00';
    } else if (pval > 9) {
        return pval;
    } else {
        return '0' + pval;
    }

}

function emptyStorage() {
    $api.setStorage('project_name', '');
    $api.setStorage('current_user', '');
    $api.setStorage('user_secret', '');
    $api.setStorage('MachineCode', '');
    $api.setStorage('host', '');
    $api.setStorage('access_token', '');
    $api.setStorage('expire_in', '');
    $api.setStorage('levelname', '');
    $api.setStorage('toplevels', '');
    $api.setStorage('oeefiltoptins', '');
    $api.setStorage('statusFiltsObjs', '');
    $api.setStorage('pageSrchopts', '');
    $api.setStorage('stsstatfiltoptins', '');
    $api.setStorage('yieldfiltoptins', '');
    $api.setStorage('alarmfiltoptins', '');
    $api.setStorage('projectmodules', '');
    $api.setStorage('sectionInfo', '');
    $api.setStorage('userInfo', '');
}

function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return Y + M + D + h + m + s;
}


//获取时间到分钟
function timestampToDate(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return Y + M + D;
}

function adRefreashEvent() {
    api.sendEvent({
        name: 'dogdstssrerch'
    });
    api.sendEvent({
        name: 'sdfdoycclylrefreash'
    });
    api.sendEvent({
        name: 'refjtndgfdhhffad'
    });
    api.sendEvent({
        name: 'djaghaalngaan'
    });
}

// 安灯状态
function andonStatus(status) {
    var str = "";
    switch (status) {
        case 0:
            str = "正常";
            break;
        case 1:
            str = "异常预警";
            break;
        case 2:
            str = "待签到";
            break;
        case 3:
            str = "处理中";
            break;
        case 4:
            str = "待确认";
            break;
        default:
            str = "关闭";
            break;
    }
    return str;
}
//根据秒求天小时分钟
function showTimeStr(val) {
    if (val < 60) {
        return val + lang('1104'); //秒
    } else {
        var min_total = Math.floor(val / 60); // 分钟
        var sec = Math.floor(val % 60); // 余秒
        var sec_str = sec == 0 ? "" : sec + lang('1104');
        if (min_total < 60) {
            return min_total + lang('1103') + sec_str;
        } else {
            var hour_total = Math.floor(min_total / 60); // 小时数
            var min = Math.floor(min_total % 60); // 余分钟
            var min_str = min == 0 ? "" : min + lang('1103');
            if (hour_total < 24) {
                return hour_total + lang('1102') + min_str + sec_str;
            } else {
                var day_total = Math.floor(hour_total / 24); // 天数
                var hour = Math.floor(hour_total % 24); //余小时
                var hour_str = hour == 0 ? "" : hour + lang('1102');
                return day_total + lang('1101') + hour_str + min_str + sec_str;
            }

        }
    }
}

//精确到分钟
function showTimeStrToMinute(val) {
    if (val < 60) {
        return 0 + lang('200028')
    } else {
        var min_total = Math.floor(val / 60) // 分钟
        if (min_total < 60) {
            return min_total + lang('200028')
        } else {
            var hour_total = Math.floor(min_total / 60) // 小时数
            var min = Math.floor(min_total % 60) // 余分钟
            var min_str = min == 0 ? '' : min + lang('200028')
            if (hour_total < 24) {
                return hour_total + lang('1102') + min_str
            } else {
                var day_total = Math.floor(hour_total / 24) // 天数
                var hour = Math.floor(hour_total % 24) // 余小时
                var hour_str = hour == 0 ? '' : hour + lang('1102')
                return day_total + lang('1101') + hour_str + min_str
            }
        }
    }
}

//强制显示两位小数
function getStyleNum(num) {
    if (num < 0) {
        num = 0;
    }
    if (num > 100) {
        num = 100;
    }
    let value_str = num
    value_str = (value_str + '').split('.');
    if (value_str.length < 2) {
        value_str.push('00')
    }
    // num = value_str[0] + '.' + (value_str[1] + '00').slice(0, 2);
    num = value_str[0] + '.' + (value_str[1] + '0').slice(0, 1);
    return num;
}

//强制显示两位小数
function getStyleNumMax(num) {
    if (num < 0) {
        num = 0;
    }
    // if(num > 100){
    //   num = 100;
    // }
    let value_str = num
    value_str = (value_str + '').split('.');
    if (value_str.length < 2) {
        value_str.push('00')
    }
    // num = value_str[0] + '.' + (value_str[1] + '00').slice(0, 2);
    num = value_str[0] + '.' + (value_str[1] + '0').slice(0, 1);
    return num;
}

function reportStorage(obj = {}) {
    localStorage.setItem('reportobj', JSON.stringify(obj));
}
