const fs = require('fs-extra');
const path = require('path');

const getPageData = require('../../models/common/getPageData');
const Minute = require('../../models/minutes/minutes');
const Converter = require('../function/converter');
const File = require('../file/file');
const { RSA_NO_PADDING } = require('constants');

module.exports = {
    get: async (req, res, next) => {
        try {
            let minuteID = req.params.minuteid;
            const minuteData = await Minute.get(minuteID);
            if (!minuteData[0]) return res.status(401).json({ message: '查無此紀錄' });
            res.status(200).json({ message: '成功取得會議記錄', minuteData: minuteData[0] });
        } catch (err) {
            res.status(500).json(err);
        }
    },
    gets: async (req, res, next) => {
        try {
            let { currentPage, limit, order, searchQueries } = req.query;

            if (!currentPage || !limit || !order) return res.status(401).json({ message: 'No params!' });

            //對查詢條件進行處理
            if (!searchQueries) {
                searchQueries = null;
            } else {
                searchQueries = JSON.parse(searchQueries);
                searchQueries.keyWord = searchQueries.keyWord.split(' ');
            }

            //運算頁數
            const skip = (parseInt(currentPage) - 1) * parseInt(limit);
            //取得當前頁面資料
            const { totalPages, pageData } = await getPageData({
                skip,
                limit,
                order,
                searchQueries,
                table: 'meeting_records',
            });

            //取得檔案名稱
            const files = await pageData.map((data) => {
                let fileArr = [];
                fileArr.push(data.MEETING_DOC_NAME);
                if (data.MEETING_ATTACH_NAME) fileArr = fileArr.concat(data.MEETING_ATTACH_NAME.split(','));
                return { folder: data.MEETING_TITLE, files: fileArr };
                // const folderName = data.MEETING_TITLE;
                // return File.getFolder(folderName);
            });
            res.status(200).json({
                totalPages: totalPages,
                currentPage: currentPage,
                pageData: pageData,
                files: files,
            });
        } catch (err) {
            res.status(500).json(err);
        }
    },
    post: async (req, res, next) => {
        try {
            let { title, charperson, minute, venue, participant, tags, date, time } = req.body;
            let { filename: docFileName, path: filePath } = req.files.content[0];
            let { attach } = req.files;

            if (!title || !charperson || !minute || !venue || !participant || !date || !time)
                return res.status(401).json({ message: '缺少必要欄位' });

            let attachFilesName = attach
                ? attach.map((file) => {
                      return file.filename;
                  })
                : '';

            //將pdf轉成文字
            const minuteText = await Converter.pdf2text(filePath);

            //取得標題的中文次數，轉換為阿拉伯數字
            let number = title.substring(title.lastIndexOf('第') + 1, title.lastIndexOf('次'));
            number = Converter.text2Num(number);

            const minuteData = {
                title,
                number,
                charperson,
                minute,
                venue,
                participant,
                tags,
                date,
                time,
                minuteText,
                docFileName,
                attachFilesName,
            };
            //將data傳入DB
            await Minute.post(minuteData);
            res.status(200).json({ message: '新增成功', minuteData });
        } catch (err) {
            res.status(500).json(err);
        }
    },
    put: async (req, res, next) => {
        try {
            let { charperson, minute, venue, participant, tags, date, time, doc_name, attach_name } = req.body;
            const { minuteid } = req.params;
            const { content } = req.files;
            let minuteText = '';
            if (content) {
                //將pdf轉成文字
                let filePath = content[0].path;
                minuteText = await Converter.pdf2text(filePath);
            }
            attach_name = attach_name || '';

            const minuteData = {
                charperson,
                minute,
                venue,
                participant,
                tags,
                date,
                time,
                doc_name,
                attach_name,
                text: minuteText,
                minuteID: minuteid,
            };
            await Minute.put(minuteData);
            res.status(200).json({ message: '修改成功', minuteData });
        } catch (err) {
            res.status(500).json(err);
        }
    },
    delete: async (req, res, next) => {
        try {
            const { minuteid } = req.params;
            const minuteData = await Minute.get(minuteid);
            const deleteFolderPath = path.join(__dirname + `../../../minutesFiles/${minuteData[0].MEETING_TITLE}`);
            await Minute.delete(minuteid);
            // 判斷資料夾是否存在，有則刪除
            if (fs.existsSync(deleteFolderPath)) fs.removeSync(deleteFolderPath);
            res.status(200).json({ message: '刪除成功', minuteid });
        } catch (err) {
            res.status(500).json(err);
        }
    },
    getLatest: async (req, res, next) => {
        try {
            const minuteData = await Minute.get();
            let latestNum = parseInt(minuteData[0].MEETING_NUMBER);
            latestNum++;
            res.status(200).json({ number: Converter.num2Text(latestNum.toString()) });
        } catch (err) {
            res.status(500).json(err);
        }
    },
};
