'use strict';
const fs = require('fs');
const xlsx = require('better-xlsx');
const path = require('path')
const moment = require('moment')


module.exports = function (app, opts) {

    //递归创建目录 同步方法  
    async function makeDir(dir) {
        if (!fs.existsSync(dir)) {
            makeDir(path.dirname(dir))
            fs.mkdirSync(dir, function (err) {
                if (err) {
                    throw err
                }
            });
        }
    }

    async function simpleExcelDown({ data = [], header = [], fileName = moment().format('YYYY-MM-DD HH:mm:ss'), needIndexCell = true } = {}) {
        const fileDirPath = path.join(__dirname, `../../downloadFiles`)
        makeDir(fileDirPath)
        const file = new xlsx.File();
        const sheet_1 = file.addSheet('sheet_1');

        // header
        const headerStyle = new xlsx.Style();
        headerStyle.align.h = 'center';
        headerStyle.align.v = 'center';
        headerStyle.border.right = 'thin';
        headerStyle.border.rightColor = '#000000';
        headerStyle.border.bottom = 'thin';
        headerStyle.border.bottomColor = '#000000';

        const headerRow = sheet_1.addRow();
        if (needIndexCell) {
            const indexCell = headerRow.addCell();
            indexCell.value = '序号'
            indexCell.style = headerStyle
        }
        for (let h of header) {
            const cell = headerRow.addCell();
            cell.value = h.title;
            cell.style = headerStyle
        }

        // data
        const style = new xlsx.Style();
        style.align.h = 'left';
        style.align.v = 'center';
        style.border.right = 'thin';
        style.border.rightColor = '#000000';
        style.border.bottom = 'thin';
        style.border.bottomColor = '#000000';
        for (let i = 0; i < data.length; i++) {
            const row = sheet_1.addRow();
            if (needIndexCell) {
                const indexCell = row.addCell();
                indexCell.value = i + 1
                indexCell.style = headerStyle
            }
            for (let h of header) {
                const cell = row.addCell();
                cell.value = data[i][h.key] || h.defaultValue || '-';
                cell.style = style
            }
        }

        const savePath = path.join(fileDirPath, fileName)
        await new Promise(function (resolve, reject) {
            file.saveAs()
                .pipe(fs.createWriteStream(savePath))
                .on('finish', () => {
                    resolve()
                });
        })
        return savePath
    }

    return {
        simpleExcelDown,
        makeDir
    }
}