/**
 * Created by Zhong on 2017/12/21.
 */

const mongoose = require('mongoose');
const compleRationSectionTreeModel = mongoose.model('complementary_ration_section_tree');
const compleRationModel = mongoose.model('complementary_ration_items');
let counter = require('../../../public/counter/counter');
let stdSectionTreeModel = require ('../../ration_repository/models/ration_section_tree').Model;
const uuidV1 = require('uuid/v1');
const sectionTemplateModel = mongoose.model('complementary_ration_section_templates');

class SectionTreeDao {
    //从补充定额章节树模板中拷贝数据到用户的补充定额章节树中
    async copyDataFromTemplate(userId, compilationId){
        const count = await compleRationSectionTreeModel.count({userId, compilationId});
        if (count > 0) {
            return;
        }
        let templateData = await sectionTemplateModel.find({compilationId: compilationId});
        if (templateData.length > 0) {
            let insertDatas = [],
                uuidMapping = {};
            //将ID替换成UUID
            for (let temData of templateData) {
                uuidMapping[temData.ID] = uuidV1();
            }
            for(let temData of templateData) {
                let insertD = {
                    userId: userId,
                    compilationId: compilationId,
                    name: temData.name,
                    ID: uuidMapping[temData.ID],
                    ParentID: uuidMapping[temData.ParentID] || -1,
                    NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
                };
                insertDatas.push(insertD);
            }
            //插入数据
            await compleRationSectionTreeModel.insertMany(insertDatas);
        }
    }

    getNewTreeID(callback){
        counter.counterDAO.getIDAfterCount(counter.moduleName.rationTree, 1, function (err, result) {
            if(err){
                callback(err, null);
            }
            else {
                callback(0, result.sequence_value);
            }
        });

    }

    async getComplementaryTree (userId, compilationId) {
        const treeData = await compleRationSectionTreeModel.find({userId, compilationId}).lean();
        return treeData;
    }

    async getRationTree(userId, compilationId, rationRepId, type, callback) {
        //区分要获取的是标准的数据还是补充的数据
        const rationLibType = {
            complementary: 0,
            std: 1
        };
        try {
            let treeData;
            if (type === rationLibType.complementary) {
                treeData = await compleRationSectionTreeModel.find({userId: userId, compilationId: compilationId, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]}).lean();
            } else {
                treeData = await stdSectionTreeModel.find({rationRepId: rationRepId}).lean();
            }
            callback(0, treeData);
        } catch (err) {
            console.log(err);
            callback(1, null);
        }
    }

    //获取补充定额拼接章节树
   /* async getRationTree(userID, rationRepId, callback){
        try{
            let stdSectionTree = await stdSectionTreeModel.find({rationRepId: rationRepId, $or: [{isDeleted: null}, {isDeleted: false}]});
            let compleSectionTree = await compleRationSectionTreeModel.find({userId: userID, rationRepId: rationRepId, deleteInfo: null});
            let dropPids = [], rstCompleSectionTree = [];
            //mark std
            for(let i = 0, len = stdSectionTree.length; i < len; i++){
                stdSectionTree[i]._doc.type = 'std';
            }
            for(let i = 0, len = compleSectionTree.length; i < len; i++){
                //mark complementary
                compleSectionTree[i]._doc.type = 'complementary';
                if(compleSectionTree[i]['isFirst']){
                    let updateSection = getUpdateSection(compleSectionTree[i]['ParentID'], stdSectionTree);
                    if(updateSection) {
                        updateSection._doc.NextSiblingID = compleSectionTree[i]['ID'];
                    }
                    else if(!updateSection && compleSectionTree[i]['ParentID'] !== -1){
                        dropPids.push(compleSectionTree[i]['ParentID']);
                    }
                }
            }
            function getUpdateSection(pid, datas){
                for(let i = 0, len = datas.length; i < len; i++){
                    if(datas[i]['ParentID'] === pid && datas[i]['NextSiblingID'] === -1){
                        return datas[i];
                    }
                }
                return null;
            }
            //返回父节点未被删除的
            for(let i = 0, len = compleSectionTree.length; i < len; i++){
                if(dropPids.indexOf(compleSectionTree[i]['ParentID']) === -1){
                    rstCompleSectionTree.push(compleSectionTree[i]);
                }
            }
            callback(0, stdSectionTree.concat(rstCompleSectionTree));
        }
        catch (err){
            callback(err, null);
        }
    }*/

    async updateSection(userID, compilationId, updateData, callback){
        try{
            for(let i = 0, len = updateData.length; i < len; i++){
                let updateObj = updateData[i];
                if(updateObj.updateType === 'new'){
                    updateObj.updateData.userId = userID;
                    updateObj.updateData.compilationId = compilationId;
                    await compleRationSectionTreeModel.create(updateObj.updateData);
                }
                else if(updateObj.updateType === 'update'){
                    if(!updateObj.updateData.deleteInfo){
                        await compleRationSectionTreeModel.update({userId: userID, ID: updateObj.updateData.ID}, updateObj.updateData);
                    } else {
                        await compleRationSectionTreeModel.remove({userId: userID, ID: updateObj.updateData.ID});
                    }
                }
            }
            callback(0, 'success');
        }
        catch(err){
            callback(err, null);
        }
    }
}

export default SectionTreeDao;
