'use strict';
const MONTH_CONVERSION = {
    one: 1,
    two: 2,
    three: 3,
    four: 4,
    five: 5,
    six: 6,
    seven: 7,
    eight: 8,
    nine: 9,
    ten: 10,
    eleven: 11,
    twelve: 12
}
// 查询业绩汇总表-->关联sale表
async function getSalePerformance(ctx, next) {
    const { type } = ctx.params;
    const models = ctx.fs.dc.models;
    let rslt = null;
    try {
        rslt = await models.sale.findAll({
            order: [['id', 'DESC']],
            include: [{
                model: models.salePerformance
            }]
        })
        ctx.status = 200
        ctx.body = rslt
    } catch (error) {
        ctx.fs.logger.error(`path:${ctx.path},error:${error}`)
        ctx.status = 400;
        ctx.body = { name: 'FindAllError', message: '获取失败' }
    }
}

async function importSalePerformance(ctx) {
    let errorMsg = { message: '导入业绩汇总失败' };
    const transaction = await ctx.fs.dc.orm.transaction();
    try {
        const models = ctx.fs.dc.models;
        const body = ctx.request.body;
        let importData = [];
        const imporNames = [];
        for (let item of body) {//循环捞数据
            const { name, ...rest } = item;
            const data = [];
            imporNames.push(name);
            Object.keys(rest).map(value => {
                if (MONTH_CONVERSION[value.replace("ActualPerformance", "")]) {
                    const index = data.findIndex(d => d.month == MONTH_CONVERSION[value.replace("ActualPerformance", "")]);
                    if (index > -1) {
                        data[index].actualPerformance = item[value];
                    } else {
                        data.push({
                            saleName: item.name,
                            month: MONTH_CONVERSION[value.replace("ActualPerformance", "")],
                            actualPerformance: item[value]
                        });
                    }
                } else if (MONTH_CONVERSION[value.replace("AssessmentPerformance", "")]) {
                    const index = data.findIndex(d => d.month == MONTH_CONVERSION[value.replace("AssessmentPerformance", "")]);
                    if (index > -1) {
                        data[index].assessmentPerformance = item[value];
                    } else {
                        data.push({
                            saleName: item.name,
                            month: MONTH_CONVERSION[value.replace("AssessmentPerformance", "")],
                            assessmentPerformance: item[value]
                        });
                    }
                } else if (MONTH_CONVERSION[value.replace("Task", "")]) {
                    const index = data.findIndex(d => d.month == MONTH_CONVERSION[value.replace("Task", "")]);
                    if (index > -1) {
                        data[index].task = item[value];
                    } else {
                        data.push({
                            saleName: item.name,
                            month: MONTH_CONVERSION[value.replace("Task", "")],
                            task: item[value]
                        });
                    }
                } else if (MONTH_CONVERSION[value.replace("Amount", "")]) {
                    const index = data.findIndex(d => d.month == MONTH_CONVERSION[value.replace("Amount", "")]);
                    if (index > -1) {
                        data[index].amount = item[value];
                    } else {
                        data.push({
                            saleName: item.name,
                            month: MONTH_CONVERSION[value.replace("Amount", "")],
                            amount: item[value]
                        });
                    }
                } else {

                }
            })
            if (data.length) {
                importData = importData.concat(data);
            }
        }

        /**查出历史数据进行比对
         * 1. 比对是否存在的月份+销售名称
         *    a. 存在:记录id(用于删除)
         *    b. 不存在,记录数据
         * 2. 批量删除记录的ids
         * 3. 批量插入导入数据
         * 
         * PS:库里的数据以导入的数据为准(如果历史数据task字段有值,导入的数据该字段为空,即库里的task为空值)
         */
        if (imporNames.length) {
            const delDataIds = [];
            const oldData = await models.salePerformance.findAll({
                //todo 待考虑加入年份比对
                where: { saleName: { $in: imporNames } }
            });
            if (oldData.length) {
                for (let old of oldData) {
                    if (importData.find(d => d.month == old.month && d.saleName == old.saleName)) {
                        delDataIds.push(old.id);
                    }
                }
            }
            await models.salePerformance.destroy({ where: { id: { $in: delDataIds } }, transaction });

        }
        if (importData.length)
            await models.salePerformance.bulkCreate(importData, { transaction });

        await transaction.commit();
        ctx.status = 204;
    } catch (error) {
        await transaction.rollback();
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = errorMsg;
    }
}

module.exports = {
    getSalePerformance,
    importSalePerformance,
}