const mongoose = require('mongoose');
const uuidV1 = require('uuid/v1');

const priceInfoClassModel = mongoose.model('infoPriceClass');


// 旧数据没有ID，初次加载需要给数据加上ID
const setIDForData = async () => {
    const item = await priceInfoClassModel.findOne({}).lean();
    if (!item || item.ID) {
        return;
    }
    const bulks = [];
    const items = await priceInfoClassModel.find({}, '-_id class ID').lean();
    items.forEach(item => {
        if (!item.ID) {
            bulks.push({
                updateOne: {
                    filter: { class: item.class },
                    update: { $set: { ID: uuidV1() } }
                }
            });
        }
    });
    if (bulks.length) {
        await priceInfoClassModel.bulkWrite(bulks);
    }
}


// 获取分页数据
const getPagingData = async (page, pageSize, searchStr) => {
    let query = {};
    if (searchStr) {
        const nameReg = new RegExp(searchStr);
        query = {
            $or: [{ classCode: searchStr }, { name: { $regex: nameReg } }]
        }
    }
    const totalCount = await priceInfoClassModel.count(query);
    const items = await priceInfoClassModel.find(query).lean().sort({ class: -1 }).skip(page * pageSize).limit(pageSize);
    return { items, totalCount };
}

const UpdateType = {
    UPDATE: 'update',
    DELETE: 'delete',
    CREATE: 'create',
};

// 编辑表格
async function editClassData(postData) {
    const classList = [];
    const bulks = [];
    postData.forEach(data => {
        if (data.data && data.data.class) {
            classList.push(data.data.class);
        }
        if (data.type === UpdateType.UPDATE) {
            bulks.push({
                updateOne: {
                    filter: { ID: data.ID },
                    update: { ...data.data }
                }
            });
        } else if (data.type === UpdateType.DELETE) {
            bulks.push({
                deleteOne: {
                    filter: { ID: data.ID }
                }
            });
        } else {
            bulks.push({
                insertOne: {
                    document: data.data
                }
            });
        }
    });

    if (classList.length) {
        const classItems = await priceInfoClassModel.find({ class: { $in: classList } }, '-_id class').lean();
        if (classItems) {
            const existClassList = [];
            const classMap = {};
            classItems.forEach(item => {
                classMap[item.class] = 1;
            });
            classList.forEach(classVal => {
                if (classMap[classVal]) {
                    existClassList.push(classVal);
                }
            });
            if (existClassList.length) {
                throw new Error(`类别${existClassList.join('，')}，已存在。`)
            }
        }
    }

    if (bulks.length) {
        await priceInfoClassModel.bulkWrite(bulks);
    }
}

// 导出excel数据
async function exportExcelData() {
    const items = await priceInfoClassModel.find({}).sort({ class: 1 }).lean();
    // 整理数据
    let classData = [];
    for (const tmp of items) {
        const item = [tmp.class || '', tmp.classCode || '', tmp.code || '', tmp.name || '', tmp.specs || '', tmp.unit || ''];
        classData.push(item);
    }
    const excelData = [['class', '别名编码', '编码', '材料名称', '规格型号', '单位']];
    excelData.push.apply(excelData, classData);

    return excelData;
}


module.exports = {
    setIDForData,
    getPagingData,
    editClassData,
    exportExcelData
}