'use strict';

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

const status = require('../const/audit').stage.status;
const _ = require('lodash');

module.exports = options => {
    /**
     * 期校验 中间件
     * 1. 读取期数据
     * 2. 检验用户是否参与期（不校验具体权限）
     *
     * 写入ctx.stage数据
     * 其中:
     * stage.auditors: 审批人列表(退回原报时，加载上一流程)
     * stage.curAuditor: 当前审批人(未上报为空，审批通过 or 退回原报时，为空)
     * stage.readonly: 登录人，是否可操作
     * stage.curTimes: 当前登录人，操作、查阅数据times
     * stage.curOrder: 当前登录人，操作、查阅数据order
     *
     * 该方法为通用方法，如需stage其他数据，请在controller中查询
     *
     * @param {function} next - 中间件继续执行的方法
     * @return {void}
     */
    return function* stageCheck(next) {
        try {
            // 读取标段数据
            const stageOrder = parseInt(this.params.order);
            if (stageOrder <= 0) {
                throw '您访问的期不存在';
            }
            const stage = yield this.service.stage.getDataByCondition({
                tid: this.tender.id,
                order: stageOrder,
            });
            if (!stage) {
                throw '期数据错误';
            }

            // 读取原报、审核人数据
            stage.auditors = yield this.service.stageAudit.getAuditors(stage.id, stage.times);
            stage.curAuditor = yield this.service.stageAudit.getCurAuditor(stage.id, stage.times);

            // 权限相关
            // todo 校验权限 （标段参与人、分享）
            const accountId = this.session.sessionUser.accountId, auditorIds = _.map(stage.auditors, 'aid'), shareIds = [];
            if (accountId === stage.user_id) { // 原报
                stage.readOnly = stage.status !== status.uncheck && stage.status !== status.checkNo;
                stage.curTimes = stage.times;
                if (stage.status === status.uncheck || stage.status === status.checkNo) {
                    stage.curOrder = 0;
                } else if (stage.status === status.checked) {
                    stage.curOrder = _.max(_.map(stage.auditors, 'order'));
                } else {
                    stage.curOrder = stage.curAuditor.order - 1;
                }
            } else if (auditorIds.indexOf(accountId) !== -1) { // 审批人
                if (stage.status === status.uncheck) {
                    throw '您无权查看该数据';
                }
                stage.readOnly = (stage.status !== status.checking && stage.status !== status.checkNoPre) || accountId !== stage.curAuditor.aid;
                stage.curTimes = stage.status === status.checkNo ? stage.times - 1 : stage.times;
                if (stage.status === status.checked) {
                    stage.curOrder = _.max(_.map(stage.auditors, 'order'));
                } else if (stage.status === status.checkNo) {
                    const audit = this.service.stageAudit.getDataByCondition({
                        sid: stage.id, times: stage.times, status: status.checkNo
                    });
                    stage.curOrder = audit.order;
                } else {
                    stage.curOrder = accountId === stage.curAuditor.aid ? stage.curAuditor.order : stage.curAuditor.order - 1;
                }
            } else if (shareIds.indexOf(accountId) !== -1) { // 分享人
                if (stage.status === status.uncheck) {
                    throw '您无权查看该数据';
                }
                stage.readOnly = true;
                stage.curTimes = stage.status === status.checkNo ? stage.times - 1 : stage.times;
                stage.curOrder = stage.status === status.checked ? _.max(_.map(stage.auditors, 'order')) : stage.curAuditor.order - 1;
            } else { // 其他不可见
                throw '您无权查看该数据';
            }
            this.stage = stage;
            yield next;
        } catch (err) {
            console.log(err);
            // 输出错误到日志
            if (err.stack) {
                this.logger.error(err);
            } else {
                this.getLogger('fail').info(JSON.stringify({
                    error: err,
                    project: this.session.sessionProject,
                    user: this.session.sessionUser,
                    body: this.session.body,
                }));
            }
            // 重定向值标段管理
            this.redirect(this.request.headers.referer);
        }
    };
};
