'use strict';

/**
 * 计量相关控制器
 *
 * @author olym
 * @date 2018/2/11
 * @version
 */

const spreadConst = require('../const/spread');
const codeRuleConst = require('../const/code_rule');
const auditConst = require('../const/audit').stage;
const moment = require('moment');
const measureType = require('../const/tender').measureType;

module.exports = app => {

    class MeasureController extends app.BaseController {

        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            ctx.showProject = true;
            ctx.showTender = true;
            ctx.showTitle = true;
        }

        /**
         * 期列表(Get)
         * @param ctx
         * @returns {Promise<void>}
         */
        async stage(ctx) {
            try {
                const renderData = {
                    tender: ctx.tender.data,
                    tenderMenu: this.menu.tenderMenu,
                    preUrl: '/tender/' + ctx.tender.id,
                    auditConst,
                    auditConst2: JSON.stringify(auditConst),
                };
                renderData.stages = await ctx.service.stage.getValidStages(ctx.tender.id);
                for (const s of renderData.stages) {
                    // s.curAuditor = null;
                    // 根据期状态返回展示用户
                    s.curAuditor = await ctx.service.stageAudit.getAuditorByStatus(s.id, s.status, s.times);
                    if (s.status === auditConst.status.checkNoPre) {
                        s.curAuditor2 = await ctx.service.stageAudit.getAuditorByStatus(s.id, auditConst.status.checking);
                    }
                }
                await this.layout('measure/stage.ejs', renderData, 'measure/stage_modal.ejs');
            } catch (err) {
                this.log(err);
                ctx.redirect(this.menu.menu.dashboard.url);
            }
        }

        /**
         * 期审批流程(Get)
         * @param ctx
         * @returns {Promise<void>}
         */
        async stageAuditors(ctx) {
            try {
                const responseData = {
                    err: 0, msg: '', data: {},
                };
                const order = JSON.parse(ctx.request.body.data).order;
                const tenderId = ctx.params.id;
                const stageInfo = await ctx.service.stage.getDataByCondition({ tid: tenderId, order });
                // 获取审批流程中右边列表
                const auditHistory = [];
                const times = stageInfo.status === auditConst.status.checkNo ? stageInfo.times - 1 : stageInfo.times;
                if (times >= 1) {
                    for (let i = 1; i <= times; i++) {
                        auditHistory.push(await ctx.service.stageAudit.getAuditors(stageInfo.id, i));
                    }
                }
                responseData.data.auditHistory = auditHistory;
                // 获取审批流程中左边列表
                responseData.data.auditors = await ctx.service.stageAudit.getAuditGroupByList(stageInfo.id, times);
                // 获取原报信息
                const stageAuditor = await ctx.service.projectAccount.getAccountInfoById(stageInfo.user_id);
                responseData.data.stageAuditor = stageAuditor;
                ctx.body = responseData;
            } catch (error) {
                this.log(error);
                ctx.body = { err: 1, msg: error.toString(), data: null };
            }
        }

        /**
         * 新增期(Post)
         * @param ctx
         * @returns {Promise<void>}
         */
        async add(ctx) {
            try {
                if (ctx.session.sessionUser.accountId !== ctx.tender.data.user_id) {
                    throw '您无权创建计量期';
                }
                const date = ctx.request.body.date;
                const period = ctx.request.body.period;
                const newStage = await ctx.service.stage.addStage(ctx.tender.id, date, period);
                if (!newStage) {
                    throw '新增计量期失败，请重试';
                }
                ctx.redirect('/tender/' + ctx.tender.id + '/measure/stage/' + newStage.order);
            } catch (err) {
                this.log(err);
                ctx.redirect(ctx.request.header.referer)
            }
        }

        /**
         * 编辑期(Post)
         * @param ctx
         * @returns {Promise<void>}
         */
        async save(ctx) {
            try {
                const data = {
                    order: ctx.request.body.order,
                    date: ctx.request.body.date,
                    period: ctx.request.body.period,
                };
                const stage = await ctx.service.stage.getDataByCondition({
                    tid: ctx.tender.id,
                    order: data.order,
                });
                if (!stage) {
                    throw '提交数据错误';
                }
                if (stage.status !== auditConst.status.uncheck) {
                    throw '该计量期当前不可编辑';
                }
                if (ctx.session.sessionUser.accountId !== stage.user_id) {
                    throw '您无权修改该数据';
                }
                await this.ctx.service.stage.saveStage(ctx.tender.id, data.order, data.date, data.period);
                ctx.redirect('/tender/' + ctx.tender.id + '/measure/stage/');
            } catch (err) {
                this.log(err);
                ctx.redirect('/tender/' + ctx.tender.id + '/measure/stage/');
            }
        }

        /**
         * 多期汇总 (Get)
         * @param ctx
         * @returns {Promise<void>}
         */
        async gather(ctx) {
            try {
                const renderData = {
                    tender: ctx.tender.data,
                    tenderMenu: this.menu.tenderMenu,
                    preUrl: '/tender/' + ctx.tender.id,
                }
                await this.layout('measure/gather.ejs', renderData);
            } catch (err) {
                this.log(err);
                ctx.redirect(this.menu.menu.dashboard.url);
            }
        }

        /**
         * 多期比较(Get)
         * @param ctx
         * @returns {Promise<void>}
         */
        async compare(ctx) {
            try {
                const renderData = {
                    tender: ctx.tender.data,
                    tenderMenu: this.menu.tenderMenu,
                    preUrl: '/tender/' + ctx.tender.id,
                }
                await this.layout('measure/compare.ejs', renderData, 'measure/compare_modal.ejs');
            } catch (err) {
                this.log(err);
                ctx.redirect(this.menu.menu.dashboard.url);
            }
        }
    }

    return MeasureController;
};
