import BaseController from "../../common/base/base_controller";
const facade = require('../facade/index');
const config = require("../../../config/config.js");
const excel = require('node-xlsx');
const fs = require('fs');

class PriceInfoClassController extends BaseController {
    async main(req, res) {
        const renderData = {
            title: '材料信息价类别总表',
            userAccount: req.session.managerData.username,
            userID: req.session.managerData.userID,
            LicenseKey: config.getLicenseKey(process.env.NODE_ENV),
        };
        await facade.setIDForData();
        res.render("maintain/price_info_class/html/main.html", renderData);
    }

    // 获取分页数据
    async getPagingData(req, res) {
        try {
            const { page, pageSize, searchStr } = JSON.parse(req.body.data);
            const data = await facade.getPagingData(page, pageSize, searchStr);
            res.json({ error: 0, message: 'getData success', data });
        } catch (err) {
            console.log(err);
        }
    }

    // 编辑
    async editClassData(req, res) {
        try {
            const { postData } = JSON.parse(req.body.data);
            await facade.editClassData(postData);
            res.json({ error: 0, message: 'editPrice success' });
        } catch (err) {
            console.log(err);
            res.json({ error: 1, message: err.toString() });
        }
    }

    async exportClassData(request, response) {
        try {
            const excelData = await facade.exportExcelData();
            const buffer = excel.build([{ name: "材料信息价类别总表", data: excelData }]);
            const filePath = './public/exportPriceClass.xlsx';
            fs.writeFileSync(filePath, buffer, 'binary');
            const stats = fs.statSync(filePath);
            // 下载相关header
            response.set({
                'Content-Type': 'application/octet-stream',
                'Content-Disposition': 'attachment; filename=infoPriceClass.xlsx',
                'Content-Length': stats.size
            });
            fs.createReadStream(filePath).pipe(response);
            fs.unlink(filePath);
        } catch (error) {
            response.end(error);
        }
    }


}

module.exports = {
    priceInfoClassController: new PriceInfoClassController()
};