'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/5/7
 * @version
 */

const fs = require('fs');
const path = require('path');
const excel = require('node-xlsx');

module.exports = app => {
    class DealBillsController extends app.BaseController {

        /**
         * 获取标段的签约清单数据
         * @param ctx
         * @returns {Promise<void>}
         */
        async getData (ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (isNaN(tenderId) || tenderId <= 0) {
                    throw '参数错误';
                }

                responseData.data =  await ctx.service.dealBills.getAllDataByCondition({ where: {tender_id: tenderId} });
            } catch (error) {
                responseData.err = 1;
                responseData.msg = error.toString();
            }

            ctx.body = responseData;
        }

        /**
         * 导入Excel数据
         * @param ctx
         * @returns {Promise<void>}
         */
        async loadExcel (ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            let stream;
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (isNaN(tenderId) || tenderId <= 0) {
                    throw '参数错误';
                }

                stream = await ctx.getFileStream();
                const create_time = Date.parse(new Date())/1000;
                const fileInfo = path.parse(stream.filename);
                const fileName = this.app.baseDir + '/app/public/deal_bills/uploads/' + 'deal_bills' + create_time + fileInfo.ext;
                // 保存文件
                await ctx.helper.saveStreamFile(stream, fileName);
                // 读取文件
                const sheet = excel.parse(fileName);
                if (!sheet || sheet.length === 0 || sheet[0] === undefined || sheet[0].data === undefined) {
                    throw 'excel没有对应数据';
                }
                const result = await ctx.service.dealBills.importData(sheet[0], tenderId);
                if (!result) {
                    throw '导入数据失败';
                }

                responseData.data =  await this.ctx.service.dealBills.getAllDataByCondition({ where: {tender_id: tenderId} });
            } catch (err) {
                console.log(err);
                // 失败需要消耗掉stream 以防卡死
                if (stream) {
                    await sendToWormhole(stream);
                }
                this.setMessage(err.toString(), this.messageType.ERROR);
            }

            ctx.body = responseData;
        }

        /**
         * 下载模板文件
         * @param ctx
         * @returns {Promise<void>}
         */
        async download (ctx) {
            const file = ctx.params.file;
            if (file) {
                try {
                    let fileName;
                    if (file === 'template.xls') {
                        fileName = this.app.baseDir + '/app/public/deal_bills/deal_template.xls';
                    } else {
                        const tenderId = ctx.session.sessionUser.tenderId;
                        if (isNaN(tenderId) || data.tenderId <= 0) {
                            throw '参数错误';
                        }
                        const create_time = Date.parse(new Date())/1000;
                        fileName = this.app.baseDir + '/app/public/deal_bills/downloads/' + tenderId + '-' + create_time + '.xlsx';
                        // todo 导出签约清单Excel
                    }
                    ctx.body = await fs.readFileSync(fileName);
                } catch(err) {
                    console.log(err);
                }
            }
        }
    }

    return DealBillsController;
};