'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/5/28
 * @version
 */
const auditConst = require('../const/audit').flow;
const spreadConst = require('../const/spread');
const measureType = require('../const/tender').measureType;

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

        /**
         * 获取SpreadSetting
         * @private
         */
        _getSpreadSetting() {
            const _ = this.app._;
            function removeFieldCols(setting, cols) {
                _.remove(setting.cols, function(c) {
                    return cols.indexOf(c.field) > -1;
                });
            }
            const ledger = JSON.parse(JSON.stringify(spreadConst.ledgerSpread));
            const pos = JSON.parse(JSON.stringify(spreadConst.ledgerPosSpread));
            const tender = this.ctx.tender;
            ledger.readOnly = true;
            pos.readOnly = true;
            if (tender.data.measure_type === measureType.tz.value) {
                removeFieldCols(ledger, spreadConst.filterCols.tzWithoutCols);
            }
            if (!tender.info.display.ledger.dgnQty) {
                removeFieldCols(ledger, spreadConst.filterCols.dgnCols);
            }
            return [ledger, pos];
        }

        /**
         * 台账审批页面(get)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async index(ctx) {
            try {
                const renderData = {
                    tender: ctx.tender.data,
                    tenderMenu: this.menu.tenderMenu,
                    preUrl: '/tender/' + ctx.tender.id,
                    measureType,
                };
                const [ledgerSpread, posSpread] = this._getSpreadSetting();

                const curAuditor = await ctx.service.ledgerAudit.getCurAuditor(ctx.tender.id, ctx.tender.data.ledger_times);
                if (!curAuditor && (ctx.tender.data.ledger_status !== auditConst.status.checkNo && ctx.tender.data.ledger_status !== auditConst.status.checked)) {
                    throw '审核信息错误';
                }

                const auditors = await ctx.service.ledgerAudit.getAuditors(ctx.tender.id, ctx.tender.data.ledger_times);
                if (ctx.tender.data.user_id !== ctx.session.sessionUser.accountId) {
                    if (auditors.length > 0) {
                        const auditor = auditors.find(function(a) { return a.audit_id === ctx.session.sessionUser.accountId; });
                        if (!auditor) {
                            throw '您无权查看台账审批';
                        }
                    }
                }

                renderData.user = await ctx.service.projectAccount.getAccountInfoById(ctx.tender.data.user_id);
                renderData.auditHistory = [];
                if (ctx.tender.data.ledger_times > 1) {
                    for (let i = 1; i < ctx.tender.data.ledger_times; i++) {
                        renderData.auditHistory.push(await ctx.service.ledgerAudit.getAuditors(ctx.tender.id, i));
                    }
                }

                const ledgerData = await ctx.service.ledger.getDataByTenderId(ctx.tender.id, -1);
                renderData.curAuditor = curAuditor;
                renderData.auditConst = auditConst;
                renderData.auditors = auditors;
                renderData.ledger = JSON.stringify(ledgerData);
                renderData.ledgerSpreadSetting = JSON.stringify(ledgerSpread);
                renderData.posSpreadSetting = JSON.stringify(posSpread);
                renderData.readOnly = true;
                renderData.jsFiles = this.app.jsFiles.common.concat(this.app.jsFiles.ledger.audit),
                await this.layout('ledger/audit.ejs', renderData, 'ledger/audit_modal.ejs');
            } catch (err) {
                this.log(err);
                console.log(err);
                ctx.redirect('/tender/' + ctx.tender.id);
            }
        }

        /**
         * 新增审批人(Ajax)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async add(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            try {
                const data = JSON.parse(ctx.request.body.data);
                const id = data.auditorId;
                if (isNaN(id) || id <= 0) {
                    throw '参数错误';
                }

                const result = await ctx.service.ledgerAudit.addAuditor(ctx.tender.id, id);
                if (!result) {
                    throw '添加审核人失败';
                }

                responseData.data = await ctx.service.ledgerAudit.getAuditor(ctx.tender.id, id);
            } catch (err) {
                responseData.err = 1;
                responseData.msg = err.toString();
            }

            ctx.body = responseData;
        }

        /**
         * 移除审批人(Ajax)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async remove(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            try {
                const data = JSON.parse(ctx.request.body.data);
                const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
                if (isNaN(id) || id <= 0) {
                    throw '参数错误';
                }

                const result = await ctx.service.ledgerAudit.deleteAuditor(ctx.tender.id, id);
                if (!result) {
                    throw '移除审核人失败';
                }

                responseData.data = await ctx.service.ledgerAudit.getAuditors(ctx.tender.id);
            } catch (err) {
                responseData.err = 1;
                responseData.msg = err.toString();
            }

            ctx.body = responseData;
        }

        /**
         * 上报(post)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async start(ctx) {
            try {
                if (!ctx.tender.data || ctx.tender.data.ledger_status === auditConst.status.checking || ctx.tender.data.ledger_status === auditConst.status.checked) {
                    throw '标段数据有误';
                }
                if (ctx.tender.data.user_id !== ctx.session.sessionUser.accountId) {
                    throw '上报失败';
                }

                await ctx.service.ledgerAudit.start(ctx.tender.id, ctx.tender.data.ledger_times);

                ctx.redirect('/tender/' + ctx.tender.id + '/ledger/explode');
            } catch (err) {
                this.log(err);
                ctx.session.postError = err.toString();
                ctx.redirect('/tender/' + ctx.tender.id + '/ledger/explode');
            }
        }

        /**
         * 审批(post)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async check(ctx) {
            try {
                const tender = ctx.tender;
                if (!tender.data || tender.data.ledger_status !== auditConst.status.checking) {
                    throw '当前标段数据有误';
                }
                const curAudit = await ctx.service.ledgerAudit.getCurAuditor(tender.id, tender.data.ledger_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.ledgerAudit.check(tender.id, checkType, ctx.request.body.opinion, tender.data.ledger_times);

                ctx.redirect('/tender/' + ctx.tender.id + '/ledger/explode');
            } catch (err) {
                this.log(err);
                ctx.session.postError = err.toString();
                ctx.redirect(ctx.request.header.referer);
            }
        }
    }

    return LedgerAuditController;
};
