'use strict';

/**
 * 标段数据模型
 *
 * @author CaiAoLin
 * @date 2017/11/30
 * @version
 */

const tenderConst = require('../const/tender');
module.exports = app => {

    class Tender extends app.BaseService {

        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            this.tableName = 'tender';

            // 状态相关
            this.status = {
                TRY: 1,
                NORMAL: 2,
                DISABLE: 3,
            };
            this.displayStatus = [];
            this.displayStatus[this.status.TRY] = '试用';
            this.displayStatus[this.status.NORMAL] = '正常';
            this.displayStatus[this.status.DISABLE] = '禁用';

            this.statusClass = [];
            this.statusClass[this.status.TRY] = 'warning';
            this.statusClass[this.status.NORMAL] = 'success';
            this.statusClass[this.status.DISABLE] = 'danger';
        }

        /**
         * 数据规则
         *
         * @param {String} scene - 场景
         * @return {Object} - 返回数据规则
         */
        rule(scene) {
            let rule = {};
            switch (scene) {
                case 'add':
                    rule = {
                        name: { type: 'string', required: true, min: 2 },
                        type: { type: 'string', required: true, min: 1 },
                    };
                    break;
                case 'save':
                    rule = {
                        name: { type: 'string', required: true, min: 2 },
                        type: { type: 'string', required: true, min: 1 },
                    };
                default:
                    break;
            }

            return rule;
        }

        /**
         * 获取标段列表
         *
         * @param {Object} type - 标段类型
         * @return {Array} - 返回标段数据
         */
        async getList(type = 0) {
            // 获取当前项目信息
            const sessionProject = this.ctx.session.sessionProject;
            this.initSqlBuilder();
            this.sqlBuilder.setAndWhere('project_id', {
                value: sessionProject.id,
                operate: '=',
            });
            if(type !== 0) {
                this.sqlBuilder.setAndWhere('type', {
                    value: type,
                    operate: '=',
                });
            }
            this.sqlBuilder.limit = 10;
            this.sqlBuilder.columns = ['id', 'name', 'status', 'type'];
            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);

            return await this.db.query(sql, sqlParam);
        }

        /**
         * 新增标段
         *
         * @param {Object} postData - 表单post过来的数据
         * @return {Boolean} - 返回新增结果
         */
        async add(postData) {
            let result = false;
            this.transaction = await this.db.beginTransaction();
            try {
                // 获取当前用户信息
                const sessionUser = this.ctx.session.sessionUser;
                // 获取当前项目信息
                const sessionProject = this.ctx.session.sessionProject;

                const insertData = {
                    name: postData.name,
                    status: tenderConst.status.APPROVAL,
                    project_id: sessionProject.id,
                    user_id: sessionUser.accountId,
                    create_time: postData.create_time,
                    type: postData.type,
                };
                const operate = await this.transaction.insert(this.tableName, insertData);

                result = operate.insertId > 0;
                if (!result) {
                    throw '新增标段数据失败';
                }

                // 获取标段项目节点模板
                const tenderNodeTemplateData = await this.ctx.service.tenderNodeTemplate.getData();
                // 复制模板数据到标段数据表
                result = await this.ctx.service.ledger.innerAdd(tenderNodeTemplateData, operate.insertId, this.transaction);

                if (!result) {
                    throw '新增标段项目节点失败';
                }
                this.transaction.commit();
            } catch (error) {
                console.log(error);
                result = false;
                this.transaction.rollback();
            }
            return result;
        }

        /**
         * 保存标段
         *
         * @param {Object} postData - 表单post过来的数据
         * @param {Number} id - 用于判断修改还是新增的id
         * @return {Boolean} - 返回执行结果
         */
        async save(postData,id = 0) {
            id = parseInt(id);

            const rowData = {
                id: id,
                name: postData.name,
                type: postData.type,
            };
            const result = await this.db.update(this.tableName, rowData);
            return result.affectedRows > 0;
        }

        /**
         * 假删除
         *
         * @param {Number} id - 删除的id
         * @return {Boolean} - 删除结果
         */
        async deleteTenderById(id) {

            const updateData = {
                status: this.status.DISABLE,
                id,
            };

            const result = this.db.update(this.tableName, updateData);

            return result.affectedRows > 0;
        }

        /**
         * 切换标段
         *
         * @param {Number} tenderId - 标段id
         * @return {Boolean} - 返回切换结果
         */
        async switchTender(tenderId) {
            // 获取该用户拥有的项目数据
            const sessionUser = this.ctx.session.sessionUser;
            const tenderInfo = await this.ctx.service.projectAccount.getProjectInfoByAccount(sessionUser.account);

            let result = false;
            // 判断切换的标段是否属于对应用户
            if (tenderInfo.length < 0) {
                return result;
            }

            let targetTender = {};
            for (const tmp of tenderInfo) {
                if (tmp.id === tenderId) {
                    result = true;
                    targetTender = tmp;
                }
            }

            // 成功后更改session
            if (result) {
                this.ctx.session.sessionTender = {
                    id: targetTender.id,
                    name: targetTender.name,
                    userAccount: targetTender.user_account,
                };
            }

            return result;
        }

    }

    return Tender;
};