'use strict';

/**
 *
 *
 * @author Mai
 * @date
 * @version
 */

const auditConst = require('../const/audit').flow;
const spreadConst = require('../const/spread');

module.exports = app => {
    class MeasureAuditController extends app.BaseController {
        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局context
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            ctx.showProject = true;
        }

        /**
         * 中间计量--计量审批 页面 (Get)
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async list(ctx) {
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '当前未打开标段';
                }

                const works = await ctx.service.measure.joinMeasure(tenderId, ctx.session.sessionUser.accountId);
                const renderData = {
                    works,
                    auditConst,
                };
                await this.layout('measure/list.ejs', renderData);
            } catch (err) {
                this.log(err);
                ctx.redirect(ctx.request.header.referer);
            }
        }

        /**
         * 中间计量审批页面 (Get)
         *
         * @param ctx
         * @returns {Promise<void>}
         */
        async index(ctx) {
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '当前未打开标段';
                }

                const mid = ctx.params.mid;
                const measure = mid ? await ctx.service.measure.getDataByCondition({mid: mid}) : null;
                if (!measure) {
                    throw '查看的中间计量不存在';
                }
                const curAuditor = await ctx.service.measureAudit.getCurAuditor(measure.mid, measure.times);
                const times = (measure.times > 1 && measure.status === auditConst.status.checkNo) ? measure.times - 1 : measure.times;
                const auditors = await ctx.service.measureAudit.getAuditors(measure.mid, times);
                const bills = await ctx.service.measureBills.getBillsDetailWithParent(tenderId, mid);

                const renderData = {
                    measure,
                    billsData: JSON.stringify(bills),
                    curAuditor,
                    auditors,
                    auditConst,
                    measureSpreadSetting: JSON.stringify(spreadConst.measureSpread),
                }
                await this.layout('measure/audit.ejs', renderData, 'measure/audit_modal.ejs');
            } catch (err) {
                this.log(err);
                ctx.redirect(ctx.request.header.referer);
            }
        };

        /**
         * 新增审批人(Ajax)
         *
         * @param {Object} ctx - egg全局context
         * @returns {Promise<void>}
         */
        async add(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '当前未打开标段';
                }

                const data = JSON.parse(ctx.request.body.data);
                const mid = data.mid;
                const id = data.auditorId;
                if (!mid ||  isNaN(id) || id <= 0) {
                    throw '参数错误';
                }

                const auditor = await ctx.service.measureAudit.getAuditor(mid, id);
                if (auditor) {
                    throw '该审批人已存在，请勿重复添加';
                }

                const result = await ctx.service.measureAudit.addAuditor(tenderId, mid, id);
                if (!result) {
                    throw '添加审批人失败';
                }

                responseData.data = await ctx.service.measureAudit.getAuditor(mid, id);
            } catch (err) {
                this.log(err);
                responseData.err = 1;
                responseData.msg = err.toString();
            }

            ctx.body = responseData;
        }

        /**
         * 移除审批人 (Ajax)
         *
         * @param {Object} ctx - egg全局context
         * @returns {Promise<void>}
         */
        async remove(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '当前未打开标段';
                }

                const data = JSON.parse(ctx.request.body.data);
                const mid = data.mid;
                const id = data.auditorId;
                if (!mid ||  isNaN(id) || id <= 0) {
                    throw '参数错误';
                }

                const measure = await ctx.service.measure.getDataByCondition({mid: mid});
                const auditor = await ctx.service.measureAudit.getAuditor(mid, id);
                if (!measure || !auditor) {
                    throw '提交数据错误';
                }

                const result = await ctx.service.measureAudit.deleteAuditor(mid, id, measure.times);
                if (!result) {
                    throw '移除审批人失败';
                }

                responseData.data = await ctx.service.measureAudit.getAuditors(mid);
            } catch (err) {
                this.log(err);
                responseData.err = 1;
                responseData.msg = err.toString();
            }

            ctx.body = responseData;
        }

        /**
         * 上报 (Ajax)
         *
         * @param {Object} ctx - egg全局context
         * @returns {Promise<void>}
         */
        async start(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: {},
            };
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '未打开标段';
                }

                const data = JSON.parse(ctx.request.body.data);
                const mid = data.mid;
                if (!mid) {
                    throw '参数错误';
                }

                const measure = await ctx.service.measure.getDataByCondition({mid: mid});
                if (!measure || measure.status === auditConst.status.checking || measure.status === auditConst.status.checked) {
                    throw '中间计量数据有误';
                }
                if (measure.user_id !== ctx.session.sessionUser.accountId) {
                    throw '上报失败';
                }

                await ctx.service.measureAudit.start(mid, measure.times);
                responseData.data = await ctx.service.measure.getDataByCondition({mid: mid});
                responseData.data.auditors = await ctx.service.measureAudit.getAuditors(measure.mid, measure.times);
                responseData.data.curAuditor = await ctx.service.measureAudit.getCurAuditor(measure.mid, measure.times);
            } catch (err) {
                this.log(err);
                responseData.err = 1;
                responseData.msg = err.toString();
                responseData.data = {};
            }

            ctx.body = responseData;
        }

        /**
         * 审批 (Post)
         *
         * @param {Object} ctx - egg全局context
         * @returns {Promise<void>}
         */
        async check(ctx) {
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '当前未打开标段';
                }

                const mid = ctx.request.body.mid;
                if (!mid) {
                    throw '参数错误';
                }
                const measure = await ctx.service.measure.getDataByCondition({mid: mid});
                if (!measure || measure.status !== auditConst.status.checking) {
                    throw '中间计量数据有误';
                }
                const curAudit = await ctx.service.measureAudit.getCurAuditor(mid, measure.times);
                if (curAudit.audit_id !== ctx.session.sessionUser.accountId) {
                    throw '审批失败';
                }

                const checkType = parseInt(ctx.request.body.checkType);
                if (!checkType || isNaN(checkType)) {
                    throw '提交数据错误';
                }

                await ctx.service.measureAudit.check(mid, checkType, ctx.request.body.opinion, measure.times);

                ctx.redirect(ctx.request.header.referer);
            } catch (err) {
                this.log(err);
                ctx.session.postError = err.toString();
                ctx.redirect(ctx.request.header.referer);
            }
        }

    };

    return MeasureAuditController;
};