/**
 * Created by Mai on 2017/4/14.
 * 清单模板，新建项目使用
 */
import BaseModel from "../../../common/base/base_model";
const mongoose = require('mongoose');
const BillsTemplateSchema = mongoose.model('std_bills_template_items');

class BillsTemplateModel extends BaseModel {
    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = BillsTemplateSchema;
        parent.init();
    }

    /**
     * 获取模板库对应的清单模板
     * @param libID
     * @returns {*}
     */
    async getTemplateData (libID) {
        // 筛选字段
        let field = {_id: 1, valuationId: 1, ID: 1, ParentID: 1, NextSiblingID: 1, code: 1, name: 1, unit: 1, flags: 1, calcBase: 1};
        let data = await this.findDataByCondition({valuationId: valuationId, engineering: engineering}, field, false);

        return data === null ? [] : data;
    }

    /**
     * 新建项目时，获取模板库对应的清单模板
     * @param valuationId
     * @param engineering
     * @returns {*}
     */
    async getTemplateDataForNewProj (libID) {
        // 筛选字段
        let field = {_id: 0, ID: 1, ParentID: 1, NextSiblingID: 1, code: 1, name: 1, unit: 1, flags: 1,type:1, calcBase: 1,feeRateID:1,quantity:1};
        let data = await this.findDataByCondition({libID: libID}, field, false);

        return data === null ? [] : data;
    }

    async updateTemplate (valuationId, datas) {
        try {
            for (let data of datas) {
                data.data.valuationId = valuationId;
                let condition = {valuationId: valuationId, ID: data.data.ID}, result;
                if (data.type === 'update') {
                    result = await this.db.update(condition, data.data);
                    if (result === undefined || result.ok ===undefined || !result.ok) {
                        throw '更新数据错误';
                    }
                } else if (data.type === 'new') {
                    result = await this.db.create(data.data);
                    if (!result) {
                        throw '新增数据错误';
                    }
                } else if (data.type === 'delete') {
                    result = await this.db.delete(condition);
                    if (result === undefined || result.ok ===undefined || !result.ok) {
                        throw '删除数据错误';
                    }
                }
            }
            return true;
        } catch (error) {
            console.log(error);
        }
    }
};

export default BillsTemplateModel;
