
/* eslint-disable */
import htmlDocx from 'html-docx-js/dist/html-docx';
import FileSaver from 'file-saver';
import * as html2pdf from 'html2pdf.js';
import { saveAs } from "file-saver";
import * as XLSX from "xlsx";
import { utils } from "xlsx";
// import XLSX from "xlsx-style";
import * as XLSXStyle from "xlsx-js-style";
import XLSXST from "xlsx-js-style";

import Axios from 'axios'
// import * as FileSaver from "file-saver";
// import docxtemplater from 'docxtemplater'
// import PizZip from 'pizzip'
// import JSZipUtils from 'jszip-utils'
// import * as FileSaver from "file-saver";
require('script-loader!file-saver');
require('./Blob.js');
require('script-loader!xlsx/dist/xlsx.core.min');

function generateArray(table) {
    var out = [];
    var rows = table.querySelectorAll('tr');
    var ranges = [];
    for (var R = 0; R < rows.length; ++R) {
        var outRow = [];
        var row = rows[R];
        var columns = row.querySelectorAll('td');
        for (var C = 0; C < columns.length; ++C) {
            var cell = columns[C];
            var colspan = cell.getAttribute('colspan');
            var rowspan = cell.getAttribute('rowspan');
            var cellValue = cell.innerText;
            if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;

            //Skip ranges
            ranges.forEach(function (range) {
                if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
                    for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
                }
            });

            //Handle Row Span
            if (rowspan || colspan) {
                rowspan = rowspan || 1;
                colspan = colspan || 1;
                ranges.push({
                    s: {
                        r: R,
                        c: outRow.length
                    },
                    e: {
                        r: R + rowspan - 1,
                        c: outRow.length + colspan - 1
                    }
                });
            };

            outRow.push(cellValue !== "" ? cellValue : null);
            if (colspan)
                for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
        }
        out.push(outRow);
    }
    return [out, ranges];
};

function datenum(v, date1904) {
    if (date1904) v += 1462;
    var epoch = Date.parse(v);
    return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
    var ws = {};
    var range = {
        s: {
            c: 10000000,
            r: 10000000
        },
        e: {
            c: 0,
            r: 0
        }
    };
    for (var R = 0; R != data.length; ++R) {
        for (var C = 0; C != data[R].length; ++C) {
            if (range.s.r > R) range.s.r = R;
            if (range.s.c > C) range.s.c = C;
            if (range.e.r < R) range.e.r = R;
            if (range.e.c < C) range.e.c = C;
            var cell = {
                v: data[R][C]
            };
            if (cell.v == null) continue;
            var cell_ref = XLSX.utils.encode_cell({
                c: C,
                r: R
            });

            if (typeof cell.v === 'number') cell.t = 'n';
            else if (typeof cell.v === 'boolean') cell.t = 'b';
            else if (cell.v instanceof Date) {
                cell.t = 'n';
                cell.z = XLSX.SSF._table[14];
                cell.v = datenum(cell.v);
            } else cell.t = 's';

            ws[cell_ref] = cell;
        }
    }
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
}

function Workbook() {
    if (!(this instanceof Workbook)) return new Workbook();
    this.SheetNames = [];
    this.Sheets = {};
}



export function export_table_to_excel(id) {
    var theTable = document.getElementById(id);
    var oo = generateArray(theTable);
    var ranges = oo[1];

    /* original data */
    var data = oo[0];
    var ws_name = "SheetJS";
    var wb = new Workbook(),
        ws = sheet_from_array_of_arrays(data);

    /* add ranges to worksheet */
    // ws['!cols'] = ['apple', 'banan'];
    ws['!merges'] = ranges;

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary'
    });

    saveAs(new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
    }), "test.xlsx")
}


export function export_json_to_excel(th, jsonData, defaultTitle) {

    /* original data */

    var data = jsonData;
    data.unshift(th);
    var ws_name = "SheetJS";

    var wb = new Workbook(),
        ws = sheet_from_array_of_arrays(data);


    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary'
    });
    var title = defaultTitle || '列表'
    saveAs(new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
    }), title + ".xlsx")
}
// 处理请求返回信息
export function handleDownloadBlod(fileName, response) {
    const res = response.data
    if (res.type === 'application/json') {
        const reader = new FileReader()
        reader.readAsText(response.data, 'utf-8')
        reader.onload = function () {
            const { msg } = JSON.parse(reader.result)
            notification.error({
                message: '下载失败',
                description: msg
            })
        }
    } else {
        exportBlod(fileName, res)
    }
}

// 导出Excel

export function exportBlod(fileName, data) {
    const blob = new Blob([data])
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
}
//导出xlsx
export function exportXlsx(titleData, tableData, tableTitle, tablename, sheetName = '', merges = []) {
    if (titleData && tableData) {
        tableData.unshift(titleData)
    }
    const list = tableData.length > 0 ? tableData.map((item) => {
        const obj = {};
        for (const k in item) {
            if (titleData[k]) {
                obj[titleData[k]] = item[k]
            }
        }
        return obj;
    }) : []
    //表格大标题
    // const one = ['考试成绩']
    // const oneobj = {}
    let title = tableTitle ? tableTitle : tablename.split('.')[0]
    list.unshift({ title: title })
    //创建表
    const wb = XLSXST.utils.book_new();
    const data = XLSXST.utils.json_to_sheet(list, { skipHeader: true });
    let count = Object.keys(titleData).length + 1;
    data['!cols'] = []
    for (let i = 0; i < count; i++) {
        //表格列宽
        data['!cols'].push({ wpx: 200 })
    }
    data['!cols'].unshift({ wpx: 0 })
    data['!ref'] = `A1:AI${tableData.length + 1}`;
    // data['!cols'] = cols; // 设置列宽信息到工作表
    for (const key in data) {
        if (data[key] instanceof Object) {
            data[key].s = {
                alignment: {
                    vertical: 'center',
                    horizontal: 'center',
                    indent: 0,
                    wrapText: true
                },
                font: {
                    name: '宋体',
                    sz: 10,
                    color: { rgb: '#FF000000' },
                    bold: false,
                    italic: false,
                    underline: false
                },
                border: {
                    top: { style: 'thin' },
                    bottom: { style: 'thin' },
                    left: { style: 'thin' },
                    right: { style: 'thin' }
                }
            }
            if (key === 'A1') {
                data[key].s.font.sz = 16;
            }
            if (key === 'A2') {
                worksheet[key].s.alignment.horizontal = 'left';
            }

        }
    }

    // 合并单元格
    data['!merges'] = []
    data['!merges'].push({ s: { r: 0, c: 0 }, e: { r: 0, c: count - 1 } })
    if (merges) {
        if (merges.length > 0) {
            if (!data['!merges']) data['!merges'] = []
            merges.forEach(item => {
                data['!merges'].push(XLSXST.utils.decode_range(item))
            })
        }
    }
    // 将工作表添加到工作簿中
    XLSXST.utils.book_append_sheet(wb, data, sheetName ? sheetName : 'data')
    const excelBuffer = XLSXST.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    saveAs(blob, tablename);
    // XLSX.writeFile(wb, tablename)
}


/**
 * 导出 PDF
 * @param{*} id demo ID
 * @param{*} name 文件名
 */
export const downloadPDF = (id, name = '导出文件') => {
    const html = document.getElementById(id);
    var opt = {
        margin: 1,
        filename: name + '.pdf',
        image: {
            type: 'jpeg',
            quality: 0.98
        },
        html2canvas: {
            scale: 2,
            useCoRs: true
        },
        jsPDF: {
            unit: 'in',
            format: 'letter',
            orientation: "portrait"
        },
        pagebreak: {
            mode: "avoid-all"
        }

    }
    html2pdf().set(opt).from(html).save();
    return true
}
/**
* 导出word文档
 * val-- - 导出的内容
* id--导出盒子的id 
* mz--导出文件的名字
*/
import { asBlob } from "html-docx-js-typescript";

export function exportwordFn(id, mz) {
    let name = mz;
    let element = document.getElementById(id)
    var html = element.innerHTML;// 将图片转base64,这样word就能显示图片信息了 ...
    var cssstyle = window.getComputedStyle(element);
    let contentHtml = html
    let content = `
    < !DOCTYPE html> <html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style>
    ${cssstyle}
    </style>
    </head>
        <body>
            <div>
                ${contentHtml}
                     </div>
                     </body>
                     </htm1> `;
    //方法一
    // asBlob(content).then((data) => {
    //     // FileSaver.saveAs(data, name + "docx")
    //     saveAs(data, `${name}.docx`);
    // })
    //方法二
    const converted = htmlDocx.asBlob(content);

    // 使用 file-saver 保存 Blob 对象为 Word 文档文件
    FileSaver.saveAs(converted, `${name}.docx`);

    //方法三
    // let converted = htmlDocx.asBlob(content);
    // const link = document.createElement('a');
    // link.href = URL.createObjectURL(converted);
    // link.download = `${name}.docx`;
    // link.click();




}
//下载图片
export function downloadImg(url, name) {
    fetch(url)
        .then(res => {
            res.blob().then(blob => {
                let a = document.createElement('a');
                let url = window.URL.createObjectURL(blob);
                let filename = name || '图片.jpg'
                a.href = url;
                a.download = filename
                a.click()
                window.URL.revokeObjectURL(url);
            })
        })
}


//上传excel转成数组
export async function importExcel(url) {
    let res = await Axios.get(url, { responseType: 'arraybuffer' })
    const data = new Uint8Array(res.data);
    const workbook = XLSX.read(data, { type: 'array' });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const result = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
    // 获取属性名数组
    let keys = result[0];

    // 将属性名数组和数据数组转换为对象数组
    // let arr = result.slice(1).map(row => {
    //     let obj = {};
    //     keys.forEach((key, index) => {
    //         obj[key] = row[index];
    //     });
    //     return obj;

    // });
    return result
}
/**
 * 导出xlsx
 * @param {*} idSelector dome
 * @param {*} fileName 文件名
 * @param {*} titleNum
 * @returns
 */
export function exportXlsxs(idSelector, fileName, titleNum = 1) {
    // 设置导出的内容是否只做解析，不进行格式转换     false：要解析， true:不解析
    const xlsxParam = { raw: true };
    let table = document.querySelector(idSelector).cloneNode(true);

    // 因为element-ui的表格的fixed属性导致多出一个table，会下载重复内容，这里删除掉
    if (table.querySelector(".el-table__fixed-right"))
        table.removeChild(table.querySelector(".el-table__fixed-right"));
    if (table.querySelector(".el-table__fixed"))
        table.removeChild(table.querySelector(".el-table__fixed"));

    const wb = XLSX.utils.table_to_book(table, xlsxParam);
    let range = XLSX.utils.decode_range(wb.Sheets["Sheet1"]["!ref"]);
    let cWidth = [];
    for (let C = range.s.c; C < range.e.c; ++C) {
        //SHEET列
        let len = 100; //默认列宽
        let len_max = 400; //最大列宽
        for (let R = range.s.r; R <= range.e.r; ++R) {
            //SHEET行
            let cell = { c: C, r: R }; //二维 列行确定一个单元格
            let cell_ref = XLSX.utils.encode_cell(cell); //单元格 A1、A2
            if (wb.Sheets["Sheet1"][cell_ref]) {
                // if (R == 0){
                if (R < titleNum) {
                    wb.Sheets["Sheet1"][cell_ref].s = {
                        //设置第一行单元格的样式 style
                        alignment: {
                            horizontal: "center",
                            vertical: "center"
                        }
                    };
                } else {
                    wb.Sheets["Sheet1"][cell_ref].s = {
                        alignment: {
                            horizontal: "center",
                            vertical: "center"
                        }
                    };
                }
                //动态自适应：计算列宽
                let va = JSON.parse(JSON.stringify(wb.Sheets["Sheet1"][cell_ref].v));
                var card1 = JSON.parse(JSON.stringify(va)).match(/[\u4e00-\u9fa5]/g); //匹配中文
                var card11 = "";
                if (card1) {
                    card11 = card1.join("");
                }
                var card2 = JSON.parse(JSON.stringify(va)).replace(
                    /([^\u0000-\u00FF])/g,
                    ""
                ); //剔除中文
                let st = 0;
                if (card11) {
                    // st += card11.length * 16  //中文字节码长度
                    st += card11.length * 20; //中文字节码长度
                }
                if (card2) {
                    // st += card2.length * 8  //非中文字节码长度
                    st += card2.length * 10; //非中文字节码长度
                }
                if (st > len) {
                    len = st;
                }
            }
        }
        if (len > len_max) {
            //最大宽度
            len = len_max;
        }

        cWidth.push({ wpx: len }); //列宽
    }
    wb.Sheets["Sheet1"]["!cols"] = cWidth;
    const wbout = XLSXStyle.write(wb, {
        bookType: "xlsx",
        bookSST: false,
        type: "binary"
    });
    try {
        saveAs(new Blob([s2ab(wbout)], { type: "" }), `${fileName}.xlsx`);
    } catch (e) {
        if (typeof console !== "undefined") {
            console.log(e, wbout);
        }
    }
    return wbout;
}
//处理文件
function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
}

// 辅助函数，用于将给定的数据转换为适合添加到工作表的格式，并设置样式、列宽、合并单元格等相关操作
/**
 * 创建工作表数据
 * @param {*} titleData 标题数据
 * @param {*} tableData 表格数据
 * @param {*} tableTitle 表格标题
 * @param {*} sheetName 表名
 * @param {*} merges 合并单元格
 * @returns 
 */
function createSheetData(titleData, tableData, tableTitle, sheetName, merges, tips, rules) {
    merges = JSON.parse(JSON.stringify(merges));
    tableData = JSON.parse(JSON.stringify(tableData));
    titleData = JSON.parse(JSON.stringify(titleData));
    // if (titleData && tableData) {
    //     tableData.unshift(titleData);
    // }
    let tipsData = tips;
    let rulesData = rules;
    // 添加标题
    if (titleData && tableData) {
        titleData = titleData.reverse()
        titleData.forEach(item => {
            tableData.unshift(item);
        })
    }
    let tableHeader = titleData[0];
    // 添加规则
    if (rulesData && tableData) {
        tableData.unshift(rulesData);
    }
    const list = tableData.length > 0 ? tableData.map((item) => {
        Object.keys(tableHeader).forEach(key => {
            if (!item[key] && item[key] !== 0) {
                item[key] = ''
            }
        })
        const obj = {};
        for (const k in tableHeader) {
            // item[k] = item[k] === 0 ? '0' : item[k];
            // item[k] = item[k] == undefined ? '' : item[k];
            if (k && tableHeader[k]) {
                obj[k] = item[k];
            }
        }
        return obj;
    }) : [];


    // 添加提示
    if (tipsData) {
        list.unshift({ title: tipsData });
    }
    // let title = tableTitle ? tableTitle : sheetName.split('.')[0];
    // list.unshift({ title: title });
    const data = XLSXST.utils.json_to_sheet(list, { skipHeader: true });
    const count = Object.keys(tableHeader).length + 1;
    data['!cols'] = [];
    for (let i = 0; i < count; i++) {
        data['!cols'].push({ wpx: 160 });
    }
    data['!cols'].unshift({ wpx: 0 });
    data['!rows'] = [];
    for (let i = 0; i < tableData.length + 2; i++) {
        if (i === 0) {
            data['!rows'].push({ hpx: 140 });
        } else if (i === 1) {
            data['!rows'].push({ hpx: 30 });
        } else if (i === 2) {
            data['!rows'].push({ hpx: 40 });
        } else if (i === 3) {
            data['!rows'].push({ hpx: titleData.length > 1 ? 40 : 20 });
        } else if (i === 4) {
            data['!rows'].push({ hpx: titleData.length > 2 ? 40 : 20 });
        } else if (i === 5) {
            data['!rows'].push({ hpx: titleData.length > 3 ? 40 : 20 });
        } else {
            data['!rows'].push({ hpx: 20 });
        }
    }
    data['!ref'] = `A1:AI${tableData.length + 1}`;
    for (const key in data) {
        if (data[key] instanceof Object) {
            data[key].s = {
                alignment: {
                    vertical: 'center',
                    horizontal: 'center',
                    indent: 0,
                    wrapText: true
                },
                font: {
                    name: '微软雅黑',
                    sz: 10,
                    color: { rgb: '#2f75b500' },
                    bold: false,
                    italic: false,
                    underline: false
                },
                border: {
                    top: { style: 'thin' },
                    bottom: { style: 'thin' },
                    left: { style: 'thin' },
                    right: { style: 'thin' }
                }
            };
            // tips
            if (key === 'A1') {

                data[key].s.font.color = { rgb: '#000000' };
                data[key].s.alignment.horizontal = 'left';

                // 设置高度
                // data[key].h = 200;
            }
            // 所有第二行 规则行
            if (/^[A-Z]{1,3}2$/.test(key)) {
                data[key].s.font.color.rgb = '#2f75b5';
                // data[key].s.font.bold = true;
                data[key].s.alignment.horizontal = 'left';
            }
            // 第三行 表头
            if (/^[A-Z]{1,3}3$/.test(key)) {
                data[key].s.font.bold = true;
                data[key].s.font.sz = 12;
            }
            // 第四行 且是表头
            if (titleData.length > 1 && /^[A-Z]{1,3}4$/.test(key)) {
                data[key].s.font.bold = true;
                data[key].s.font.sz = 12;
            }
            // 第五行设置 且是表头
            if (titleData.length > 2 && /^[A-Z]{1,3}5$/.test(key)) {
                data[key].s.font.bold = true;
                data[key].s.font.sz = 12;
            }
            // 第六行设置 且是表头
            if (titleData.length > 3 && /^[A-Z]{1,3}6$/.test(key)) {
                data[key].s.font.bold = true;
                data[key].s.font.sz = 12;
            }

            // table 行
            // if (key === 'A3') {
            //     data[key].s.font.sz = 16;
            //     // data[key].s.font.bold = true;
            // }
        }
    }
    data['!merges'] = [];
    data['!merges'].push({ s: { r: 0, c: 0 }, e: { r: 0, c: count - 1 } });

    if (merges) {
        if (merges.length > 0) {
            if (!data['!merges']) {
                data['!merges'] = [];
            } else {
                merges.forEach(item => {
                    data['!merges'].push(item);
                });
            }

        }
    }
    return data;
}
function createBaseData(baseData) {

    let baseArray = []
    baseArray.push({ left: baseData.content, center: '', right: '' });
    baseArray.push({ left: '填报单位', center: baseData.orgName || '', right: '可以不填写，系统会根据导入账号识别' });
    const data = XLSXST.utils.json_to_sheet(baseArray, { skipHeader: true });

    data['!cols'] = [];
    for (let i = 0; i < 2; i++) {
        data['!cols'].push({ wpx: 160 });
    }
    // data['!cols'].unshift({ wpx: 0 });
    data['!merges'] = [];
    data['!merges'].push({ s: { r: 0, c: 0 }, e: { r: 0, c: 1 } });

    for (const key in data) {
        if (data[key] instanceof Object) {
            data[key].s = {
                alignment: {
                    vertical: 'top',
                    horizontal: 'left',
                    indent: 0,
                    wrapText: true
                },
                font: {
                    name: '宋体',
                    sz: 10,
                    color: { rgb: '#FF000000' },
                    bold: false,
                    italic: false,
                    underline: false
                },
                border: {
                    top: { style: 'thin' },
                    bottom: { style: 'thin' },
                    left: { style: 'thin' },
                    right: { style: 'thin' }
                }
            };
            // // tips
            // if (key === 'A1') {

            //     data[key].s.font.color = { rgb: '#000000' };
            //     data[key].s.alignment.horizontal = 'left';

            //     // 设置高度
            //     // data[key].h = 200;
            // }
            // // 所有第二行颜色为 #2f75b5
            // if (/^[A-Z]{1,3}2$/.test(key)) {
            //     data[key].s.font.color = { rgb: '#2f75b5' };
            //     data[key].s.alignment.horizontal = 'left';
            // }
            // // 第三行设置为灰色
            // if (/^[A-Z]{1,3}3$/.test(key)) {
            //     data[key].s.font.bold = true;
            // }
            // // table 行
            // // if (key === 'A3') {
            // //     data[key].s.font.sz = 16;
            // //     // data[key].s.font.bold = true;
            // // }
        }
    }
    data['!rows'] = [];
    data['!rows'].push({ hpx: 140 });
    data['!rows'].push({ hpx: 100 });
    return data;
}
function createDictData(dict, dictHeader) {

    let dictData = [];
    let obj = {};
    let lastLength = 0;
    dict.forEach(item => {
        // 
        // let data = item.data
        const title = item.title;
        // const isNOr
        let valArr = item.data?.value || item.data
        valArr = Array.isArray(valArr) ? valArr : []
        if (valArr.length > lastLength) {
            lastLength = valArr.length;
        }
        let currTableArr = [];
        currTableArr.push(title)
        valArr.forEach(item2 => {
            currTableArr.push(item2.label)
        })
        dictData[dictData.length] = currTableArr
    });
    // 将dictData转换为sheetData 
    // 列表翻转下 由 列 变成 行
    // 由 [
    //     ['性别','男','女'],
    //     ['职业','教师','医生'],
    // ]
    // 变成
    // [
    //     {'性别':'男','职业':'教师'},
    //     {'性别':'女','职业':'医生'},
    // ]
    let sheetData = [];
    for (let i = 0; i < lastLength + 1; i++) {
        let obj = {};
        for (let j = 0; j < dictData.length; j++) {
            let currKey = dictData[j][0];
            obj['x_' + j + currKey] = dictData[j][i] || '';
        }
        sheetData.push(obj)
    }
    let header = {};
    if (dictHeader?.content?.length > 0) {
        dictHeader.content.forEach((item, index) => {
            header[dictData[0][index]] = item
        })
        sheetData.unshift(header)
    }
    const data = XLSXST.utils.json_to_sheet(sheetData, { skipHeader: true });
    data['!merges'] = [];
    if (dictHeader?.merges?.length > 0) {
        dictHeader.merges.forEach(item => {
            data['!merges'].push(item);
        });
    }
    data['!cols'] = [];
    for (let i = 0; i < dict.length; i++) {
        data['!cols'].push({ wpx: 120 });
    }
    return data;
}
function createotherSheetData(titleData, tableData, tableTitle, sheetName, merges, tips, rules) {
    merges = JSON.parse(JSON.stringify(merges));
    tableData = JSON.parse(JSON.stringify(tableData));
    titleData = JSON.parse(JSON.stringify(titleData));
    // if (titleData && tableData) {
    //     tableData.unshift(titleData);
    // }
    // let tipsData = tips;
    let rulesData = rules;
    // 添加标题
    if (titleData && tableData) {
        titleData = titleData.reverse()
        titleData.forEach(item => {
            tableData.unshift(item);
        })
    }
    let tableHeader = titleData[0];
    // 添加规则
    if (rulesData && tableData) {
        tableData.unshift(rulesData);
    }
    const list = tableData.length > 0 ? tableData.map((item) => {
        Object.keys(tableHeader).forEach(key => {
            if (!item[key] && item[key] !== 0) {
                item[key] = ''
            }
        })
        const obj = {};
        for (const k in tableHeader) {
            // item[k] = item[k] === 0 ? '0' : item[k];
            // item[k] = item[k] == undefined ? '' : item[k];
            if (k && tableHeader[k]) {
                obj[k] = item[k];
            }
        }
        return obj;
    }) : [];


    // 添加提示
    // if (tipsData) {
    //     list.unshift({ title: tipsData });
    // }
    // let title = tableTitle ? tableTitle : sheetName.split('.')[0];
    // list.unshift({ title: title });
    const data = XLSXST.utils.json_to_sheet(list, { skipHeader: true });
    const count = Object.keys(tableHeader).length + 1;
    // data['!cols'] = [];
    // for (let i = 0; i < count; i++) {
    //     data['!cols'].push({ wpx: 160 });
    // }
    // data['!cols'].unshift({ wpx: 0 });
    // data['!rows'] = [];
    // for (let i = 0; i < tableData.length + 2; i++) {
    //     if (i === 0) {
    //         data['!rows'].push({ hpx: 140 });
    //     } else if (i === 1) {
    //         data['!rows'].push({ hpx: 30 });
    //     } else if (i === 2) {
    //         data['!rows'].push({ hpx: 40 });
    //     } else if (i === 3) {
    //         data['!rows'].push({ hpx: titleData.length > 1 ? 40 : 20 });
    //     } else if (i === 4) {
    //         data['!rows'].push({ hpx: titleData.length > 2 ? 40 : 20 });
    //     } else if (i === 5) {
    //         data['!rows'].push({ hpx: titleData.length > 3 ? 40 : 20 });
    //     } else {
    //         data['!rows'].push({ hpx: 20 });
    //     }
    // }
    // data['!ref'] = `A1:AI${tableData.length + 1}`;
    for (const key in data) {
        if (data[key] instanceof Object) {
            data[key].s = {
                alignment: {
                    vertical: 'center',
                    horizontal: 'center',
                    indent: 0,
                    wrapText: true
                },
                font: {
                    name: '微软雅黑',
                    sz: 10,
                    color: { rgb: '#2f75b500' },
                    bold: false,
                    italic: false,
                    underline: false
                },
                border: {
                    top: { style: 'thin' },
                    bottom: { style: 'thin' },
                    left: { style: 'thin' },
                    right: { style: 'thin' }
                }
            };
            // tips
            // if (key === 'A1') {
            //     data[key].s.font.color = { rgb: '#000000' };
            //     data[key].s.alignment.horizontal = 'left';
            //     // 设置高度
            //     // data[key].h = 200;
            // }
            // // 所有第二行 规则行
            // if (/^[A-Z]{1,3}2$/.test(key)) {
            //     data[key].s.font.color.rgb = '#2f75b5';
            //     // data[key].s.font.bold = true;
            //     data[key].s.alignment.horizontal = 'left';
            // }
            // 第三行 表头
            if (/^[A-Z]{1,3}3$/.test(key)) {
                data[key].s.font.bold = true;
                data[key].s.font.sz = 12;
            }
            // 第四行 且是表头
            if (titleData.length > 1 && /^[A-Z]{1,3}4$/.test(key)) {
                data[key].s.font.bold = true;
                data[key].s.font.sz = 12;
            }
            // 第五行设置 且是表头
            if (titleData.length > 2 && /^[A-Z]{1,3}5$/.test(key)) {
                data[key].s.font.bold = true;
                data[key].s.font.sz = 12;
            }
            // 第六行设置 且是表头
            if (titleData.length > 3 && /^[A-Z]{1,3}6$/.test(key)) {
                data[key].s.font.bold = true;
                data[key].s.font.sz = 12;
            }

            // table 行
            // if (key === 'A3') {
            //     data[key].s.font.sz = 16;
            //     // data[key].s.font.bold = true;
            // }
        }
    }
    data['!merges'] = [];
    data['!merges'].push({ s: { r: 0, c: 0 }, e: { r: 0, c: count - 1 } });

    if (merges) {
        if (merges.length > 0) {
            if (!data['!merges']) {
                data['!merges'] = [];
            } else {
                merges.forEach(item => {
                    data['!merges'].push(item);
                });
            }

        }
    }
    return data;
}
/**
 * 导出xlsx
 * @param {*} {tablename, sheetArray}
 * sheetArray: [{titleData, tableData, tableTitle, sheetName, merges, tips}]
 * 
 */
export function exportXlsx2({ tablename, baseData, tableObj, dict, dictHeader, othertable }) {
    const wb = XLSXST.utils.book_new();
    // 遍历每个sheet对应的相关数据，创建sheet并添加到工作簿中

    const titleData = tableObj.titleData;
    const tableData = tableObj.tableData;
    const tableTitle = tableObj.tableTitle;
    const sheetName = tableObj.sheetName || `sheet`;
    const merges = tableObj.merges || [];
    const tips = tableObj.tips || '';
    const rules = tableObj.rules || {};
    const sheetData = createSheetData(titleData, tableData, tableTitle, sheetName, merges, tips, rules);

    // 添加基础数据
    if (baseData) {
        XLSXST.utils.book_append_sheet(wb, createBaseData(baseData), '填报基础数据');
    }
    // 添加表格数据
    XLSXST.utils.book_append_sheet(wb, sheetData, sheetName);
    // 添加字典数据
    if (dict) {
        XLSXST.utils.book_append_sheet(wb, createDictData(dict, dictHeader), '枚举字典(请勿删除)');
    }
    if (othertable) {
        const otherttitleData = othertable.titleData;
        const otherttableData = othertable.tableData;
        const otherttableTitle = othertable.tableTitle;
        const othertsheetName = othertable.sheetName || `sheet`;
        const othertmerges = othertable.merges || [];
        const otherttips = othertable.tips || '';
        const othertrules = othertable.rules || {};
        const othertsheetData = createotherSheetData(otherttitleData, otherttableData, otherttableTitle, othertsheetName, othertmerges, otherttips, othertrules);
        XLSXST.utils.book_append_sheet(wb, othertsheetData, othertsheetName);
    }
    const excelBuffer = XLSXST.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    saveAs(blob, tablename);
}
