/**
 * Created by Mai on 2017/6/5.
 */
var rationItem = require('../models/ration_item').Dao;;
let rationChapter = require('../models/ration_section_tree').Dao;
let asyncTool = require('async');
var callback = function(req, res, err, message, data){
    res.json({error: err, message: message, data: data});
};

module.exports = {
    getRationItem: function (req, res) {
        let rId = req.body.rationLibId, code = req.body.code;
        rationItem.getRationItem(rId, code).then(function (result) {
            let rationData = JSON.stringify(result._doc);
            rationData = JSON.parse(rationData);
            rationChapter.getRationChapter(rationData.rationRepId, rationData.sectionId).then(function (result) {
                rationData.chapter = result._doc;
                callback(req, res, null, '', rationData);
            }).catch(function (err, message) {
                callback(req, res, null, '', rationData);
            });
        }).catch(function (err, message) {
            callback(req, res, err, message, null);
        })
    },
    findRation: function (req, res) {
        var rId = req.body.rationLibId, keyword = req.body.keyword;
        rationItem.findRation(rId, keyword, function (err, message, rst) {
            if (err) {
                callback(req, res, err, message, null);
            } else {
                callback(req, res, 0, '', rst);
            }
        });
    },
    matchRation: function (req, res) {
        let rId = req.body.rationLibId, code = req.body.code;
        asyncTool.waterfall([
            function (callback) {
                rationItem.matchRation(rId, code, callback);
            },
            function (ration, callback) {
                if (ration) {
                    rationChapter.getRationChapter(rId, ration.sectionId).then(function(result, err) {
                        if (!err) {
                            ration.chapter = JSON.parse(JSON.stringify(result));
                            callback(err, ration);
                        } else {
                            callback(err, ration);
                        }
                    }).catch(

                    );
                } else {
                    callback(null, ration);
                }
            }
        ], function (err, result) {
            if (err) {
                callback(req, res, 1, err, null);
            } else {
                callback(req, res, 0, err, result);
            }
        });
    }
};