'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/7/9
 * @version
 */

module.exports = options => {
    /**
     * 标段选择中间件
     *
     * @param {function} next - 中间件继续执行的方法
     * @return {void}
     */
    return function* tenderSelect(next) {
        try {
            if (this.request.query.tenderId) {
                const tenderId = parseInt(this.request.query.tenderId);
                const tender = yield this.service.tender.getDataById(tenderId);
                this.session.sessionUser.tenderId = tender.id;
                this.session.sessionUser.tenderName = tender.name;

                this.redirect(this.urlInfo.pathname);
            } else {
                this.tenderList = yield this.service.tender.getList();
                for (const tender of this.tenderList) {
                    tender.url = this.request.url + '?tenderId=' + tender.id;
                }

                let tenderId = this.session.sessionUser.tenderId;
                if (!tenderId) {
                    // 根据标段列表获取默认tenderId
                    if (this.tenderList && this.tenderList.length > 0) {
                        tenderId = this.tenderList[0].id;
                        this.session.sessionUser.tenderId = tenderId;
                        this.session.sessionUser.tenderName = this.tenderList[0].name;
                    } else {
                        throw '项目无标段数据';
                    }
                }
                this.tenderData = yield this.service.tender.getDataById(tenderId);

                yield next;
            }
        } catch (err) {
            console.log(err);
            this.redirect(this.menuList.dashboard.url);
        }
    };
};