'use strict';

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

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

        /**
         * 台账审批页面(get)
         *
         * @param ctx
         * @returns {Promise<void>}
         */
        async index(ctx) {
            try {
                if (!ctx.request.query.tenderId) {
                    throw '标段信息错误';
                }

                const tenderId = ctx.request.query.tenderId;
                const tender = await ctx.service.tender.getDataById(tenderId);
                if (!tender.ledger_times) {
                    tender.ledger_times = 1;
                }
                ctx.session.sessionUser.tenderId = tender.id;
                ctx.session.sessionUser.tenderName = tender.name;

                const curAuditor = await ctx.service.ledgerAudit.getCurAuditor(tenderId, tender.ledger_times);
                if (curAuditor.audit_id !== ctx.session.sessionUser.accountId) {
                    throw '审核信息错误';
                }

                const auditors = await ctx.service.ledgerAudit.getAuditors(tenderId, tender.ledger_times);
                const ledgerData = await ctx.service.ledger.getDataByTenderId(tenderId);
                const content = await ctx.service.ledgerAuditContent.getAllDataByCondition({
                    where: {tender_id: tenderId, times: tender.ledger_times, audit_id: auditors[0].audit_id}
                });
                const renderData = {
                    auditConst,
                    tender,
                    curAuditor,
                    auditors,
                    content,
                    ledger: JSON.stringify(ledgerData),
                    ledgerSpreadSetting: JSON.stringify(spreadConst.ledgerSpread),
                    readOnly: true,
                };
                await this.layout('ledger/audit.ejs', renderData, 'ledger/audit_modal.ejs');
            } catch(err) {
                console.log(err);
                ctx.redirect('/dashboard');
            }
        }

        /**
         * 新增审批人(Ajax)
         *
         * @param ctx
         * @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 id = data.auditorId;
                if (isNaN(id) || id <= 0) {
                    throw '参数错误';
                }

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

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

            ctx.body = responseData;
        }

        /**
         * 移除审批人(Ajax)
         *
         * @param ctx
         * @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 id = data.auditorId;
                if (!(id instanceof Number) || isNaN(id) || id <= 0) {
                    throw '参数错误';
                }

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

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

            ctx.body = responseData;
        }

        /**
         * 上报(post)
         *
         * @param ctx
         * @returns {Promise<void>}
         */
        async start(ctx) {
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '未打开标段';
                }
                const tenderData = await ctx.service.tender.getDataById(tenderId);
                if (!tenderData || tenderData.ledger_status === auditConst.status.checking || tenderData.ledger_status === auditConst.status.checked) {
                    throw '标段数据有误';
                }
                if (tenderData.user_id !== ctx.session.sessionUser.accountId) {
                    throw '上报失败';
                }
                if (!tenderData.ledger_times) {
                    tenderData.ledger_times = 1;
                }

                await ctx.service.ledgerAudit.start(tenderId, tenderData.ledger_times);

                ctx.redirect('/ledger/explode');
            } catch (err) {
                console.log(err);
                ctx.session.postError = err.toString();
                ctx.redirect('/ledger/explode');
            }
        }

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

                ctx.redirect('/ledger/explode');
            } catch (err) {
                console.log(err);
                ctx.session.postError = err.toString();
                ctx.redirect(ctx.request.headers.referer);
            }
        }

        /**
         * 添加清单意见(Ajax)
         * @param ctx
         * @returns {Promise<void>}
         */
        async addContent(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '当前未打开标段';
                }
                const tenderData = await ctx.service.tender.getDataById(tenderId);
                if (!tenderData || tenderData.ledger_status !== auditConst.status.checking ) {
                    throw '当前标段数据有误';
                }
                if (!tenderData.ledger_times) {
                    tenderData.ledger_times = 1;
                }
                const curAudit = await ctx.service.ledgerAudit.getCurAuditor(tenderId, tenderData.ledger_times);
                if (curAudit.audit_id !== ctx.session.sessionUser.accountId) {
                    throw '添加清单意见失败';
                }
                const data = JSON.parse(ctx.request.body.data);

                const result = await ctx.service.ledgerAuditContent.add(tenderData, curAudit.audit_id, data);
                responseData.data = await ctx.service.ledgerAuditContent.getAllDataByCondition({
                    where: {tender_id: tenderId, times: tenderData.ledger_times, audit_id: curAudit.audit_id}
                });
            } catch (err) {
                console.log(err);
                responseData.err = 1;
                responseData.msg = err.toString();
            }

            ctx.body = responseData;
        }

        /**
         * 获取审核人的全部清单意见
         * @param ctx
         * @returns {Promise<void>}
         */
        async getContent(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '当前未打开标段';
                }
                const tenderData = await ctx.service.tender.getDataById(tenderId);
                if (!tenderData) {
                    throw '当前标段数据有误';
                }
                if (!tenderData.ledger_times) {
                    tenderData.ledger_times = 1;
                }
                const data = JSON.parse(ctx.request.body.data);

                const times = tenderData.ledger_status === auditConst.status.checkNo ? tenderData.ledger_times - 1 : tenderData.ledger_times;
                responseData.data = await ctx.service.ledgerAuditContent.getAllDataByCondition({
                    where: {tender_id: tenderId, times: times, audit_id: data.audit_id}
                });
            } catch (err) {
                console.log(err);
                responseData.err = 1;
                responseData.msg = err.toString();
            }

            ctx.body = responseData;
        }
    }

    return LedgerAuditController;
};