/**
 * 计价规则标准库业务逻辑
 *
 * @author CaiAoLin
 * @date 2017/8/31
 * @version
 */
import mongoose from "mongoose";
import BaseModel from "../../common/base/base_model";
import CompilationModel from "./compilation_model";
let stdRationLibModel = mongoose.model("std_ration_lib_map");
import {default as EngineeringConst, List as EngineeringList} from "../../common/const/engineering";

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

    /**
     * 获取标准库数据
     *
     * @param {Object} data
     * @param {Number} engineering
     * @return {Promise}
     */
    async getLib(data, engineering) {
        let result = {};
        if (data.length <= 0) {
            return result;
        }
        let id = '';
        for(let tmp of data) {
            if (tmp.engineering === engineering) {
                id = tmp.engineering_id;
                break;
            }
        }
        if (id === '') {
            return result;
        }
        let condition = {_id: id};
        return this.findDataByCondition(condition);
    }

    async getLibsByValuationID(valuationID){
        return this.findDataByCondition({valuationID:valuationID},null,false);
    }

    async deleteByValuationID(valuationID){
        return await this.db.delete({valuationID:valuationID});
    }


    //添加空的默认的所有标准库
    /**
     * @param valuationID
     * @returns {Promise.<*>}
     */
    async addStdLib(valuationID){
        let stdLibs = [];
        for(let eng of EngineeringList){
            let tem = {
                glj_col:{showAdjustPrice:false},
                valuationID:valuationID,
                name:eng.name,
                engineering:eng.value
            };
            stdLibs.push(tem);
        }
        let result = await this.db.create(stdLibs);
        return result;
    }

    async addEngineer(data){
        data.glj_col = {showAdjustPrice:false};
        if(data.compilationId && data.compilationId!=""){
            data.ration_lib = [];
            let rationList = await stdRationLibModel.find({compilationId:data.compilationId},['ID','dispName']);
            for(let i =0;i< rationList.length;i++){
                let tem = {
                    id:rationList[i].ID,
                    name:rationList[i].dispName,
                    isDefault:false
                };
                if(i == 0) tem.isDefault = true;
                data.ration_lib.push(tem);
            }
        }
        let result = await this.db.create(data);
        return result;
    }

    /**
     * 新增标准库
     *
     * @param {String} valuationId
     * @param {Object} data
     * @return {Promise}
     */
    async addLib(engineerId, data) {
        if(data.glj_col){
            data.glj_col =  JSON.parse(data.glj_col);
        }
        data.isInstall == 'true'?data.isInstall=true:data.isInstall=false;
        let result = false;
        data = this.filterLibData(data);
        try {
            let engineeringLib = await this.findDataByCondition({_id:engineerId});
            if(engineeringLib){
                // 存在则直接更新
                delete data.id;
                delete data.section;
                let condition = {_id: engineerId};
                result = await this.db.update(condition, data);
                result = result.ok === 1;
            }else {
                throw  new Error("找不到对应的工程专业");
            }

        } catch (error) {
            console.log(error);
            result = false;
        }

        return result;
    }

    /**
     * 过滤计价数据
     *
     * @param {Object} data
     * @return {Object}
     */
    filterLibData(data) {
        if (Object.keys(data).length <= 0 || data.section === undefined) {
            console.log('1');
            throw '数据有误';
        }
        data.engineering = parseInt(data.engineering);
        //需求修改，工程专业可以随便输入了
        //检测专业工程是否合法
   /*     let match = false;
        for(let index in EngineeringConst) {
            if (EngineeringConst[index] === data.engineering) {
                match = true;
                break;
            }
        }
        if (!match) {
            throw '工程专业错误';
        }*/

        // 判断标准清单
        data.bill_lib = this._validLib(data.bill_lib);

        // 判断定额库
        data.ration_lib = this._validLib(data.ration_lib);

        //设置默认定额库
        this.setDefaultRation(data);

        // 判断工料机库
        data.glj_lib = this._validLib(data.glj_lib);

        // 判断清单指引库
        data.billsGuidance_lib = this._validLib(data.billsGuidance_lib);

        /*// 判断费率标准
        data.fee_lib = this._validLib(data.fee_lib);*/

        // 判断人工系数
        data.artificial_lib = this._validLib(data.artificial_lib);

        //判断工程特征库
        data.feature_lib = this._validLib(data.feature_lib);

        //判断累进区间库
        data.progressive_lib = this._validLib(data.progressive_lib);

        //判断车船税
        data.vvTax_lib = this._validLib(data.vvTax_lib);

        //计税方式组合
        data.tax_group = this._validLib(data.tax_group);

        return data;
    }

    /**
     * 校验库数据
     *
     * @param {Object} libData
     * @return {Object}
     */
    _validLib(libData) {
        let result = [];
        // 判断标准库
        if (libData === undefined || libData ===null ||libData === '') {
            return result;//throw '标准库不能为空'; 按新需求，标准库等不做非空判断
        }
        libData = libData instanceof Array ? libData : [libData];
        for(let tmp in libData) {
            result[tmp] = JSON.parse(libData[tmp]);
        }
        return result;
    }

    //设置默认定额库
    setDefaultRation(data){
        if(data.ration_lib && data.ration_lib.length>0){
            if(data.ration_isDefault && data.ration_isDefault != ""){
                for(let r of data.ration_lib){
                    r.id.toString() == data.ration_isDefault?r.isDefault = true:r.isDefault=false;
                }
            }else {
                data.ration_lib[0].isDefault = true;
            }
        }
    }


    /**
     * 获取对应标准库数量
     *
     * @param {Object} valuationData
     * @return {Object}
     */
    async getLibCount(valuationData) {
        let result = {};
        if (valuationData.engineering_list === undefined || valuationData.engineering_list.length <= 0) {
            return result;
        }

        // 整理需要查找的数据
        let findIdList = [];
        for(let engineering of valuationData.engineering_list) {
            findIdList.push(engineering.engineering_id);
        }

        let condition = {_id: {$in: findIdList}};
        let libData = await this.findDataByCondition(condition, null, false);
        if (libData === null) {
            return result;
        }

        // 整理数据
        let countData = {};
        for(let tmp of libData) {
            countData[tmp._id] = {
                bill_count: tmp.bill_lib.length,
                ration_count: tmp.ration_lib.length,
                glj_count: tmp.glj_lib.length,
                fee_count: tmp.fee_lib.length,
                artificial_count: tmp.artificial_lib.length,
                program_count: tmp.program_lib.length,
            };
        }


        for(let engineering of valuationData.engineering_list) {
            if (countData[engineering.engineering_id] !== undefined) {
                result[engineering.engineering] = countData[engineering.engineering_id];
            }
        }

        return result;
    }

}

export default EngineeringLibModel;
