/**
 * Created by Zhong on 2017/11/13.
 */
//default setting
let defaultDecimal = {
    min: 0,
    max: 6,
    _def: {//editable: 开放给用户编辑的
        bills: {editable: true, data: {unitPrice: 2, totalPrice: 2}},
        ration: {editable: true, data: {quantity: 4, unitPrice: 2, totalPrice: 2}},
        glj: {editable: true, data: {quantity: 4, unitPriceHasMix: 2, unitPrice: 3}},
        material: {editable: false, data: 5},
        feeRate: {editable: true, data: 3},
        quantity_detail: {editable: false, data: 4},
        process: {editable: false, data: 6}
    }
};

let decimalObj = Object.create(null);

decimalObj.decimal = function (field, node) {
    if(isDef(field)){
        if(field.sameText('unitFee')){
            field = 'unitPrice';
        }
        else if(field.sameText('totalFee')){
            field = 'totalPrice';
        }
    }
    if(!isDef(node)){
        if(!isDef(field)){
            return this.process;
        }
        let fields = field.split('.');
        let fieldDecimal = fields.length === 2 ? this[fields[0]][fields[1]] : this[fields[0]];
        return  fieldDecimal ? fieldDecimal : this.process;
    }
    else {
        if(node.sourceType === projectObj.project.Bills.getSourceType()){
            if(field === 'quantity'){
                return billsQuanDecimal.decimal(node.data.unit);
            }
            else {
                return returnV(this['bills'][field], this.process);
            }
        }
        else if(node.sourceType === projectObj.project.Ration.getSourceType()){
            return returnV(this['ration'][field], this.process);
        }
        else if(node.sourceType === projectObj.project.ration_glj.getSourceType()){
            return returnV(this['glj'][field], this.process);
        }
    }
    return  this[field]? this[field] : this.process;
};

/*decimalObj.decimal = function (field, node) {
    if(isDef(field)){
        if(field === 'feeRate'||field==="quantity_detail"){
            return this[field];
        }
        else if (field.sameText('unitFee')) field = 'unitPrice'
        else if (field.sameText('totalFee')) field = 'totalPrice';

        if(isDef(node)){
            if(node.sourceType === projectObj.project.Bills.getSourceType()){
                if(field === 'quantity'){
                    return billsQuanDecimal.decimal(node.data.unit);
                }
                else {
                    return returnV(this['bills'][field], this.process);
                }
            }
            else if(node.sourceType === projectObj.project.Ration.getSourceType()){
                return returnV(this['ration'][field], this.process);
            }
            else if(node.sourceType === projectObj.project.ration_glj.getSourceType()){
                return returnV(this['glj'][field], this.process);
            }
        }
    }
    return  this[field]?this[field]:this.process;
};*/

function returnV(v, r){
    if(isDef(v)){
        return v;
    }
    return r;
}

function isUndef(v) {
    return v === undefined || v === null;
}

function isDef(v){
    return v !== undefined && v !== null;
}

function isObj(v){
    return isDef(v) && typeof v === 'object';
}

function isNum(v){
    return isDef(v) && !isNaN(v);
}

function isInt(v){
    return isNum(v) && v % 1 === 0;
}

function isValidDigit(v){
    return isInt(v) && v >= defaultDecimal.min && v <= defaultDecimal.max;
}

//newV用户可编辑数据
function toUpdateDecimal(orgV, newV){
    let rst = false;
    reCompare(orgV, newV);
    function reCompare(orgV, newV){
        for(let attr in newV){
            if(Object.keys(newV[attr]).length > 0){
                if(isUndef(orgV[attr])){
                    rst =  true;
                    return;
                }
                else{
                    reCompare(orgV[attr], newV[attr]);
                }
            }
            else {
                if(isUndef(orgV[attr]) || parseInt(newV[attr]) !== parseInt(orgV[attr])){
                    rst = true;
                    return;
                }
            }
        }
    }
    return rst;
}

function setDecimal(_digits, data){
    if(isDef(data)){
        for(let attr in data){
            _digits[attr] = returnV(data[attr], defaultDecimal['_def'][attr]['data']);
        }
    }
    else {
        for(let attr in defaultDecimal['_def']){
            _digits[attr] = defaultDecimal['_def'][attr]['data'];
        }
    }
}

//获取decimalPanel中要展示的数据
function m_getInitData(data){
    let rst = Object.create(null);
    for(let attr in defaultDecimal['_def']){
        if(defaultDecimal['_def'][attr]['editable'] && isDef(data[attr])){
            rst[attr] = data[attr];
        }
    }
    return rst;
}
//获取小数位数panel里的数据
function m_getDecimalData(inputs){
    let rst = Object.create(null);
    for(let i = 0, len = inputs.length ; i < len; i++){
       let name = $(inputs[i]).attr('name');
        let attrs = name.split('-');
        if(attrs.length > 1){
            if(isUndef(rst[attrs[0]])){
                rst[attrs[0]] = Object.create(null);
            }
            if(isDef(rst[attrs[0]])) {
                rst[attrs[0]][attrs[1]] = parseInt($(inputs[i]).val());
            }
        }
        else {
            rst[attrs[0]] = parseInt($(inputs[i]).val());
        }
    }
    for(let attr in defaultDecimal['_def']){
        if(!defaultDecimal['_def'][attr]['editable']){
            rst[attr] = defaultDecimal['_def'][attr]['data'];
        }
    }
    return rst;
}

function v_initPanel(data){
    if(this.isDef(data)){
        for(let attr in data){
            if(this.isObj(data[attr])){
                for(let subAttr in data[attr]){
                    let str = attr + '-' + subAttr;
                    let jqs = 'input[name="' + str + '"]';
                    $(jqs).val(data[attr][subAttr]);
                    $(jqs).attr('min', defaultDecimal.min);
                    $(jqs).attr('max', defaultDecimal.max);
                }
            }
            else {
                let str = attr + '';
                let jqs = 'input[name="' + str + '"]';
                $(jqs).val(data[attr]);
                $(jqs).attr('min', defaultDecimal.min);
                $(jqs).attr('max', defaultDecimal.max);
            }
        }
    }
}

function e_validIn(inputs){
    for(let i = 0, len = inputs.length; i < len; i++){
        let orgV = $(inputs[i]).val();
        $(inputs[i]).bind('input', function () {
            let v = $(this).val();
            let inputName = $(this).attr('name');
            if(v.trim().length === 0 || !isValidDigit(v)){
                alert('小数位数范围在0-6！');
                $(this).val(orgV);
            }
            else{
                orgV = v;
                //清单单价、合价 与定额单价、合价同步
                if(inputName === 'bills-unitPrice'){
                    $("input[name='ration-unitPrice']").val(v);
                }
                else if(inputName === 'bills-totalPrice'){
                    $("input[name='ration-totalPrice']").val(v);
                }
                else if(inputName === 'ration-unitPrice'){
                    $("input[name='bills-unitPrice']").val(v);
                }
                else if(inputName === 'ration-totalPrice'){
                    $("input[name='bills-totalPrice']").val(v);
                }
            }
        });
    }
}

function e_bindCof(btn){
    btn.bind('click', function () {
        //获取更新的数据
        let updateDecimal = m_getDecimalData($('input', '#poj-settings-decimal'));
        if(toUpdateDecimal(decimalObj, updateDecimal)){
            a_updateDigits(updateDecimal);
        }
    });
}

function e_unbindCof(btn){
    btn.unbind();
}

function a_updateDigits(updateDecimal){
    let url = '/pm/api/updateProjects';
    let data = {
        updateType: 'update',
        updateData: {
            ID: parseInt(scUrlUtil.GetQueryString('project')),
            'property.decimal': updateDecimal
        }
    };
    let postData = {
        user_id: userID,
        updateData: [data]
    };
    let scCaller = function (resultData) {
        //update data
        setDecimal(decimalObj, updateDecimal);
        let v_data = m_getInitData(decimalObj);
        v_initPanel(v_data);
    };
    let errCaller = function () {
        alert('更新小数位数失败！');
        let v_data = m_getInitData(decimalObj);
        v_initPanel(v_data);
    };
    CommonAjax.post(url, postData, scCaller, errCaller);
}

$(document).ready(function () {
    $('#poj-set').on('shown.bs.modal', function (e) {
        let v_data = m_getInitData(decimalObj);
        v_initPanel(v_data);
        let headerText =  projectObj.project.projectInfo.property && projectObj.project.projectInfo.property.valuationType == "bill"?"项目节":"清单";//项目属性-小数位数，“清单”改文字为“项目节”，工程量清单中保持不变。
        $("#bills_decimal_header").text(headerText);
    });

    //绑定确定按钮
    //e_bindCof($('#property_ok'));
    //绑定小数位数输入控制
    e_validIn($('input', '#poj-settings-decimal'));
});
