
import FileSaver from 'file-saver'
import { utils } from 'xlsx'

const commonStyle = {
    font: {
        name: '宋体', sz: 11, bold: false,
        color: {
            rgb: '000000'
        }
    },
    alignment: { horizontal: 'center', vertical: 'center', wrapText: false }
}

const titleStyle = {
    font: {
        name: '黑体', sz: 18, bold: false,
        color: {
            rgb: '000000'
        }
    },
    alignment: { horizontal: 'center', vertical: 'center', wrapText: false }
}

const headerStyle = {
    font: {
        name: '黑体', sz: 11, bold: false,
        color: {
            rgb: '000000'
        }
    },
    alignment: { horizontal: 'center', vertical: 'center', wrapText: false },
    border: {
        top: { style: 'thin' },
        bottom: { style: 'thin' },
        left: { style: 'thin' },
        right: { style: 'thin' }
    }
    // fill: {
    //   fgColor: { rgb: 'ebebeb' }// 设置标题单元格的背景颜色
    // }
}

const contentStyle = {
    font: { name: '宋体', sz: 11, bold: false },
    alignment: { horizontal: 'center', vertical: 'center', wrapText: false },
    border: {
        top: { style: 'thin' },
        bottom: { style: 'thin' },
        left: { style: 'thin' },
        right: { style: 'thin' }
    }
}

const redFont = {
    font: {
        name: '宋体', sz: 11, bold: false,
        color: {
            rgb: 'FF0000' // 十六进制，不带#
        }
    },
    alignment: { horizontal: 'left', vertical: 'center', wrapText: false }
}

/**
 * table数据导出execl文件
 * @param {*} id:table元素id
 * @param {*} fileName :导出文件名称
 */
function exportExecl(titleData, fileName, HEADERRANGE, TABLERANGE, REDRANGE = false) {
    let excelName = fileName || '导出表格.xlsx'
    const list = tableData.map((item) => {
        const obj = {};
        for (const k in item) {
            if (titleData[k]) {
                obj[titleData[k]] = item[k]
            }
        }
        return obj;
    })
    //创建表
    const wb = XLSX.utils.book_new();
    const data = XLSX.utils.json_to_sheet(list);
    // XLSX.utils.book_append_sheet(wb, data, 'data')
    // XLSX.writeFile(wb, tablename)
    var xlsxParam = { raw: false } // 导出数据是否未加工
    // let tables = document.getElementById(id)
    // if (!tables) return
    // tables = document.getElementById(id).cloneNode(true)
    // // 移除固定列，防止重复生成表格
    // if (tables.querySelector('.el-table__fixed') !== null) {
    //     tables.removeChild(tables.querySelector('.el-table__fixed'))
    // }
    // let table_book = utils.table_to_book(tables, xlsxParam)
    let table_book = data
    table_book.Sheets.Sheet1 = setTitleClass(table_book.Sheets.Sheet1)
    table_book.Sheets.Sheet1 = setCellStyle(table_book.Sheets.Sheet1, HEADERRANGE, headerStyle)
    table_book.Sheets.Sheet1 = setCellStyle(table_book.Sheets.Sheet1, TABLERANGE, contentStyle)
    if (REDRANGE) {
        table_book.Sheets.Sheet1 = setCellStyle(table_book.Sheets.Sheet1, REDRANGE, redFont)
    }
    table_book.Sheets.Sheet1 = addRangeBorder(table_book.Sheets.Sheet1['!merges'], table_book.Sheets.Sheet1) // 合并项添加边框

    var table_write = XLSX.write(table_book, {
        bookSST: false,
        type: 'binary',
        bookType: 'xlsx'
    })
    try {
        FileSaver.saveAs(
            new Blob([s2ab(table_write)], { type: 'application/octet-stream' }),
            excelName
        )
    } catch (e) {
        console.log(e, table_write)
    }
    return table_write
}
function setCellStyle(worksheet, range, RANGESTYLE) {
    const headerRange = utils.decode_range(range)
    for (let col = headerRange.s.c; col <= headerRange.e.c; col++) {
        for (let row = headerRange.s.r; row <= headerRange.e.r; row++) {
            const headerCell = utils.encode_cell({ r: row, c: col })
            if (worksheet[headerCell] != undefined) {
                worksheet[headerCell].s = RANGESTYLE
            }
        }
    }
    return worksheet
}

function setTitleClass(worksheet) {
    // title
    for (const key in worksheet) {
        if (key.indexOf('!') === -1 && worksheet[key].v) {
            if (key == 'A1') { // title
                worksheet[key].s = titleStyle
            } else {
                worksheet[key].s = commonStyle
            }
        }
    }
    return worksheet
}

// 为合并项添加边框
function addRangeBorder(range, ws) {
    let arr = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
    ]
    if (range) {
        range.forEach((item) => {
            let startColNumber = Number(item.s.r),
                endColNumber = Number(item.e.r);
            let startRowNumber = Number(item.s.c),
                endRowNumber = Number(item.e.c);
            const test = ws[arr[startRowNumber] + (startColNumber + 1)];
            for (let col = startColNumber; col <= endColNumber; col++) {
                for (let row = startRowNumber; row <= endRowNumber; row++) {
                    ws[arr[row] + (col + 1)] = test;
                }
            }
        });
    }
    return ws;
}

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
}

export default exportExecl

