/**
 * 工具组件 对原有的工具进行封装，自定义某方法统一处理
 *
 * @author lefan 2014-12-12
 * @Email: 124972225@qq.com
 * @version 1.00
 */

var screenHeight = document.documentElement.clientHeight;
var screenWidth = document.documentElement.clientWidth;
var gridwidth = 0;
var gridheight = 0;
var otpTypeEnum = {
    ADD: 0,
    EDIT: 1,
    COPY: 2
};

var eSignBusinessTypeCodeEnum = {
    //合同
    CONTRACT: 'contract',
    //对账单
    ACCOUNT_STATEMENT: 'account_statement',
    COST_ACCOUNT_STATEMENT: 'cost_account_statement',
    COMPANY_ACCOUNT_STATEMENT: 'company_account_statement',
    //采购订单
    PURCHASE_ORDER: 'purchase_order',
    DELIVERY_ORDER: 'delivery_order',
    OVERSEAS_DELIVERY_ORDER: 'overseas_delivery_order',
    CUSTOMS_DECLARATION: 'customs_declaration',
    PAYMENT_MATCHING: 'payment_matching',
    COST_MATCHING: 'cost_matching',
    //购销合同
    PURCHASE_SALE_CONTRACT :'purchase_sale_contract',
    PURCHASE_SALE_PROCESS_CONTRACT :'purchase_sale_process_contract'
};

var columnSortCodeEnum = {
    //定价详情
    FIX_DETAIL: 'fixDetail',
    BID_DETAIL: 'bidDetail',
    //物料凭证列表
    RECEIVE: 'receive',
    ACCOUNT_STATEMENT_SUP: 'account_statement_sup',
    COST_ACCOUNT_STATEMENT_SUP: 'cost_account_statement_sup',
    DEDUCTION: 'deduction',
    PURCHASE_ORDER: 'purchase_order',
    PURCHASE_ORDER_DETAIL: 'purchase_order_detail',
};
(function () {
    Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
        places = !isNaN(places = Math.abs(places)) ? places : 2;
        symbol = symbol !== undefined ? symbol : "$";
        thousand = thousand || ",";
        decimal = decimal || ".";
        var number = this,
            negative = number < 0 ? "-" : "",
            i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
            j = (j = i.length) > 3 ? j % 3 : 0;
        return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    };
    if (screenWidth < 760) {
        gridwidth = screenWidth;
        gridheight = screenHeight - 30;
    } else {
        gridwidth = screenWidth - 20;
        gridheight = screenHeight - 100;
    }
    ly = {};
    ly.ajax = (function (params) {
        var pp = {
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.open({
                    type: 1,
                    title: "出错啦！",
                    area: ['95%', '95%'],
                    content: "<div id='layerError' style='color:red'>" + XMLHttpRequest.responseText + "</div>"
                });
            }
        };
        $.extend(pp, params);
        $.ajax(pp);
    });
    ly.ajaxSubmit = (function (form, params) {// form 表单ID. params ajax参数
        var pp = {
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.open({
                    type: 1,
                    title: "出错啦！",
                    area: ['95%', '95%'],
                    content: "<div id='layerError' style='color:red'>" + XMLHttpRequest.responseText + "</div>"
                });
            }
        };
        $.extend(pp, params);
        $(form).ajaxSubmit(pp);
    });
    CommnUtil = {
        /**
         * ajax同步请求 返回一个html内容 dataType=html. 默认为html格式 如果想返回json.
         * CommnUtil.ajax(url, data,"json")
         *
         */
        ajax: function (url, data, dataType) {
            if (!CommnUtil.notNull(dataType)) {
                dataType = "html";
            }
            var html = '没有结果!';
            // 所以AJAX都必须使用ly.ajax..这里经过再次封装,统一处理..同时继承ajax所有属性
            if (url.indexOf("?") > -1) {
                url = url + "&_t=" + new Date();
            } else {
                url = url + "?_t=" + new Date();
            }
            ly.ajax({
                type: "post",
                data: data,
                url: url,
                dataType: dataType,// 这里的dataType就是返回回来的数据格式了html,xml,json
                async: false,
                cache: false,// 设置是否缓存，默认设置成为true，当需要每次刷新都需要执行数据库操作的话，需要设置成为false
                success: function (data) {
                    html = data;
                }
            });
            return html;
        },
        /**
         * 判断某对象不为空..返回true 否则 false
         */
        notNull: function (obj) {
            if (obj === null) {
                return false;
            } else if (obj === undefined) {
                return false;
            } else if (obj === "undefined") {
                return false;
            } else if (obj === "") {
                return false;
            } else if (obj === "[]") {
                return false;
            } else if (obj === "{}") {
                return false;
            } else {
                return true;
            }

        },

        /**
         * 判断某对象不为空..返回obj 否则 ""
         */
        notEmpty: function (obj) {
            if (obj === null) {
                return "";
            } else if (obj === undefined) {
                return "";
            } else if (obj === "undefined") {
                return "";
            } else if (obj === "") {
                return "";
            } else if (obj === "[]") {
                return "";
            } else if (obj === "{}") {
                return "";
            } else {
                return obj;
            }

        },
        loadingImg: function () {
            var html = '<div class="alert alert-warning">' + '<button type="button" class="close" data-dismiss="alert">' + '<i class="ace-icon fa fa-times"></i></button><div style="text-align:center">' + '<img src="' + rootPath + '/images/loading.gif"/><div>' + '</div>';
            return html;
        },
        /**
         * html标签转义
         */
        htmlspecialchars: function (str) {
            var s = "";
            if (str.length == 0)
                return "";
            for (var i = 0; i < str.length; i++) {
                switch (str.substr(i, 1)) {
                    case "<":
                        s += "&lt;";
                        break;
                    case ">":
                        s += "&gt;";
                        break;
                    case "&":
                        s += "&amp;";
                        break;
                    case " ":
                        if (str.substr(i + 1, 1) == " ") {
                            s += " &nbsp;";
                            i++;
                        } else
                            s += " ";
                        break;
                    case "\"":
                        s += "&quot;";
                        break;
                    case "\n":
                        s += "";
                        break;
                    default:
                        s += str.substr(i, 1);
                        break;
                }
            }
        },
        /**
         * in_array判断一个值是否在数组中
         */
        in_array: function (array, string) {
            for (var s = 0; s < array.length; s++) {
                thisEntry = array[s].toString();
                if (thisEntry == string) {
                    return true;
                }
            }
            return false;
        }
    };
})();
// 表单json格式化方法……不使用&拼接
(function ($) {
    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        $(array).each(function () {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };
    Date.prototype.format = function (format) {
        var o = {
            "M+": this.getMonth() + 1, // month
            "d+": this.getDate(), // day
            "h+": this.getHours(), // hour
            "m+": this.getMinutes(), // minute
            "s+": this.getSeconds(), // second
            "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
            "S": this.getMilliseconds()
            // millisecond
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }
})(jQuery);

/**
 * 调用此方法，在当前页面的datagrid上启用按钮授权控制
 *
 * @param resKey 传入菜单资源的唯一resKey
 */
function displayButtonByUserRole(resKey) {
    $("div.datagrid-toolbar a").each(function (index, item) {
        $(item).parent().next().find('div').css('display', 'none');
        $(item).hide();
    });
    var storedData = localStorage.getItem("btn");
    var btnMap = JSON.parse(storedData);
    if (btnMap[resKey]) {
        $("div.datagrid-toolbar a").each(function (index, item) {
            var _this = $(item);
            var bid = _this.attr("id");
            if (btnMap[resKey].indexOf(bid) != -1) {
                _this.show();
                $(item).parent().next().find('div').css('display', 'block');
            }
        });
    }
}


/**
 * 毫秒格式化
 *
 * @param value 时间戳
 * @return {string} 结果 yyyy-MM-dd
 */
function DateFormatMs(value) {
    if (!value) {
        return '';
    }
    var d = new Date(value);
    return d.format('yyyy-MM-dd');
}


/**
 * 毫秒格式化
 *
 * @param value 时间戳
 * @return {string} 结果 yyyy-MM-dd hh:mm:ss
 */
function DateTimeFormatMs(value) {
    if (!value) {
        return '';
    }
    var d = new Date(value);
    return d.format('yyyy-MM-dd hh:mm:ss');
}

/**
 * 公共查询参数返回方法
 */
function searchParams() {
    var params = {};
    $.each($("#searchForm").serializeArray(), function (index, item) {
        console.log(item)
        if (params[item.name] != undefined) {
            params[item.name] = (params[item.name] + ',' + item.value).trim();
        } else {
            params[item.name] = ('' + item.value).trim();
        }
    });
    return params;
}

/**
 * 公共查询参数返回方法变成 "name=John&age=25&city=New%20York"这种形式
 */
function searchQueryParams() {
    return $.param(searchParams())
}

/**
 * 公共查询方法
 */
function searchInfo() {
    // 原有的代码逻辑

    // 监听键盘事件

    $('#tb').datagrid('options').queryParams = searchParams();
    $('#tb').datagrid('load');
}

/**
 * 清空查询条件
 */
function resetSearch() {
    $('#searchForm').form("clear");
    $('input').not('[type="radio"]').val('');
    $('.Wdate').val('');
    $('.select2').val('0');
    //遍历所有select2重置
    $('.select2').each(function () {
        $(this).val(null).trigger("change");
    });
    $('#tb').datagrid('options').queryParams = $('#searchForm').serializeJson();
    $('#tb').datagrid('load');
}

$(function () {
    document.addEventListener("keydown", function (event) {
        if (event.key === 'Enter') {
            $("#search").click()
            $("#search_btn").click()
            $("#searchX").click()
            $("#btn").click()
        }
    })
})

/**
 * 查看更多查询条件
 */
function moreSearch() {
    // 获取表格高度
    let height = $('#tb').datagrid('options').height;
    $('.search-box.search-more .search-item:nth-of-type(n+4)').css('display', 'inline-block');
    $('.search-box .search-action-item').children("a:last").remove();
    $('.search-box .search-action-item').append('<a onclick=\'lessSearch(' + height + ')\' class="search-item-more"><i class="iconfont icons-arrowup"></i>收起</ a>');
    // 获取查询框高度
    let searchHeight = $('.search-box').height();
    // 获取差额高度
    let fixedHeight = searchHeight - 44;
    $('#tb').datagrid('resize', {height: height - fixedHeight});
}

/**
 * 隐藏更多查询条件
 */
function lessSearch(height) {
    $('.search-box.search-more .search-item:nth-of-type(n+4)').css('display', 'none');
    $('.search-box .search-action-item').children("a:last").remove();
    $('.search-box .search-action-item').append('<a onclick=\'moreSearch()\' class="search-item-more"><i class="iconfont icons-arrowdown"></i>展开更多</ a>');
    $('#tb').datagrid('resize', {height: height});
}

var topWin = (function (p, c) {
    while (p != c) {
        c = p;
        p = p.parent;
    }
    return c;
})(window.parent, window);

function openDialog(name, url, options) {
    var windowHeight = topWin.$(topWin).height();

    if (options.height === '100%') {
        options.height = windowHeight;
    } else if (options.height > windowHeight) {
        options.height = windowHeight;
    }

    var element = topWin.$('<div/>').appendTo(topWin.document.body);
    var content = '<iframe name="' + name + '" src="' + url + '" width="100%" height="100%" frameborder="0"></iframe>';
    $.extend(options, {
        content: content
    });
    return element.dialog(options);
}

/**
 * 调用方传入:
 *          列表的 url地址和fileIds二选一
 *          扩展的列,比如是否删除，文件类型等扩展列
 *          文件上传成功后的文件关联调用地址，例如:把文件id跟业务id关联的url,统一用post请求
 *          删除url,会增加文件id参数，
 *
 *        {
 *            listUrl:g.ctx+'pc/sys/aa?tenderId=1',//必传
 *            lookupFlag:0,//是否是查看，默认是0:否
 *            fileIds:,//必传
 *            extendedColumns:[
 *                {
 *                     field: 'status',
 *                     title: '状态',
 *                     width: 100,
 *                     formatter: function (data) {
 *                         if (data === '1')
 *                             return "正常";
 *                         else
 *                             return "删除";
 *                     }
 *                 }
 *            ],
 *             mapping: {'id':'fileId'},//映射，默认上传后直接把文件ID
 *            callBack:function(fileId){
 *
 *            },//必传
 *            removeUrl:g.ctx+'pc/sys/remove?tenderId=1'//ids=1,2,3   这个是列表的ids，如果是默认的列表就是文件的id，如果是自定义的列表就是业务数据的id
 *        }
 *
 */

function openFileUploadDialog(name, uploadOptions) {
    var dialog = {}
    var btns = [
        {
            text: itablei8n.save,
            handler: function () {
                topWin.frames[name].save(function (rows) {
                    var fileIds = []
                    $.each(rows, function (idx, itm) {
                        fileIds.push(itm.id);
                    });
                    uploadOptions.callBack(fileIds, rows)
                    dialog.dialog('close');
                });
            }
        },
        {
            text: itablei8n.close,
            handler: function () {
                dialog.dialog('close');
            }
        }
    ]
    if (uploadOptions.lookFlag != undefined && uploadOptions.lookFlag == 1) {
        btns.shift()
    }

    var options = {
        title: uploadOptions.title,
        width: uploadOptions.width == undefined ? '630px' : uploadOptions.width,
        height: uploadOptions.height == undefined ? '800px' : uploadOptions.height,
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dialog.dialog('destroy');
        },
        buttons: btns
    }
    if (uploadOptions['extendedColumns'] !== undefined) {
        // 自定义序列化函数，将函数转换为字符串
        const serializeColumns = uploadOptions['extendedColumns'].map(column => {
            if (typeof column.formatter === 'function') {
                return {
                    ...column,
                    formatter: column.formatter.toString()
                };
            }
            return column;
        });
        uploadOptions['extendedColumns'] = serializeColumns
    }

    var url = g.ctx + "pc/sys/file/fileUpload?optionKey=" + name
    localStorage.setItem(name, JSON.stringify(uploadOptions));
    dialog = openDialog(name, url, options)

}


/**
 * e签宝一步发起弹窗
 * @param options
 */
function openSignDialog(name, options) {
    //标题
    let title = options.title;
    //业务类型编码
    let businessTypeCode = options.businessTypeCode;
    //业务唯一id
    let businessId = options.businessId;
    //甲方
    let firstParty = options.firstParty;
    let firstPartyUserId = options.firstPartyUserId;
    //甲方名称
    let firstPartyName = options.firstPartyName;
    //乙方
    let secondParty = options.secondParty;
    //乙方名称
    let secondPartyName = options.secondPartyName;
    //采购订单汇总打印标识
    let sumSignFlag = options.sumSignFlag;
    let summaryFileId =  options.summaryFileId;
    let attachmentType =  options.attachmentType;
    let url = g.ctx + "pc/sys/esign/dialog?businessTypeCode=" + businessTypeCode + '&businessId=' + businessId + '&title=' + title
        + '&firstParty=' + firstParty + '&firstPartyUserId=' + (firstPartyUserId?firstPartyUserId:'') + '&firstPartyName=' + firstPartyName
        + '&secondParty=' + secondParty + '&secondPartyName=' + secondPartyName+'&sumSignFlag=' + sumSignFlag+'&summaryFileId='+summaryFileId+'&attachmentType='+attachmentType
    let signDialog = openDialog(name, url, {
        title: '一步发起签署',
        width: '60%',
        height: '99%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            signDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '发起',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames[name].save(function () {
                        topWin.layer.msg('操作成功', {icon: 1});
                        options.callBack();
                        signDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    signDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * e签宝文件查看弹窗
 * @param options
 */
function openSignLookDialog(name, businessId, businessTypeCode) {
    var title = "签署文件查看";
    let url = g.ctx + "pc/sys/esign/fileLookDialog?businessId=" + businessId + '&businessTypeCode=' + businessTypeCode;
    //如果是采购订单查看窗口，则需要传所有选中的businessId
    if (businessTypeCode == 'purchase_order' && name == 'downEsignDialog') {
        title = "签署文件下载";
        url = g.ctx + "pc/sys/esign/fileLookDialogs?businessId=" + businessId + '&businessTypeCode=' + businessTypeCode;
    }

    let signDialog = openDialog(name, url, {
        title: title,
        width: '60%',
        height: '80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            signDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    signDialog.dialog('close');
                }
            }
        ]
    });
}

function openCommonFileDialog(name, options) {
    //业务类型编码
    let title = options.title;
    let businessTypeCode = options.businessTypeCode;
    //业务唯一id
    let businessId = options.businessId;
    let businessCode = options.businessCode;
    let url = g.ctx + "pc/sys/businessAttachment/fileUploadWithType?businessTypeCode=" + businessTypeCode + '&businessId=' + businessId+ '&businessCode=' + businessCode
    let signDialog = openDialog(name, url, {
        title: title,
        width: '70%',
        height: '80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            signDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '保存',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames[name].save(function () {
                        topWin.layer.msg('操作成功', {icon: 1});
                        options.callBack();
                        signDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    signDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 固定模板路径导入弹框(模板放前端excel目录)
 * @param path 模板目录路径
 * @param title 是弹框的标题
 * @param call 是导入成功后的回调函数(只回调附件)
 * @returns {*}
 */
function openImportExcelDialog(path, title, call) {
    var name = title + 'importExcelDialog';
    var importDialog = openDialog(name, g.ctx + 'pc/sys/file/importExcelData?path=' + path, {
            title: title,
            width: '550px',
            height: '450px',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                importDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: "导入",
                    handler: function () {
                        if (title && title === '供应商AVL清单导入') {
                            topWin.layer.load(0);
                        }
                        topWin.frames[name].callFile(function (file) {
                            call(file)
                        });
                    }
                },
                {
                    text: itablei8n.close,
                    handler: function () {
                        importDialog.dialog('close');
                    }
                }
            ]
        }
    );
    return importDialog
}

/**
 * 动态模板数据url导入弹框
 * @param url 动态模板数据url
 * @param query 查询参数对象
 * @param title 是弹框的标题
 * @param call 是导入成功后的回调函数(只回调附件)
 * @returns {*}
 */
function openQueryImportExcelDialog(url, query, title, call) {
    var name = title + 'importQueryExcelDialog';
    localStorage.setItem('queryImport' + btoa(url), JSON.stringify(query));
    var importDialog = openDialog(name, g.ctx + 'pc/sys/file/importQueryExcelData?url=' + url, {
            title: title,
            width: '550px',
            height: '450px',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                importDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: "导入",
                    handler: function () {
                        topWin.frames[name].callFile(function (file) {
                            call(file)
                        });
                    }
                },
                {
                    text: itablei8n.close,
                    handler: function () {
                        importDialog.dialog('close');
                    }
                }
            ]
        }
    );
    return importDialog
}

function tableSingleFileUpload(tbEl, fileBoxEl, accept, rowIndex, fileIdField, fileNameField) {
    console.log(arguments)
    const options = {
        onChange: function () {
            let formData = new FormData();
            var filebox = $('#' + fileBoxEl).filebox("files");
            if (filebox.length <= 0) {
                return
            }
            formData.append("file", filebox[0]);
            topWin.layer.load(0);
            $.ajax({
                    url: g.ctx + 'pc/sys/file/rest/upload/file', type: 'POST', data: formData, processData: false,// ⑧告诉jQuery不要去处理发送的数据
                    contentType: false,
                    success: function (obj) {
                        var row = {}
                        row[fileIdField] = obj.id
                        row[fileNameField] = obj.fileName
                        $("#" + tbEl).datagrid('updateRow', {
                            index: rowIndex,
                            row: row
                        })
                        topWin.layer.closeAll('loading');
                        $('#' + fileBoxEl).filebox("clear");
                    },
                    error: function (responseStr) {
                        let message = responseStr['responseJSON']['message'];
                        if (message) {
                            topWin.layer.msg(message);
                        } else {
                            topWin.layer.msg('附件上传出错');
                        }
                        topWin.layer.closeAll('loading');
                        $('#' + fileBoxEl).filebox("clear");
                    }
                }
            )
            ;
        }
    }

    if (accept != undefined) {
        options.accept = accept
    }
    $('#' + fileBoxEl).filebox(options)
    $('#' + fileBoxEl).parent().find(".filebox-label").click();
}

function fileUploadAjaxWithCall(formData, call, multiple) {
    topWin.layer.load(0);
    var url = g.ctx + 'pc/sys/file/rest/upload/file'
    if (multiple != undefined && multiple) {
        url = g.ctx + 'pc/sys/file/rest/upload/files'
    }
    $.ajax({
        url: url, type: 'POST', data: formData, processData: false,// ⑧告诉jQuery不要去处理发送的数据
        contentType: false,
        async: false, // 设置为同步请求
        success: function (obj) {
            call(obj)
            topWin.layer.closeAll('loading');
        }, error: function (responseStr) {
            let message = responseStr['responseJSON']['message'];
            if (message) {
                topWin.layer.msg(message);
            } else {
                topWin.layer.msg('附件上传出错');
            }
            topWin.layer.closeAll('loading');
        }
    });
}

function singleFileUpload(el, idEl, accept) {
    const options = {
        buttonText: '选择文件',
        icons: [{
            iconCls: 'icon-cancel',
            handler: function (e) {
                $('#' + el).filebox('clear')
                $('#' + idEl).val('')
            }
        }],
        onChange: function () {
            let formData = new FormData();
            var filebox = $('#' + el).filebox("files");
            if (filebox.length <= 0) {
                return
            }
            formData.append("file", filebox[0]);
            fileUploadAjaxWithCall(formData, function (obj) {
                $('#' + idEl).val(obj.id)
            })
        }
    }
    if (accept != undefined) {
        options.accept = accept
    }
    $('#' + el).filebox(options)
    $('#' + el).next().children(".validatebox-text").css({'cursor': 'pointer'})
    $('#' + el).next().children(".validatebox-text").click(function () {
        if ($('#' + idEl).val()) {
            window.location.href = g.ctx + 'pc/sys/file/rest/download/' + $('#' + idEl).val()
        }
    })
}

//表单文件上传渲染组件
$(function () {
    initFileForm('custom-file-form')

});

/**
 * 初始化附件
 * @param className 附件class名称
 */
function initFileForm(className) {
    $.each($('.' + className), function (index, target) {
        let options = $(target).data('options');
        let fileIds = $(target).attr('data-fileIds');
        let fileSpan = '<div class="file-content">';
        if (!options.uploadEnable) {
            fileSpan = '<div class="file-content file-content-auto">';
        }
        if (fileIds) {
            $.ajax({
                url: g.ctx + 'pc/sys/file/rest/getFileListByFileIds',
                method: "get",
                async: false,
                data: {fileIds: fileIds},
                success: function (data) {
                    for (var i = 0; i < data.length; i++) {
                        fileSpan += '<span class="file-content-span">\n' +
                            '<div class="file-content-span-info" data-fileId="' + data[i].id + '" onclick="downloadFileForm(this,' + JSON.stringify(className).replace(/\"/g, "'") + ')">\n' +
                            ' <div class="img-div"><span class="file-icon file-icon-' + data[i].fileType + '"></span></div>\n' +
                            ' <div class="file-name">\n' +
                            '   <span>' + ellipsisMiddle(data[i].fileName,20) + '</span>\n' +
                            '   <div>' + Number((data[i].fileSize / 1024).toFixed(2)) + 'k</div>\n' +
                            '</div>\n' +
                            '</div>';
                        // if ((data[i].fileType === 'pdf' || data[i].fileType === 'png' || data[i].fileType === 'jpg') && options.previewEnable) {
                        fileSpan += '<div class="file-content-span-preview"><a data-fileId="' + data[i].id + '" onclick="previewFileForm(this,' + JSON.stringify(data[i].fileName).replace(/\"/g, "'") + ')">预览</a></div>'
                        // }
                        if (options.deleteEnable) {
                            fileSpan += '<div class="file-content-span-delete"><span data-fileId="' + data[i].id + '" onclick="deleteFileForm(this,' + JSON.stringify(className).replace(/\"/g, "'") + ')" class="layui-icon layui-icon-close"></span></div>'
                        }
                        fileSpan += '</span>';
                    }
                },
                error: function (data) {
                    layer.alert(JSON.parse(data.responseText).message);
                }
            });
        }
        fileSpan += '</div>';
        if (options.uploadEnable) {
            fileSpan += '<div class="file-upload-content">';
            if (options.moreFileUploadEnable) {
                fileSpan += '<input type="file" accept="' + options.fileTypes + '" multiple name="upload" class="header-upload-file" style="display: none;" onchange="fileUploadChange(this,' + JSON.stringify(options).replace(/\"/g, "'") + ',' + JSON.stringify(className).replace(/\"/g, "'") + ')"/>';
            } else {
                fileSpan += '<input type="file" accept="' + options.fileTypes + '" name="upload" class="header-upload-file" style="display: none;" onchange="fileUploadChange(this,' + JSON.stringify(options).replace(/\"/g, "'") + ',' + JSON.stringify(className).replace(/\"/g, "'") + ')"/>';
            }
            if (className === 'sign-create-file-form') {
                fileSpan += '<span onclick="fileUploadCreate(this,' + JSON.stringify(options).replace(/\"/g, "'") + ',' + JSON.stringify(className).replace(/\"/g, "'") + ')" class="file-upload-span l-btn-left l-btn-icon-left"><span class="l-btn-text">开始生成</span><span class="l-btn-icon icon-add">&nbsp;</span></span>\n';
            } else {
                fileSpan += '<span onclick="this.previousElementSibling.click()" class="file-upload-span l-btn-left l-btn-icon-left"><span class="l-btn-text">上传附件</span><span class="l-btn-icon icon-upload">&nbsp;</span></span>\n';
            }
            fileSpan += '</div>';
            fileSpan += '<div class="clearfix"></div>';
        }
        $(target).html(fileSpan);
    });
}

function ellipsisMiddle(text, maxLength, moreText = '...') {
    if (text.length <= maxLength) return text;

    const middle = '...';
    const middleLength = middle.length;

    const left = Math.floor((maxLength - middleLength) / 2);
    const right = maxLength - left - middleLength;

    return text.slice(0, left) + middle + text.slice(-right);
}

//表单文件上传渲染组件上传
function fileUploadChange(element, options, className) {
debugger;
    var businessTypeCode = options.businessTypeCode;
    if(businessTypeCode == "account_statement"){
        $.ajax({
            url: g.ctx + 'pc/sign/file/rest/createCheck',
            method: "post",
            data: {
                businessId: options.businessId,
                businessTypeCode: options.businessTypeCode
            },
            success: function (data) {
                console.log(data)
                if (data) {
                    parent.layer.alert('已存在签署文件,重新上传则会删除原签署文件！', {icon: 1});
                //    signFileDeleteAjax(options);
                } else {
                }
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message, {icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    }
    let target = $(element).parent('.file-upload-content').parent('.' + className).children('.file-content');
    let formTarget = $(element).parent('.file-upload-content').parent('.' + className);
    let fileIds = formTarget.attr('data-fileIds');
    let fileIdList = [];
    if (fileIds) {
        fileIdList = fileIds.split(',')
    }

    let fileKeys = formTarget.attr('data-fileKeys');
    let fileKeyList = [];
    if (fileKeys) {
        fileKeyList = fileKeys.split(',')
    }
    var files = element.files; //获取被选择的文件
    let formData = new FormData();
    if (files) {
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            if (options.fileSize&&file.size > options.fileSize * 1024 * 1024) {
                layer.alert('文件“' + file.name + '"大小超过' + options.fileSize + 'M，不允许上传');
                return false;
            }
            formData.append("files", file);
        }
        var loading = top.layer.msg('上传中，请稍后', {icon: 16, shade: [0.1, '#000'], time: false});
        let url = className === 'sign-file-form' ? g.ctx + 'pc/sys/esign/rest/saveSignFile' : g.ctx + 'pc/sys/file/rest/upload/files';

        if (className === 'sign-file-form') {
            fileUploadAjaxWithCall(formData, function (rows) {
                const fileIds = []
                $.each(rows, function (idx, itm) {
                    fileIds.push(itm.id)
                })
                formData.append("fileIds", fileIds.join(','))
                var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
            }, true)
        }

        $.ajax({
            url: url, type: 'POST', data: formData, processData: false,// ⑧告诉jQuery不要去处理发送的数据
            contentType: false,
            success: function (data) {
                //清空附件框
                $(element).val('')
                topWin.layer.msg('上传成功', {icon: 1});
                var fileSpan = '';
                for (var i = 0; i < data.length; i++) {
                    //如果是单文件上传直接替换
                    if (!options.moreFileUploadEnable) {
                        fileIdList = [];
                        fileKeyList = [];
                        target.html('')
                    }
                    fileIdList.push(data[i].id)
                    if (className === 'sign-file-form' || className === 'sign-create-file-form') {
                        fileKeyList.push(data[i].fileKey)
                    }
                    fileSpan += '<span class="file-content-span" >\n' +
                        '<div class="file-content-span-info" data-fileId="' + data[i].id + '" onclick="downloadFileForm(this)">\n' +
                        ' <div class="img-div"><span class="file-icon file-icon-' + data[i].fileType + '"></span></div>\n' +
                        ' <div class="file-name">\n' +
                        '   <span>' + data[i].fileName + '</span>\n' +
                        '   <div>' + Number((data[i].fileSize / 1024).toFixed(2)) + 'k</div>\n' +
                        '</div>\n' +
                        '</div>';
                    // if ((data[i].fileType === 'pdf' || data[i].fileType === 'png' || data[i].fileType === 'jpg') && options.previewEnable) {
                    fileSpan += '<div class="file-content-span-preview"><a data-fileId="' + data[i].id + '" onclick="previewFileForm(this,' + JSON.stringify(data[i].fileName).replace(/\"/g, "'") + ')">预览</a></div>'
                    // }
                    if (options.deleteEnable) {
                        fileSpan += '<div class="file-content-span-delete"><span data-fileId="' + data[i].id + '" data-fileKey="' + data[i].fileKey + '" onclick="deleteFileForm(this,' + JSON.stringify(className).replace(/\"/g, "'") + ')" class="layui-icon layui-icon-close"></span></div>'
                    }
                    fileSpan += '</span>';
                }
                target.append(fileSpan);
                formTarget.attr('data-fileIds', fileIdList.join(','))
                if (className === 'sign-file-form' || className === 'sign-create-file-form') {
                    formTarget.attr('data-fileKeys', fileKeyList.join(','))
                }
                top.layer.close(loading);
            },
            error: function (responseStr) {
                top.layer.close(loading);
                let message = responseStr['responseJSON']['message'];
                if (message) {
                    topWin.layer.msg(message);
                } else {
                    topWin.layer.msg('附件上传出错');
                }
            }
        });
    }

}

function fileUploadCreate(element, options, className) {
    let target = $(element).parent('.file-upload-content').parent('.' + className).children('.file-content');
    let formTarget = $(element).parent('.file-upload-content').parent('.' + className);
    var msg = "已生成签数文件,是否继续生成？";
    var businessTypeCode = options.businessTypeCode;
    if("account_statement" == businessTypeCode){
        msg = "已生成签数文件,是否继续生成?点击确定则会删除已有的签署文件，重新生成！";
    }
    $.ajax({
        url: g.ctx + 'pc/sign/file/rest/createCheck',
        method: "post",
        data: {
            businessId: options.businessId,
            businessTypeCode: options.businessTypeCode
        },
        success: function (data) {
            console.log(data)
            if (data) {
                top.layer.confirm(msg, {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    top.layer.closeAll()
                   /* if(options.businessTypeCode == "account_statement"){
                        signFileDeleteAjax(options);
                    }*/

                    uploadCreateAjax(target, formTarget, options, className)
                    return false;
                }, function () {
                    top.layer.closeAll()
                    return false;
                });
            } else {
                uploadCreateAjax(target, formTarget, options, className)
            }
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message, {icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });

}

function  signFileDeleteAjax(options) {
    $.ajax({
        url: g.ctx + 'pc/sign/file/rest/signFileDelete',
        method: "post",
        data: {
            businessId: options.businessId,
            businessTypeCode: options.businessTypeCode
        },
        success: function (data) {
            console.log("删除文件成功！");
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message, {icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

function uploadCreateAjax(target, formTarget, options, className) {
    let fileIds = formTarget.attr('data-fileIds');
    let fileIdList = [];
    if (fileIds) {
        fileIdList = fileIds.split(',')
    }

    let fileKeys = formTarget.attr('data-fileKeys');
    let fileKeyList = [];
    if (fileKeys) {
        fileKeyList = fileKeys.split(',')
    }
    var loading = top.layer.msg('生成中，请稍后', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/sign/file/rest/create',
        type: 'POST',
        data: {
            businessId: options.businessId,
            businessTypeCode: options.businessTypeCode,
            templateType: $('#templateType').length>0?$('#templateType').combobox('getValue'):null
        },
        success: function (data) {
            topWin.layer.msg('生成成功', {icon: 1});
            var fileSpan = '';
            for (var i = 0; i < data.length; i++) {
                //如果是单文件上传直接替换
                if (!options.moreFileUploadEnable) {
                    fileIdList = [];
                    fileKeyList = [];
                    target.html('')
                }
                fileIdList.push(data[i].id)
                if (className === 'sign-file-form' || className === 'sign-create-file-form') {
                    fileKeyList.push(data[i].fileKey)
                }
                fileSpan += '<span class="file-content-span" >\n' +
                    '<div class="file-content-span-info" data-fileId="' + data[i].id + '" onclick="downloadFileForm(this)">\n' +
                    ' <div class="img-div"><span class="file-icon file-icon-' + data[i].fileType + '"></span></div>\n' +
                    ' <div class="file-name">\n' +
                    '   <span>' + data[i].fileName + '</span>\n' +
                    '   <div>' + Number((data[i].fileSize / 1024).toFixed(2)) + 'k</div>\n' +
                    '</div>\n' +
                    '</div>';
                if (i == 0) {
                    fileSpan += '<input type="hidden" id="numberOfPages" name="numberOfPages" value="'+data[i].numberOfPages+'">';
                }

                // if ((data[i].fileType === 'pdf' || data[i].fileType === 'png' || data[i].fileType === 'jpg') && options.previewEnable) {
                fileSpan += '<div class="file-content-span-preview"><a data-fileId="' + data[i].id + '" onclick="previewFileForm(this,' + JSON.stringify(data[i].fileName).replace(/\"/g, "'") + ')">预览</a></div>'
                // }
                if (options.deleteEnable) {
                    fileSpan += '<div class="file-content-span-delete"><span data-fileId="' + data[i].id + '" data-fileKey="' + data[i].fileKey + '" onclick="deleteFileForm(this,' + JSON.stringify(className).replace(/\"/g, "'") + ')" class="layui-icon layui-icon-close"></span></div>'
                }
                fileSpan += '</span>';
            }
            target.append(fileSpan);
            formTarget.attr('data-fileIds', fileIdList.join(','))
            if (className === 'sign-file-form' || className === 'sign-create-file-form') {
                formTarget.attr('data-fileKeys', fileKeyList.join(','))
            }
            top.layer.close(loading);
        },
        error: function (responseStr) {
            top.layer.close(loading);
            let message = responseStr['responseJSON']['message'];
            if (message) {
                topWin.layer.msg(message);
            } else {
                topWin.layer.msg('附件生成出错');
            }
        }
    });
}

//表单文件上传渲染组件删除
function deleteFileForm(obj, className) {
    let formTarget = $(obj).parent('.file-content-span-delete').parent('.file-content-span').parent('.file-content').parent('.' + className);
    let fileIds = formTarget.attr('data-fileIds');
    let fileKeys = formTarget.attr('data-fileKeys');
    let fileIdList = [];
    let fileKeyList = [];
    if (fileIds) {
        fileIdList = fileIds.split(',')
    }
    if (fileKeys) {
        fileKeyList = fileKeys.split(',')
    }
    fileIdList.remove($(obj).attr('data-fileId') + '');
    formTarget.attr('data-fileIds', fileIdList.join(','))

    if (className === 'sign-file-form' || className === 'sign-create-file-form') {
        fileKeyList.remove($(obj).attr('data-fileKey') + '');
        formTarget.attr('data-fileKeys', fileKeyList.join(','))
    }
    $(obj).parent().parent().remove();
}

//表单文件上传渲染组件下载
function downloadFileForm(obj) {
    window.location.href = g.ctx + 'pc/sys/file/rest/download/' + $(obj).attr('data-fileId')
}

function isBlank(value) {
    return value == null || String(value).trim() === '';
}

//表单文件上传渲染组件预览
function previewFileForm(obj, fileName, fileId) {
    if (fileId == undefined) {
        fileId = $(obj).attr('data-fileId');
    }
    let originUrl = sysProp.hostUrl + '/pc/sys/file/rest/download/' + fileId;
    if (fileName.substr(fileName.lastIndexOf('.') + 1).indexOf("pdf") !== -1) {
        localStorage.pdf_url = originUrl;
        top.layer.open({
            skin: 'layui-layer-molv',
            title: 'PDF文件预览',
            type: 2,
            scrollbar: false,
            area: ['100%', '100%'],
            maxmin: false,
            content: '/static/plugins/pdfjs/web/viewer.html'
        });
    }else {
        let newFileName = fileName.replace(/[^\w\-.\u4e00-\u9fa5]/g, '');
        var previewUrl = originUrl + '?fullfilename=' + fileId+'_'+newFileName;
        console.log(encodeURIComponent(Base64.encode(previewUrl)))
        top.layer.open({
            skin: 'layui-layer-molv',
            title: '文件预览',
            type: 2,
            scrollbar: false,
            area: ['100%', '100%'],
            maxmin: false,
            content: sysProp.previewUrl + '?url=' + encodeURIComponent(Base64.encode(previewUrl))
        });
    }
    // if (fileId == undefined) {
    //     originUrl = g.ctx + 'pc/sys/file/rest/download/' + $(obj).attr('data-fileId');
    // }
    // if (fileType.indexOf("png") !== -1 || fileType.indexOf("jpg") !== -1) {
    //     layer.photos({
    //         photos: {
    //             "title": "图片预览",
    //             "start": 0,
    //             "data": [
    //                 {
    //                     "alt": '',
    //                     "pid": 5,
    //                     "src": url
    //                 }
    //             ]
    //         }
    //     });
    // }
}

//判断文件是否支持预览
function previewFlag(fileType) {
    if (['pdf', 'png'].indexOf(fileType) != -1) {
        return true
    } else {
        return false
    }
}

//js 遍历数组取出字符串用逗号拼接
function getTextByJs(arr) {
    var str = "";
    for (var i = 0; i < arr.length; i++) {
        str += arr[i] + ",";
    }
    //去掉最后一个逗号(如果不需要去掉，就不用写)
    if (str.length > 0) {
        str = str.substr(0, str.length - 1);
    }
    return str;
}

/**
 这是用 js 实现数值的千分位及保存小数方法：
 * 将数值四舍五入后格式化.
 * @param num 数值(Number或者String)
 * @param cent 要保留的小数位(Number)
 * @param isThousand 是否需要千分位 0:不需要,1:需要(数值类型);
 * @return 格式的字符串,如'1,234,567.45'
 * @type String
 */
function formatNumber(num, cent, isThousand) {
    if (num == 0 || num == undefined || num == null || num == 'undefined' || num == 'null') {
        num = 0;
    }
    num = num.toString().replace(/\$|\,/g, '');

    // 检查传入数值为数值类型
    if (isNaN(num))
        num = "0";

    // 获取符号(正/负数)
    sign = (num == (num = Math.abs(num)));

    num = Math.floor(num * Math.pow(10, cent) + 0.50000000001);  // 把指定的小数位先转换成整数.多余的小数位四舍五入
    cents = num % Math.pow(10, cent);              // 求出小数位数值
    num = Math.floor(num / Math.pow(10, cent)).toString();   // 求出整数位数值
    cents = cents.toString();               // 把小数位转换成字符串,以便求小数位长度

    // 补足小数位到指定的位数
    while (cents.length < cent)
        cents = "0" + cents;

    if (isThousand) {
        // 对整数部分进行千分位格式化.
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    }

    if (cent > 0)
        return (((sign) ? '' : '-') + num + '.' + cents);
    else
        return (((sign) ? '' : '-') + num);
}


/**
 * 初始化关键数据
 * @param url
 */
function initNecessaryData(url, key, value, queryParam) {
    var self = this;
    var k = key == undefined ? 'code' : key
    var v = value == undefined ? 'codeWithDesc' : value
    $.ajax({
        url: g.ctx + url,
        type: "GET",
        data: queryParam == undefined ? {} : queryParam,
        async: false,
        success: function (data) {
            var map = {};
            $.each(data, function (iidx, iitm) {
                map[iitm[k]] = iitm[v]
            })
            self[url + "NecessaryData"] = data
            self[url + "NecessaryValues"] = map
        }
    })
}

/**
 * 初始化字典数据
 * @param types
 */
function initNecessaryDatas(urls) {
    var self = this;
    let typeList = urls.split(',');
    for (const typeListElement of typeList) {
        $.ajax({
            url: g.ctx + typeListElement,
            type: "GET",
            async: false,
            success: function (data) {
                var map = {};
                $.each(data, function (iidx, iitm) {
                    map[iitm['code']] = iitm['codeWithDesc']
                })
                //如果是税率主数据，则保存税率的值
                if (typeListElement.indexOf('tax/rest/listAll') !== -1) {
                    var valueMap = {};
                    $.each(data, function (iidx, iitm) {
                        valueMap[iitm['code']] = iitm['taxValue']
                    })
                    self["taxValues"] = valueMap
                }
                self[typeListElement + "NecessaryData"] = data
                self[typeListElement + "NecessaryValues"] = map
            }
        })
    }
}

function getNecessaryDataName(url, value) {
    if (!value) {
        return '';
    }
    var self = this;
    let map = self[url + "NecessaryValues"];
    if (map == undefined) {
        return ''
    }
    return map[value]
}

function getNecessaryDataList(url) {
    var self = this;
    return self[url + "NecessaryData"];
}

/**
 * 传入税率编码和待计算价格计算含税或未税价格使用系统默认的配置
 * @param taxCode 税率编码
 * @param price 待计算价格
 * @param countFlag 计算方式；0-算未税；1-算含税；
 * @returns 计算后的价格
 */
function getDefaultTaxPrice(taxCode, price, countFlag) {
    if (!taxCode) {
        return null;
    }
    return getTaxPrice(taxCode, price, countFlag, priceHandle.precision, priceHandle.cutType);
}

/**
 * 传入税率编码和待计算价格计算含税或未税价格
 * @param taxCode 税率编码
 * @param price 待计算价格
 * @param countFlag 计算方式；0-算未税；1-算含税；
 * @param precision 保留几位小数
 * @param cutType 截取方式；0-四舍五入；1-向下舍入（截断）；
 * @returns 计算后的价格
 */
function getTaxPrice(taxCode, price, countFlag, precision, cutType) {
    if (!taxCode) {
        return null;
    }
    precision = precision ? Number(precision) : 4;
    cutType = cutType ? Number(cutType) : 0;
    var self = this;
    let map = self["taxValues"];
    let taxValue = map[taxCode];
    let countPrice = new BigNumber(0);
    //含税 = 未税*（1+税率）	未税 = 含税/（1+税率）
    if (Number(countFlag) === 0) {
        countPrice = new BigNumber(price).dividedBy(new BigNumber(taxValue).plus(1)).decimalPlaces(precision, cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN).toNumber()
    } else {
        countPrice = new BigNumber(price).multipliedBy(new BigNumber(taxValue).plus(1)).decimalPlaces(precision, cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN).toNumber()
    }
    return countPrice;
}

/**
 * 按照系统要求输出金额，不做千分符处理
 * @param price 传入金额
 * @returns 格式化后的金额
 */
function getPrice(price) {
    let tmp = formatterPrice(price);
    //先去除可能的千分位
    return tmp.replace(/\$|\,/g, '');
}

function formatterCustomPrice(price, precision, repair, thousand) {
    if (!price || isNaN(price)) {
        return '';
    }
    //先去除可能的千分位
    price = price.toString().replace(/\$|\,/g, '');
    if (Number(price) === 0) {
        return '0';
    }
    price = new BigNumber(price).decimalPlaces(precision, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN);
    price = price.toString();
    //加上千分位
    if (thousand) {
        price = paddingNum(Number(price));
    }
    if (repair) {
        var pos_decimal = price.indexOf('.');
        //没有小数点的加上小数点
        if (pos_decimal < 0) {
            pos_decimal = price.length;
            if (precision !== 0) {
                price += '.';
            }
        }
        if (price.length <= pos_decimal + precision) {
            while (price.length <= pos_decimal + precision) {
                price += '0';
            }
        } else {
            price = price.substring(0, pos_decimal + precision + 1)
        }
    }
    return price;
}

/**
 * 金额格式化输出
 * @param price 传入金额
 * @returns 格式化后的金额
 */
function formatterPrice(price) {
    if (isBlank(price)) {
        return '';
    }
    //先去除可能的千分位
    price = price.toString().replace(/\$|\,/g, '');
    if (Number(price) === 0) {
        return '0';
    }
    price = new BigNumber(price).decimalPlaces(priceHandle.precision, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN);
    price = price.toString();
    //加上千分位
    if (priceHandle.thousand) {
        price = paddingNum(Number(price));
    }
    if (priceHandle.repair) {
        var pos_decimal = price.indexOf('.');
        //没有小数点的加上小数点
        if (pos_decimal < 0) {
            pos_decimal = price.length;
            if (priceHandle.precision !== 0) {
                price += '.';
            }
        }
        if (price.length <= pos_decimal + priceHandle.precision) {
            while (price.length <= pos_decimal + priceHandle.precision) {
                price += '0';
            }
        } else {
            price = price.substring(0, pos_decimal + priceHandle.precision + 1)
        }
    }
    return price;
}

function paddingNum(inputNum) {
    let flag = inputNum > 0;
    let numArr = Math.abs(inputNum).toString().split('.');
    let right = numArr[1] ? '.' + numArr[1] : '';   // 小数点右边的数字
    let left = numArr[0];  // 小数点左边的数字
    let temp = '';
    while (left.length > 3) {
        // str.slice(start, end); 截取字符串，返回截取的字符串，end取不到
        temp = ',' + left.slice(-3) + temp;
        left = left.slice(0, left.length - 3);
    }
    return flag ? left + temp + right : '-' + left + temp + right;
}

/**
 * 初始化字典数据
 * @param types
 */
function initDict(types) {
    var self = this;
    let typeList = types.split(',');
    $.ajax({
        url: g.ctx + 'pc/sys/dict/getDicByTypes',
        type: "GET",
        async: false,
        data: {types: types},
        success: function (data) {
            $.each(typeList, function (idx, itm) {
                var map = {};
                $.each(data[itm], function (iidx, iitm) {
                    map[iitm.code] = iitm.codeWithDesc
                })
                self[itm + "NecessaryData"] = data[itm]
                self[itm + "dictValues"] = map
            })
        }
    })
}
//字典值只显示名称
function initDictName(types) {
    var self = this;
    let typeList = types.split(',');
    $.ajax({
        url: g.ctx + 'pc/sys/dict/getDicByTypes',
        type: "GET",
        async: false,
        data: {types: types},
        success: function (data) {
            $.each(typeList, function (idx, itm) {
                var map = {};
                $.each(data[itm], function (iidx, iitm) {
                    map[iitm.code] = iitm.name
                })
                self[itm + "NecessaryData"] = data[itm]
                self[itm + "dictValues"] = map
            })
        }
    })
}

function getDicName(type, value) {
    if (!value) {
        return '';
    }
    var self = this;
    let map = self[type + "dictValues"];
    if (map == undefined) {
        return ''
    }
    return map[value]
}

function getDictList(type) {
    var self = this;
    return self[type + "NecessaryData"];
}

/**
 * 批量下载
 * @param fileIds 附件id（多个逗号隔开）
 */
function batchDownload(fileIds) {
    if (fileIds) {
        let fileIdList = fileIds.split(',');
        $.each(fileIdList, function (index, fileId) {
            var iframe = document.createElement('iframe');
            iframe.style.display = "none";
            iframe.style.height = 0;
            //设置下载路径
            iframe.src = g.ctx + 'pc/sys/file/rest/download/' + fileId;
            document.body.appendChild(iframe);
            setTimeout(function () {
                iframe.remove();
            }, 60 * 1000);
        });
    }
}

/**
 * 通用导出组件（支持列筛选、排序、记忆、重置功能）
 * @param exportUrl 导出url
 * @param tableId 表格id
 * @param query 查询参数
 */
function openExportDialog(exportUrl, tableId, query) {
    var tableData = getExcelKeyTitle(tableId);
    localStorage.setItem('default' + btoa(exportUrl), JSON.stringify(tableData));
    var dialog = {}
    var options = {
        title: '请勾选需要导出的列',
        width: '300',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确认导出',
                iconCls: 'icon-download',
                handler: function () {
                    topWin.frames['exportDialog'].confirmExport(function (exportData) {
                        console.log(exportData)
                        xhrPostExport(exportUrl, query, exportData)
                        // var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                        // var xhr = new XMLHttpRequest();
                        // xhr.responseType = "arraybuffer";
                        // xhr.open("POST", g.ctx + exportUrl, true);
                        // xhr.onload = function () {
                        //     top.layer.close(loading);
                        //     try {
                        //         let enc = new TextDecoder('utf-8')
                        //         let data = JSON.parse(enc.decode(new Uint8Array(this.response)));
                        //         if (data.message) {
                        //             parent.layer.alert(data.message, {icon: 2, shadeClose: true, title: '温馨提示'});
                        //         }
                        //     } catch (e) {
                        //         var fileName = xhr.getResponseHeader("Content-disposition").replace('attachment;filename=', '');
                        //         console.log(decodeURI(fileName.replace('attachment;filename=', ''))); // 输出文件名
                        //         const blob = new Blob([this.response], {type: "application/vnd.ms-excel"});
                        //         if (blob.size < 1) {
                        //             parent.layer.alert('导出失败，导出的内容为空！', {
                        //                 icon: 2,
                        //                 shadeClose: true,
                        //                 title: '温馨提示'
                        //             });
                        //             return;
                        //         }
                        //         if (window.navigator.msSaveOrOpenBlob) {
                        //             navigator.msSaveOrOpenBlob(blob, decodeURI(fileName))
                        //         } else {
                        //             const aLink = document.createElement('a');
                        //             aLink.style.display = 'none';
                        //             aLink.href = window.URL.createObjectURL(blob);
                        //             aLink.download = decodeURI(fileName);
                        //             document.body.appendChild(aLink);
                        //             aLink.click();
                        //             document.body.removeChild(aLink);
                        //             parent.layer.alert('请在浏览器下载中查看导出的文件', {
                        //                 icon: 1,
                        //                 shadeClose: true,
                        //                 title: '导出成功'
                        //             });
                        //         }
                        //     }
                        // };
                        // var formData = new FormData()
                        // formData.append('exportFiled', JSON.stringify(exportData))
                        // formData.append('queryStr', JSON.stringify(query))//加了这一句
                        // xhr.send(formData);
                        dialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    dialog.dialog('close');
                }
            }
        ]
    }
    dialog = openDialog('exportDialog', g.ctx + "pc/sys/export/dialog?exportUrlKey=" + btoa(exportUrl), options)

}

/**
 * 通用列排序隐藏组件（支持列筛选、排序、记忆、重置功能）
 * @param options 表格配置
 */
function openSortDialog(options) {
    var columns = options.columns;
    var code = options.code;
    var tableData = getSortKeyTitle(columns);
    //查询后台数据
    var loading = topWin.layer.msg('数据加载中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/sys/columnSort/rest/getData',
        type: 'POST',
        data: {code: code},
        async: false,
        success: function (result) {
            topWin.layer.close(loading);
            if (result){
                localStorage.setItem('remoteData' + code, result.columnSortData);
            }else {
                localStorage.removeItem('remoteData' + code);
            }
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
    localStorage.setItem('default' + code, JSON.stringify(tableData));
    var dialog = {}
    var options1 = {
        title: '列设置',
        width: '300',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确认',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['exportDialog'].confirmExport(function (exportData) {
                        dialog.dialog('close');
                        var newColumns = [];
                        exportData.forEach(function (item) {
                            columns.forEach(function (item2) {
                                if (item.title === item2.title){
                                    if (item.select === 1){
                                        newColumns.push(item2)
                                    }
                                }
                            });
                        });
                        options.callBack(newColumns);
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    dialog.dialog('close');
                }
            }
        ]
    }
    dialog = openDialog('exportDialog', g.ctx + "pc/sys/columnSort/dialog?code=" + code, options1)

}

/**
 * 通过编码查询数据库列排序
 * @param code 编码
 * @param columns 原始列
 */
function getRemoteColumnSort(code,columns){
    var loading = topWin.layer.msg('数据加载中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    var newColumns = [];
    $.ajax({
        url: g.ctx + 'pc/sys/columnSort/rest/getData',
        type: 'POST',
        data: {code: code},
        async: false,
        success: function (result) {
            topWin.layer.close(loading);
            if (result){
                var suu = false;
                columns.forEach(function (item) {
                    var su = false;
                    JSON.parse(result.columnSortData).forEach(function (item2) {
                        if (item.title === item2.title){
                            su = true;
                        }
                    });
                    if (!su){
                        suu = true;
                    }
                });
                if (!suu){
                    JSON.parse(result.columnSortData).forEach(function (item) {
                        var su = false;
                        columns.forEach(function (item2) {
                            if (item.title === item2.title){
                                su = true;
                                if (item.select === 1){
                                    newColumns.push(item2)
                                }
                            }
                        });
                    });
                }else {
                    $.ajax({
                        url: g.ctx + 'pc/sys/columnSort/rest/deleteData',
                        type: 'POST',
                        data: {code: code},
                        async: false,
                        success: function (result) {
                        },
                        error: function (data) {
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    });
                }

            }
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
    return newColumns.length>0?newColumns:columns;
}

function xhrPostExport(exportUrl, query, exportData) {
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    var xhr = new XMLHttpRequest();
    xhr.responseType = "arraybuffer";
    xhr.open("POST", g.ctx + exportUrl, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.onload = function () {
        top.layer.close(loading);
        try {
            let enc = new TextDecoder('utf-8')
            let data = JSON.parse(enc.decode(new Uint8Array(this.response)));
            if (data.message) {
                if (data.message.indexOf("成功") !== -1) {
                    parent.layer.alert(data.message, {icon: 1, shadeClose: true, title: '温馨提示'});
                } else {
                    parent.layer.alert(data.message, {icon: 2, shadeClose: true, title: '温馨提示'});
                }
            }
        } catch (e) {
            var fileName = xhr.getResponseHeader("Content-disposition").replace('attachment;filename=', '');
            console.log(decodeURI(fileName.replace('attachment;filename=', ''))); // 输出文件名
            const blob = new Blob([this.response], {type: "application/vnd.ms-excel"});
            if (blob.size < 1) {
                parent.layer.alert('导出失败，导出的内容为空！', {
                    icon: 2,
                    shadeClose: true,
                    title: '温馨提示'
                });
                return;
            }
            if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveOrOpenBlob(blob, decodeURI(fileName))
            } else {
                const aLink = document.createElement('a');
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(blob);
                aLink.download = decodeURI(fileName);
                document.body.appendChild(aLink);
                aLink.click();
                document.body.removeChild(aLink);
                parent.layer.alert('请在浏览器下载中查看导出的文件', {
                    icon: 1,
                    shadeClose: true,
                    title: '导出成功'
                });
            }
        }
    };
    var formData = new FormData()
    if (exportData) {
        formData.append('exportFiled', JSON.stringify(exportData))
    }
    formData.append('queryStr', JSON.stringify(query))//加了这一句
    xhr.send(formData);
}

function getExcelKeyTitle(gridId) {
    var opts = $('#' + gridId).datagrid('getColumnFields');
    var opts2 = $('#' + gridId).datagrid('getColumnFields', true);
    opts = opts2.concat(opts);
    var fileds = []
    for (var i = 0; i < opts.length; i++) {
        if (opts[i] === 'ck') continue;
        var option = $('#' + gridId).datagrid("getColumnOption", opts[i]);
        if (!option.hidden) {
            if (option.title === undefined) continue;
            if (option.exportHidden) continue;
            fileds.push({
                title: option.title.replace('<font color="red">*</font>', ""),
                field: opts[i],
                select: 1,
                width: Number(option.width),
                exportEnum: option.exportEnum,
                exportDateFormatter: option.exportDateFormatter
            })
        }
    }
    return fileds;
}

function getSortKeyTitle(columns) {
    for (var i = 0; i < columns.length; i++) {
        columns[i].select = 1
    }
    return columns;
}


function toCamelCase(string) {
    string = string.replace(/_([a-z])/g, function (all, letter) {
        return letter.toUpperCase();
    });
    return string.replace(/_([0-9])/g, function (all, letter) {
        return letter;
    });
}


//固定列导出
function exportFixedGrid(exportUrl, exportData, query) {
    var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    var xhr = new XMLHttpRequest();
    xhr.responseType = "arraybuffer";
    xhr.open("POST", g.ctx + exportUrl, true);
    xhr.onload = function () {
        topWin.layer.close(loading);
        try {
            let enc = new TextDecoder('utf-8')
            let data = JSON.parse(enc.decode(new Uint8Array(this.response)));
            if (data.message) {
                topWin.layer.alert(data.message, {icon: 2, shadeClose: true, title: '温馨提示'});
            }
        } catch (e) {
            var fileName = xhr.getResponseHeader("Content-disposition").replace('attachment;filename=', '');
            const blob = new Blob([this.response], {type: "application/vnd.ms-excel"});
            if (blob.size < 1) {
                topWin.layer.alert('导出失败，导出的内容为空！', {
                    icon: 2,
                    shadeClose: true,
                    title: '温馨提示'
                });
                return;
            }
            if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveOrOpenBlob(blob, decodeURI(fileName))
            } else {
                const aLink = document.createElement('a');
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(blob);
                aLink.download = decodeURI(fileName);
                document.body.appendChild(aLink);
                aLink.click();
                document.body.removeChild(aLink);
                topWin.layer.alert('请在浏览器下载中查看导出的文件', {
                    icon: 1,
                    shadeClose: true,
                    title: '导出成功'
                });
            }
        }
    };
    var formData = new FormData()
    formData.append('exportFiled', JSON.stringify(exportData))
    formData.append('queryStr', JSON.stringify(query))//加了这一句
    xhr.send(formData);
}

//时间狂时间绑定
$.extend($.fn.datetimebox.methods, {
    //绑定双击事件方法
    bindDblClick: function (jq) {
        var panel = $(jq).combo("panel");
        panel.find(".calendar-day").off("dblclick").on("dblclick", function (e) {
            var calendar = $(jq).datetimebox("calendar");
            var spinner = $(jq).datetimebox("spinner");
            var current = calendar.calendar("options").current;

            var year = current.getFullYear();
            var month = current.getMonth() + 1;
            var date = current.getDate();
            var time = spinner.spinner("getValue");

            var datetime = year + "-" + month + "-" + date + " " + time;

            $(jq).datetimebox("setValue", datetime);

            $(jq).combo("hidePanel");
        });
    }
});
$.extend($.fn.datetimebox.defaults, {
    onShowPanel: function () {
        $(this).datetimebox("bindDblClick");
    }
});


//打开弹出窗口
var pageii = null;

function openLayerWin(title, url, width, height) {
    if (url.indexOf("/login") > 0) {
        window.location.href = '/login';
        return;
    }

    if (screenWidth > 800) {
        if (title == '添加产品' || title == 'Add Product' || title == '选择物料' || title == 'select material') {
            pageii = layer.open({
                title: title,
                type: 2,
                scrollbar: false,
                area: ["910px", height],
                content: url
            });
        } else {
            if (height == '95%') {
                pageii = layer.open({
                    title: title,
                    type: 2,
                    scrollbar: false,
                    //offset:[0,210],
                    area: ["1000px;", '100%'],
                    content: url
                });
            } else if (height == '340px') {
                pageii = layer.open({
                    title: title,
                    type: 2,
                    scrollbar: false,
                    //offset:[0,210],
                    area: [width, height],
                    content: url
                });
            } else {
                var ss = screenWidth - 100;
                if (width == ss + "px") {
                    width = "1000px";
                }
                pageii = layer.open({
                    title: title,
                    type: 2,
                    scrollbar: false,
                    area: [width, height],
                    content: url
                });
            }
        }
    } else {
        pageii = layer.open({
            title: title,
            type: 2,
            scrollbar: false,
            area: ["100%", "100%"],
            content: url
        });

    }
}

const OaProcessType = {
    SUPPLIER_ACCESS: 1,//供应商准入
    SUPPLIER_CHANGE: 2,//供应商变更
    INQUIRY_PRICE: 4,//询报价价格OA回调
    TENDER_PRICE: 5,//询报价价格OA回调
    AUDIT_PRICE: 6,//调价OA回调
    PCN_CHANGE: 7,//PCN推送
    DEDUCTION: 8,//扣款确认
    CONTRACT_CONFIRM: 9,//
    PAYMENT_COD_APPLY: 13,//对账付款申请推送OA回调
    MATERIAL_DEMO: 14,//物料认证
    PAYMENT_ADVANCE_APPLY: 16,//预付款申请推送OA回调
    QUOTA_PRICE: 17,//预付款申请推送OA回调
}

const shareFormId = {
    er_contractbill: 'er_contractbill',
    t_ap_applypaybill: 'ap_payapply',
    CONTRACT_REVIEW: 'm4p4_fa_contractreview'    // 合同评审单
}

/**
 * oa审批路径
 */
function oaTrack(oaId, formId) {
    if (!oaId) {
        return ''
    }
    return '<a style="color: #108ee9" onclick="previewOaTrack(\'' + oaId + '\',\'' + formId + '\')">' + oaId + '</a>';
}

/**
 * 共享审批路径
 */
function shareTrack(pkId, formId,oaProcessCode) {
    if (!pkId) {
        return ''
    }
    return '<a style="color: #108ee9" onclick="previewShareTrack(\'' + pkId + '\',\'' + formId + '\')">' + oaProcessCode + '</a>';
}

function previewOaTrack(oaId, type) {
    var index_wait;
    $.ajax({
        url: g.ctx + "pc/sys/oaTrack/rest/index",
        data: {oaId: oaId, type: type},
        type: "GET",
        beforeSend: function () {
            index_wait = topWin.layer.load(0, {  //发送请求前调用load方法
                shade: [0.5, '#fff'],  //0.5透明度的白色背景
            });
        },
        complete: function () {
            topWin.layer.close(index_wait);
        },
        success: function (data) {
            window.open(data);
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    })
}
function previewShareTrack(pkId, formId) {
    var index_wait;
    $.ajax({
        url: g.ctx + "pc/sys/oaTrack/rest/share/index",
        data: {pkId: pkId, formId: formId},
        type: "GET",
        beforeSend: function () {
            index_wait = topWin.layer.load(0, {  //发送请求前调用load方法
                shade: [0.5, '#fff'],  //0.5透明度的白色背景
            });
        },
        complete: function () {
            topWin.layer.close(index_wait);
        },
        success: function (data) {
            window.open(data);
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    })
}

function dateColor(dateString) {
    if (dateString === '' || dateString === undefined) {
        return '';
    }
    const inputDate = moment(dateString); // 解析传入的日期字符串
    const currentDate = moment(); // 获取当前日期
    const diffDays = inputDate.diff(currentDate, 'days'); // 计算日期差（以天为单位）
    if (diffDays <= 7) {
        return '<span style="color:red">' + dateString + '</span>'; // 如果相差7天以内，返回红色
    } else {
        return '<span style="color:green">' + dateString + '</span>'; // 如果大于7天，返回绿色
    }
}


/**
 * 将金额转化为大写的方法
 * @param str 金额
 * @return {string} 汉字大写
 */
function number_chinese(str) {
    let num = parseFloat(str);
    let strOutput = "",
        strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分';
    num += "00";
    let intPos = num.indexOf('.');
    if (intPos >= 0) {
        num = num.substring(0, intPos) + num.substr(intPos + 1, 2);
    }
    strUnit = strUnit.substr(strUnit.length - num.length);
    for (let i = 0; i < num.length; i++) {
        strOutput += '零壹贰叁肆伍陆柒捌玖拾'.substr(num.substr(i, 1), 1) + strUnit.substr(i, 1);
    }
    return strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零')
        .replace(/零{2,}/g, '零').replace(/零([亿|万])/g, '$1')
        .replace(/零+元/, '元').replace(/亿零{0,3}万/, '亿')
        .replace(/^元/, "零元")
}

/**
 * 设置审计操作日志
 * @param operation 操作名称
 * @param module 模块
 * @param callback 回调函数
 */
function setOperationLog(operation, module, callback) {
    $.ajax({
        url: g.ctx + "pc/sys/auditLog/rest/save",
        type: "POST",
        async: true,
        data: {
            operation: operation,
            module: module,
        },
        success: function (data) {
            if (typeof(callback) === "function") {
                callback(data);
            }
        }
    });
}

/**
 * 打开字典选择对话框
 * @param title 标题
 * @param dictType 字典类型
 * @param callback 选择数据回调函数
 */
function openDictSelectDialog(title, dictType, callback) {
    let dictSelectDialog = openDialog(
        'dictSelectDialog',
        g.ctx + "pc/sys/dict/selectDialog?dictType=" + dictType,
        {
            title: title,
            width: '50%',
            height: '50%',
            cache: false,
            modal: true,
            border: 'thin',
            onClose: function () {
                dictSelectDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: '选择',
                    iconCls: 'icon-ok',
                    handler: function () {
                        topWin.frames['dictSelectDialog'].confirmCallback(function (row) {
                            if (typeof callback === "function") {
                                callback(row);
                                dictSelectDialog.dialog('close');
                            }
                        });
                    }
                },
                {
                    text: '关闭',
                    iconCls: 'icon-cancel',
                    handler: function () {
                        dictSelectDialog.dialog('close');
                    }
                }
            ]
        }
    );
    return dictSelectDialog;
}