"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PowerPlantQuery = exports.POWER_PLANT_STATUS = void 0;
const tslib_1 = require("tslib");
const type_graphql_1 = require("type-graphql");
const shell_1 = require("@things-factory/shell");
const power_plant_type_1 = require("./power-plant-type");
const power_plant_model_1 = require("./power-plant-model");
const eaas_inverter_model_1 = require("../eaas-inverter/eaas-inverter-model");
const moment_1 = tslib_1.__importDefault(require("moment"));
exports.POWER_PLANT_STATUS = {
    NORMAL: 'NORMAL', // 정상 = COM : 0 && RUN : 0
    STOP: 'STOP', // 가동중지 = 한 개의 인버터라도 COM : 1 인 경우
    FAULT: 'FAULT', // 장애 = 한 개의 인버터라도 RUN : 0이아닌 경우
    COMMUNICATION_FAULT: 'COMMUNICATION_FAULT' // 통신장애 = 아직 없음
};
let PowerPlantQuery = class PowerPlantQuery {
    async powerPlants(params, context) {
        const { domain } = context.state;
        const { items, listCount } = await (0, power_plant_model_1.getPowerPlans)(params, domain);
        const totalData = await (0, power_plant_model_1.getPowerPlansCount)(params, domain);
        let total = {
            count: 0,
            capacity: 0,
            generationTime: 0,
            normalCount: 0,
            stopCount: 0,
            faultCount: 0,
            communicationFaultCount: 0,
            listCount: listCount
        };
        for (const data of totalData) {
            total.count += 1;
            total.capacity += Number(data['capacity']);
            // 발전소 용량이 있을때만 발전시간 계산
            if (Number(data['capacity']) > 0) {
                total.generationTime += Number(data['acc']) / Number(data['capacity']);
            }
            // 발전소 합계 상태 계산
            if (data['isNoSignal'] == 'T') {
                total.communicationFaultCount += 1;
            }
            if (data['maxInverterOperationStatus'] !== null && data['maxInverterOperationStatus'] != '0') {
                total.faultCount += 1;
            }
            else if (data['maxInverterCommunicationStatus'] == '1') {
                total.stopCount += 1;
            }
            if (data['isNoSignal'] == 'F' &&
                data['maxInverterOperationStatus'] == '0' &&
                data['maxInverterCommunicationStatus'] == '0') {
                total.normalCount += 1;
            }
        }
        return { items, total };
    }
    async powerPlantDetail(id, context) {
        const { user, domain } = context.state;
        const powerPlantDetail = await (0, power_plant_model_1.getPowerPlantDetail)(id);
        return powerPlantDetail;
    }
    async myPowerPlant(context) {
        const { domain } = context.state;
        const myPowerPlant = await (0, shell_1.getRepository)(shell_1.Domain).findOneBy({ id: domain.id });
        return { ...myPowerPlant, ...myPowerPlant.attributes };
    }
    async powerPlantSummary(id, context) {
        const { user, domain } = context.state;
        const powerPlant = await (0, shell_1.getRepository)(shell_1.Domain).findOneBy({ id: domain.id });
        const thisMonth = (0, moment_1.default)().tz(powerPlant.timezone).format('YYYY-MM');
        const inverterSummary = await (0, eaas_inverter_model_1.getInverterSummaryMonthlyByPowerPlantId)(id, thisMonth);
        // inverterSummary가 비어있거나 유효하지 않은 경우 기본값 반환
        if (!inverterSummary || inverterSummary.length === 0) {
            return { powerPlantId: id, avg_generation_time: 0, sum_acc: 0 };
        }
        let powerPlantSummary = inverterSummary.reduce((acc, item) => {
            acc.avg_generation_time += Number(item.generationTime) || 0;
            acc.sum_acc += Number(item.value) || 0;
            return acc;
        }, { powerPlantId: id, avg_generation_time: 0, sum_acc: 0 });
        // 0으로 나누는 것을 방지
        powerPlantSummary.avg_generation_time = powerPlantSummary.avg_generation_time / inverterSummary.length;
        return powerPlantSummary;
    }
    async powerPlantHeaderInfo(id, context) {
        const { user, domain } = context.state;
        const powerPlantHeaderInfo = await (0, power_plant_model_1.getPowerPlantHeaderInfo)(id);
        return powerPlantHeaderInfo;
    }
    async powerPlantsForHeader(id, context) {
        const { user, domain } = context.state;
        const powerPlans = await (0, power_plant_model_1.getPowerPlansForHeader)(domain.id);
        return powerPlans;
    }
    async todaySmp(context) {
        const todaySmp = await (0, power_plant_model_1.getLastDataSampleByDataSetName)('SMP');
        const data = JSON.parse(todaySmp.data);
        return {
            powerPlantId: todaySmp.powerPlantId,
            TRAD_DAY: data.TRAD_DAY,
            AVG_PRC: data.AVG_PRC[0],
            LOW_PRC: data.LOW_PRC[0],
            HIGH_PRC: data.HIGH_PRC[0]
        };
    }
    async todayRec(context) {
        const todayRec = await (0, power_plant_model_1.getLastDataSampleByDataSetName)('REC');
        const data = JSON.parse(todayRec.data);
        return {
            powerPlantId: todayRec.powerPlantId,
            TRAD_DAY: data.TRAD_DAY,
            AVG_PRC: data.AVG_PRC,
            LOW_PRC: data.LOW_PRC,
            HIGH_PRC: data.HIGH_PRC
        };
    }
};
exports.PowerPlantQuery = PowerPlantQuery;
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => power_plant_type_1.PowerPlantList, { nullable: true, description: 'To fetch a PowerPlant' }),
    tslib_1.__param(0, (0, type_graphql_1.Args)()),
    tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [shell_1.ListParam, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "powerPlants", null);
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => power_plant_type_1.PowerPlantDetail, { nullable: true, description: 'To fetch a PowerPlant Detail' }),
    tslib_1.__param(0, (0, type_graphql_1.Arg)('id')),
    tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [String, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "powerPlantDetail", null);
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => power_plant_type_1.PowerPlantDetail, { description: 'To fetch a PowerPlant Detail' }),
    tslib_1.__param(0, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "myPowerPlant", null);
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => power_plant_type_1.PowerPlantSummary, { nullable: true, description: 'To fetch a PowerPlant Summary' }),
    tslib_1.__param(0, (0, type_graphql_1.Arg)('id')),
    tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [String, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "powerPlantSummary", null);
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => power_plant_type_1.PowerPlantHeaderInfo, { nullable: true, description: 'To fetch a PowerPlant Header Info' }),
    tslib_1.__param(0, (0, type_graphql_1.Arg)('id')),
    tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [String, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "powerPlantHeaderInfo", null);
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => [power_plant_type_1.PowerPlant], { nullable: true, description: 'To fetch a PowerPlant List for Header' }),
    tslib_1.__param(0, (0, type_graphql_1.Arg)('id')),
    tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [String, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "powerPlantsForHeader", null);
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => power_plant_type_1.TodaySmpRec, { nullable: true, description: 'To fetch a TodaySmp for Header' }),
    tslib_1.__param(0, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "todaySmp", null);
tslib_1.__decorate([
    (0, type_graphql_1.Query)(returns => power_plant_type_1.TodaySmpRec, { nullable: true, description: 'To fetch a TodayRec for Header' }),
    tslib_1.__param(0, (0, type_graphql_1.Ctx)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PowerPlantQuery.prototype, "todayRec", null);
exports.PowerPlantQuery = PowerPlantQuery = tslib_1.__decorate([
    (0, type_graphql_1.Resolver)(shell_1.Domain)
], PowerPlantQuery);
//# sourceMappingURL=power-plant-query.js.map