/**
 * Created by jimiz on 2017/4/1.
 */
let mongoose = require("mongoose");
let db = require("../db/project_db");
let subSchema = require("./bills_sub_schemas");
let deleteSchema = require('../../../public/models/delete_schema');
let Schema = mongoose.Schema;
let async = require("async");
let counter = require("../../../public/counter/counter.js");
let consts = require('./project_consts');
let projectConsts = consts.projectConst;
let commonConsts = consts.commonConst;
let quantity_detial = require('../../ration_glj/facade/quantity_detail_facade');


let billsSchema = new Schema({
    ID: Number,
    ParentID: Number,
    NextSiblingID: Number,
    projectID: Number,
    serialNo: Number,
    chapterID: Number,
    code: String,
    fullCode: String,
    name: String,
    unit: String,
    quantity: String, // Decimal
    isFromDetail:{type: Number,default:0},//1 true 0 false
    programID: Number,
    // 工程量计算规则
    ruleText: String,
    // 说明
    comments: String,
    // 调价
    xs_Labour: String, // Decimal
    xs_Material: String, // Decimal
    xs_Machine: String, // Decimal
    xs_FeeRate: String, // Decimal
    xs_LabourPrice: String, // Decimal
    xs_MaterialPrice: String, // Decimal
    xs_MachinePrice: String, // Decimal
    isTender_Labour: Boolean,
    isTender_Material: Boolean,
    isTender_Machine: Boolean,
    tenderTargetPrice: String, // Decimal
    tenderTargetUnitPrice: String, // Decimal
    tenderTargetUnitPrice: String, // Decimal
    //工作内容//zhong 2017-8-31
    jobContentText: String, //清单工作内容列显示文本, 减少第一次拉数据时的循环次数
    jobContent: [subSchema.jobContentSchema],
    //项目特征
    itemCharacterText: String,//清单项目特征列显示文本
    itemCharacter: [subSchema.itemCharacterSchema],
    // 费用字段
    fees: [subSchema.feesSchema],
    // 标记字段
    flags: [subSchema.flagsSchema],
    deleteInfo: deleteSchema
});

let bills = db.model("bills", billsSchema);
let baseModel = require('./base_model');

class billsModel extends baseModel {
    constructor () {
        super(bills);
    };

    getData (projectID, callback) {
        this.model.find({'$or': [{projectID: projectID, deleteInfo: null}, {projectID: projectID, 'deleteInfo.deleted': {$in: [null, false]}}]}, '-_id', function(err, datas){
            if (!err) {
                callback(0, projectConsts.BILLS, datas);
            } else {
                callback(1, projectConsts.BILLS, null);
            };
        });
    };

    save (user_id, datas, callback) {
        let functions = [];
        let data;

        function saveOne(doc) {
            return function (cb) {
                switch (doc.updateType) {
                    case commonConsts.UT_UPDATE:
                        bills.update({projectID: doc.updateData.projectID, ID: doc.updateData.ID,deleteInfo: null}, doc.updateData, cb);
                        break;
                    case commonConsts.UT_CREATE:
                        bills.create(doc.updateData, cb);
                        break;
                    case commonConsts.UT_DELETE:
                        doc.updateData.deleteInfo = {deleted: true, deleteDateTime: new Date(), deleteBy: user_id};
                        bills.update({projectID: doc.updateData.projectID, ID: doc.updateData.ID}, doc.updateData, cb);
                        break;
                }
            }
        }
        for (let i = 0; i < datas.length; i++){
            data = datas[i];
            functions.push(saveOne(data));
            quantity_detial.quantityEditChecking(data,'bills',functions);
        }
        async.parallel(functions, callback);
    };

    getItemTemplate (callback) {
        let data = new bills;
        /* to do: 需要根据标准配置库填充fees和flags字段，是否需要更多的参数？ */
        callback(0, '', data);
    };

    allocIDs (IDStep, callback) {
        counter.counterDAO.getIDAfterCount(counter.moduleName.bills, IDStep, function(err, highID){
            let lowID = highID - IDStep + 1;
            callback(0, '', {lowID: lowID, highID: highID});
        });
    };
    //zhong 2017-9-1
    updateCharacterContent(findSet, updateObj, txtObj, callback) {
        let updateSet = {};
        updateSet[updateObj.field] = updateObj.updateArr;
        if(txtObj && typeof txtObj !== 'undefined'){
            updateSet[txtObj.field] = txtObj.text;
        }
       bills.update(findSet, updateSet, function (err) {
           if(err){
               callback(1, '更新失败');
           }
           else{
               callback(0, '更新成功');
           }
       });
    };
};

module.exports = new billsModel();