import request from '../libs/request';
import lodop from '../libs/lodop';
import dateFormat from 'date-fns/format';
import saveAs from 'file-saver';

const res = 'DataSource';

export default {
    query(dataSource, filter) {
        return request({
            url: `api/${res}/query`,
            method: 'post',
            data: {
                ...filter,
                dataSource
            }
        });
    },
    async exportExcel(tableView, filter, path = 'query') {
        let data = {
            ...filter,
            per: 100000,
            returnType: 1,
            viewCode: tableView.code,
            dataSource: tableView.dataSource
        };

        const result = await request({
            url: `api/${res}/${path}`,
            method: 'post',
            responseType: 'blob',
            data
        });

        const blob = new Blob([result], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        saveAs(blob, tableView.name + '-' + dateFormat(new Date(), 'yyyyMMddHHmmss') + '.xlsx');
    },
    async exportPdf(tableView, filter, path = 'query') {
        let data = {
            ...filter,
            per: 100000,
            returnType: 3,
            viewCode: tableView.code,
            dataSource: tableView.dataSource
        };

        const result = await request({
            url: `api/${res}/${path}`,
            method: 'post',
            responseType: 'blob',
            data
        });

        const blob = new Blob([result], { type: 'application/pdf' });
        saveAs(blob, tableView.name + '-' + dateFormat(new Date(), 'yyyyMMddHHmmss') + '.pdf');
    },
    async printList(tableView, filter, landscape = true, path = 'query') {
        let LODOP;
        try {
            LODOP = lodop.getLodop();
        } catch (e) {
            alert('请检查打印驱动！' + e.message);
            return;
        }

        let data = {
            ...filter,
            per: 1000,
            returnType: 2,
            viewCode: tableView.code,
            dataSource: tableView.dataSource
        };

        const result = await request({
            url: `api/${res}/${path}`,
            method: 'post',
            data
        });

        LODOP.PRINT_INIT('Print');

        if (landscape) {
            LODOP.ADD_PRINT_TABLE('4%', '3%', '94%', '90%', result);
            LODOP.SET_PRINT_PAGESIZE(2, 0, 0, 'A4');
        } else {
            LODOP.ADD_PRINT_TABLE('4%', '3%', '94%', '90%', result);
            LODOP.SET_PRINT_PAGESIZE(1, 0, 0, 'A4');
        }
        LODOP.PRINTA();
    }
};
