/**
 * Created by Mai on 2017/1/18.
 */
import UnitPriceFileModel from "../../glj/models/unit_price_file_model";
let counter = require("../../../public/counter/counter.js");

let newProjController = require('../controllers/new_proj_controller');
let copyProjController = require('../controllers/copy_proj_controller');
let feeRateFacade = require('../../fee_rates/facade/fee_rates_facade');
let logger = require("../../../logs/log_helper").logger;

let Projects = require("./project_schema");
let projectType = {
    folder: 'Folder',
    tender: 'Tender',
    project: 'Project',
    engineering: 'Engineering',
};

let ProjectsDAO = function(){};

ProjectsDAO.prototype.getUserProjects = function(userId, callback){
    Projects.find({'$or': [{'userID': userId, 'deleteInfo': null}, {'userID': userId, 'deleteInfo.deleted': {'$in': [null, false]}}]}, '-_id', function(err, templates){
        if (err) {
            callback(1, 'Error', null);
        } else {
            callback(0, '', templates);
        }
    });
};

ProjectsDAO.prototype.getUserProject = function (userId, ProjId, callback) {
    Projects.findOne({userID: userId, ID: ProjId}, '-_id', function(err, template){
        if (err) {
            callback(1, '找不到标段数据', null);
        } else {
            callback(0, '', template);
        }
    });
}

ProjectsDAO.prototype.updateUserProjects = async function(userId, datas, callback){
    let data, project, updateLength = 0, hasError = false, deleteInfo = null, i, newProject;
    let updateAll = function (err) {
            if (!err){
                updateLength += 1;
                if (updateLength === datas.length) {
                    callback(0, '', datas);
                }
            } else {
                hasError = true;
                console.log(err);
                callback(1, '提交数据出错.', null);
            }
        };
    if (datas){
        for (i = 0; i < datas.length && !hasError; i++){
            data = datas[i];
            if (data.updateData.name !== undefined) {
                data.updateData.name = data.updateData.name.trim();
            }

            if (data.updateType === 'update') {
                Projects.update({userID: userId, ID: data.updateData.ID}, data.updateData, updateAll)
            } else if (data.updateType === 'new') {
                data.updateData['userID'] = userId;
                data.updateData['createDateTime'] = new Date();
                // 如果没有选中单价文件则新增单价文件
                if (data.updateData.projType === projectType.tender && data.updateData.property !== null &&
                    Object.keys(data.updateData.property.unitPriceFile).length > 0 &&
                    data.updateData.property.unitPriceFile.id === '') {
                    let unitPriceFileModel = new UnitPriceFileModel();

                    let insertData = {
                        name: data.updateData.name,
                        project_id: data.updateData.ID
                    };
                    let addResult = await unitPriceFileModel.add(insertData);
                    if (!addResult) {
                        callback(1, '新增单价文件失败.', null);
                        return;
                    }
                    data.updateData.property.unitPriceFile.id = addResult.id + '';
                }
                newProject = new Projects(data.updateData);
                // 查找同级是否存在同名数据
                let exist = await this.isExist(data.updateData.name, data.updateData.ParentID);
                if (exist) {
                    callback(1, '同级目录已存在相同名称数据.', null);
                    return;
                }
                if(data.updateData.projType==='Tender'){
                    let  feeRateFileID = await feeRateFacade.newFeeRateFile(data.updateData);
                    newProject.property.feeFile = feeRateFileID?feeRateFileID:-1;
                }
                newProject.save(async function (err, result) {
                    if (!err && result._doc.projType === projectType.tender) {
                        newProjController.copyTemplateData(data.updateData.property, newProject.ID, updateAll);
                    } else {
                        updateAll(err);
                    }
                });
            } else if (data.updateType === 'delete') {
                deleteInfo = {};
                deleteInfo['deleted'] = true;
                deleteInfo['deleteDateTime'] = new Date();
                deleteInfo['deleteBy'] = userId;
                data.updateData['deleteInfo'] = deleteInfo;
                Projects.update({userID: userId, ID: data.updateData.ID}, data.updateData, updateAll);
            } else {
                hasError = true;
                callback(1, '提交数据错误.', null);
            }
        }
    }
};
ProjectsDAO.prototype.copyUserProjects = function (userId, datas, callback) {
    let data, project, updateLength = 0, hasError = false, deleteInfo = null, tempType = 1, i;
    let updateAll = function (err) {
        if (!err){
            updateLength += 1;
            if (updateLength === datas.length) {
                callback(0, '', datas);
            }
        } else {
            hasError = true;
            callback(1, '提交数据出错.', null);
        }
    };
    if (datas) {
        for (i = 0; i < datas.length && !hasError; i++) {
            data = datas[i];
            if (data.updateType === 'update') {
                Projects.update({userID: userId, ID: data.updateData.ID}, data.updateData, updateAll)
            } else if (data.updateType === 'copy') {
                data.updateData['userID'] = userId;
                data.updateData['createDateTime'] = new Date();
                let newProject = new Projects(data.updateData);
                newProject['srcProjectId'] = data.srcProjectId;
                newProject.save(function (err, result) {
                    if (!err && result._doc.projType === 'Tender') {
                        copyProjController.copyProjectData(newProject.srcProjectId, result._doc.ID, updateAll);
                    } else {
                        updateAll(err);
                    }
                });
            } else {
                hasError = true;
                callback(1, '提交数据错误', null);
            }
        }
    }
};

ProjectsDAO.prototype.rename = async function (userId, data, callback){
    try {
        if (data.id === undefined || data.id === '') {
            throw '数据错误!';
        }
        if (data.newName === undefined || data.newName === '') {
            throw '请填写名称!';
        }

        // 查找同级是否存在同名数据
        let exist = await this.isExist(data.newName, data.parentID);
        if (exist) {
            throw '同级目录已存在相同名称数据';
        }

        Projects.update({userID: userId, ID: data.id}, {name: data.newName}, function(err){
            if (err){
                throw '项目不存在';
            }
        });
    } catch (error) {
        callback(1, error, null);
        return;
    }
    callback(0, '');
};

ProjectsDAO.prototype.beforeOpenProject = function (userId, projectId, updateData, callback){
    updateData['recentDateTime'] = new Date();
    Projects.update({userID: userId, ID: projectId}, updateData, function(err){
        if (err){
            callback(1, '项目不存在.');
        } else {
            callback(0, '');
        }
    });
};

ProjectsDAO.prototype.getNewProjectID = function (count, callback) {
    counter.counterDAO.getIDAfterCount(counter.moduleName.project, count, function (err, result) {
        let highID = result.value.sequence_value;
        if (!err) {
            callback(0, '', {lowID: highID - count + 1, highID: highID});
        } else {
            callback(1, '获取主键失败', null);
        }
    });
};

ProjectsDAO.prototype.getProject = function (key, callback) {
    if (callback) {
        Projects.findOne({'_id': key}, function (err, result) {
            if (err) {
                callback(1, '查找标段失败');
            } else {
                callback(0, result);
            }
        });
    } else {
        return Projects.findOne({'ID': key}).exec();
    }
};

/**
 * 整理工程专业对应标准库数据
 *
 * @param {Object} data
 * @return {Boolean}
 */
ProjectsDAO.prototype.isExist = async function(name, parentID) {
    parentID = parseInt(parentID);
    if (name === '' || isNaN(parentID)) {
        return true;
    }
    let count = await Projects.count({ParentID: parentID, name: name});
    return count > 0;
};

/**
 * 获取对应建设项目下所有的单位工程id
 *
 * @param {Number} projectId
 * @return {Promise}
 */
ProjectsDAO.prototype.getTenderByProjectId = async function(projectId) {
    let result = [];
    // 首先获取对应的单位工程id
    let engineeringData = await Projects.find({ParentID: projectId});
    if (engineeringData.length <= 0) {
        return result;
    }

    let engineeringIdList = [];
    for(let tmp of engineeringData) {
        engineeringIdList.push(tmp.ID);
    }

    // 查找对应的单位工程id
    let tenderData = await Projects.find({ParentID: {$in: engineeringIdList}});
    if (tenderData.length <= 0) {
        return result;
    }

    for(let tmp of tenderData) {
        result.push(tmp.ID);
    }

    return result;
};

/**
 * 根据单价文件id获取对应的标段数据
 *
 * @param {Number} unitPriceFileId
 * @return {Promise}
 */
ProjectsDAO.prototype.getTenderByUnitPriceFileId = async function(unitPriceFileId) {
    let result = [];

    unitPriceFileId = parseInt(unitPriceFileId);
    if (isNaN(unitPriceFileId) && unitPriceFileId <= 0) {
        return result;
    }

    let condition = {projType: 'Tender', "property.unitPriceFile.id": unitPriceFileId + ''};
    result = await Projects.find(condition);

    return result;
};

/**
 * 根据项目id获取单价文件列表id
 *
 * @param {Number} projectId
 * @return {Promise}
 */
ProjectsDAO.prototype.getUnitPriceFileId = async function(projectId) {
    let result = 0;
    let projectData = await Projects.findOne({ID: projectId});
    if (projectData === null) {
        return result;
    }

    result = projectData.property.unitPriceFile.id;
    return result;
};

/**
 * 获取当前用户的建设项目数据
 *
 * @param {Number} userId
 * @return {Promise}
 */
ProjectsDAO.prototype.getUserProjectData = async function(userId) {
    let projectList = await Projects.find({
        '$or': [
            {'userID': userId, 'deleteInfo': null, projType: 'Project'},
            {'userID': userId, 'deleteInfo.deleted': {'$in': [null, false]}, projType: 'Project'}
            ]
    }, {_id: 0, name: 1, ID: 1});

    return projectList;
};

/**
 * 更改项目属性中的单价文件
 *
 * @param {Number} projectId
 * @param {Object} changeInfo
 * @return {Promise}
 */
ProjectsDAO.prototype.changeUnitPriceFileInfo = async function(projectId, changeInfo) {
    projectId = parseInt(projectId);
    if (isNaN(projectId) || projectId <= 0) {
        return false;
    }
    let result = await Projects.update({ID: projectId}, {"property.unitPriceFile": changeInfo});

    return result.ok === 1;
};

module.exports ={
    project: new ProjectsDAO(),
    projType: projectType
};