const mongoose = require('mongoose');

const priceInfoSummaryModel = mongoose.model('std_price_info_summary');

const axios = require('axios');

const axiosInstance = axios.create({
    baseURL: 'http://112.74.42.187:26909/api/',
    timeout: 60000 * 5,
});

// 获取所有数据
const getData = async () => {
    const items = await priceInfoSummaryModel.find({}).lean();
    return items;
}


// 获取分页数据
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 priceInfoSummaryModel.count(query);
    const items = await priceInfoSummaryModel.find(query).lean().sort({ classCode: -1 }).skip(page * pageSize).limit(pageSize);
    return { items, totalCount };
}

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

// 编辑表格
async function editSummaryData(postData) {
    const bulks = [];
    postData.forEach(data => {
        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 (bulks.length) {
        await priceInfoSummaryModel.bulkWrite(bulks);
    }
}

// 保存至总表
async function saveInSummary(documents) {
    await priceInfoSummaryModel.insertMany(documents);
}

// ai匹配
async function aiMatch(listA, listB) {
    const url = '/material_sheet_match';
    const res = await axiosInstance.post(url, { list_a: listA, list_b: listB }, { timeout: 1000 * 60 * 5 });
    const resData = res.data;
    if (resData.errno) {
        throw new AppError('AI匹配失败');
    }
    return resData.data;
}

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

    return excelData;
}

module.exports = {
    getData,
    getPagingData,
    editSummaryData,
    saveInSummary,
    exportExcelData,
    aiMatch,
}