'use strict';

'use strict';
const moment = require('moment');
const { QueryTypes } = require('sequelize');

async function getLastMonthCost(ctx) {
    const { fourceUpdate } = ctx.query;
    let rslt = [];
    try {
        const startTime = new Date(moment().startOf('year')), endTime = new Date(moment().endOf('year').valueOf());
        const models = ctx.fs.dc.models;
        const costList = await models.RoadMaintenanceCost.findAll({
            where: {
                maintenanceDate: { '$between': [startTime, endTime] },
                countyName: { $not: '南昌县*' }
            }
        })
        if (!costList || !costList.length || fourceUpdate) {
            const dataList = await models.RoadMaintenance.findAll();
            if (fourceUpdate) {
                await models.RoadMaintenanceCost.destroy({ where: { id: { $not: null } } });
            }
            for (var i = 0; i < 12; i++) {
                const dateTime = new Date(moment().month(i));

                let nanChang = {
                    countyName: '南昌县*',
                    roadLengthCounty: 0,
                    roadLengthTownship: 0,
                    roadLengthVillage: 0,
                    roadCostCounty: 0,
                    roadCostTownship: 0,
                    roadCostVillage: 0,
                    maintenanceDate: dateTime
                };
                dataList.map(item => {
                    const { countyHighway, townshipRoad, villageRoad, responsibleUnitForManagementAndMaintenance } = item;
                    const randomNum = 0.1 * (0.8 + Math.random() / 2);

                    let data = {
                        countyName: responsibleUnitForManagementAndMaintenance,
                        roadLengthCounty: countyHighway ? countyHighway * randomNum : 0,
                        roadLengthTownship: townshipRoad ? townshipRoad * randomNum : 0,
                        roadLengthVillage: villageRoad ? villageRoad * randomNum : 0,
                        maintenanceDate: dateTime
                    }
                    data.roadCostCounty = typeof data.roadLengthCounty == 'number' && !isNaN(data.roadLengthCounty) ? data.roadLengthCounty * 15000 / 12 : 0,
                        data.roadCostTownship = typeof data.roadLengthTownship == 'number' && !isNaN(data.roadLengthTownship) ? data.roadLengthTownship * 7500 / 12 : 0,
                        data.roadCostVillage = typeof data.roadLengthVillage == 'number' && !isNaN(data.roadLengthVillage) ? data.roadLengthVillage * 3900 / 12 : 0;

                    rslt.push(data)
                    nanChang.roadLengthCounty += data.roadLengthCounty;
                    nanChang.roadLengthTownship += data.roadLengthTownship;
                    nanChang.roadLengthVillage += data.roadLengthVillage;
                    nanChang.roadCostCounty += data.roadCostCounty;
                    nanChang.roadCostTownship += data.roadCostTownship;
                    nanChang.roadCostVillage += data.roadCostVillage;

                    models.RoadMaintenanceCost.create(data)
                })
                models.RoadMaintenanceCost.create(nanChang)
            }

        } else {
            rslt = costList
        }


        ctx.status = 200;
        ctx.body = rslt;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: typeof error == 'string' ? error : undefined
        }
    }
}

async function getConcatData(ctx) {
    try {
        let startTime = new Date(moment().startOf('year')),
            endTime = new Date(moment().endOf('month'));

        if (moment().year() == 2022) {
            startTime = new Date(moment().startOf('year').month(3))
        }
        const models = ctx.fs.dc.models;
        const costList = await models.RoadMaintenanceCost.findAll({
            where: {
                maintenanceDate: { '$between': [startTime, endTime] },
                countyName: '南昌县*'
            },
            order: [['maintenanceDate', 'DESC']]
        })
        ctx.status = 200;
        ctx.body = costList;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: typeof error == 'string' ? error : undefined
        }
    }
}

async function getRoadMaintenanceList(ctx) {
    try {
        const models = ctx.fs.dc.models;
        const list = await models.RoadMaintenance.findAll();
        ctx.status = 200;
        ctx.body = list;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: typeof error == 'string' ? error : undefined
        }
    }
}

async function updateRoadMaintenanceList(ctx) {
    try {
        const data = ctx.request.body;
        const models = ctx.fs.dc.models;
        // const list = await models.RoadMaintenance.findAll();
        await models.RoadMaintenance.update(data, { where: { id: data.id } })

        ctx.status = 200;
        ctx.body = {message:'编辑成功'};
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: typeof error == 'string' ? error : undefined
        }
    }
}


module.exports = {
    getLastMonthCost,
    getConcatData,
    getRoadMaintenanceList,
    updateRoadMaintenanceList,
}