// 输出base64编码
const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
const tableToExcel = async (jsonData, fileName) => {
    return new Promise(resolve => {
        try {
            let str = '<tr>'
            Object.keys(jsonData[0]).forEach(name => {
                const tdStr = `<td>${name}</td>`
                str += tdStr;
            })
            str += '</tr>'
            for (let i = 0; i < jsonData.length; i++) {
                str += '<tr>';
                for (const key in jsonData[i]) {
                    // 增加\t为了不让表格显示科学计数法或者其他格式
                    str += `<td>${jsonData[i][key] + '\t'}</td>`;
                }
                str += '</tr>';
            }
            const currentTime = new Date()
            const fileSuffix = currentTime.valueOf()
            const name = fileName + '质量分' + fileSuffix
            // Worksheet名
            const worksheet = '用户质量分';
            const uri = 'data:application/vnd.ms-excel;base64,';
            // 下载的表格模板数据
            const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
    xmlns:x="urn:schemas-microsoft-com:office:excel" 
    xmlns="http://www.w3.org/TR/REC-html40">
    <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
    <x:Name>${worksheet}</x:Name>
    <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
    </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
    <meta charset='utf-8' />
    </head><body><table>${str}</table></body></html>`;
            // 下载模板
            // window.location.href = uri + base64(template);
            const downloadLink = document.createElement("a");
            downloadLink.href = uri + base64(template);
            downloadLink.download = name + '.xls';
            downloadLink.target = '_blank';
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
            resolve(true)
        }
        catch (r) {
            console.log(r, 'html excel')
            resolve(false)
        }
    })
};


export const exportExcelFunc = async (tableData,name) => {
    return new Promise(async (resolve) => {
        try {
            await tableToExcel(tableData,name)
            resolve(true)
        }
        catch (r) {
            console.log(r, 'exportExcelFunc')
            resolve(false)
        }
    })
}