/**
 * Created by Zhong on 2017/10/16.
 */
/*
 弹出组成物窗口 组成物表
 * */
let componentOprObj = {
    treeObj:null,
    rootNode: null,//分类树根节点
    workBook: null,
    selectedList: [],//选中的组成物
    setting: {
        owner: "components",
        header: [
            {headerName:"选择", headerWidth: 40, dataCode: "select", hAlign: "center", vAlign: "center"},
            {headerName:"编码",headerWidth:80,dataCode:"code", dataType: "String", formatter: "@", hAlign: "left", vAlign: "center"},
            {headerName:"名称",headerWidth:120,dataCode:"name", dataType: "String", hAlign: "left", vAlign: "center"},
            {headerName:"规格型号",headerWidth:80,dataCode:"specs", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"单位",headerWidth:80,dataCode:"unit", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"单价",headerWidth:80,dataCode:"basePrice", dataType: "Number", formatter: "0.00", hAlign: "right", vAlign: "center"},
            {headerName:"类型",headerWidth:80,dataCode:"gljType", dataType: "String",  hAlign: "center", vAlign: "center"}
        ]
    },
    //生成列头（多单价）
    initHeaders: function (priceProperties) {
        let headers = [
            {headerName:"选择", headerWidth: 40, dataCode: "select", hAlign: "center", vAlign: "center"},
            {headerName:"编码",headerWidth:80,dataCode:"code", dataType: "String", formatter: "@", hAlign: "left", vAlign: "center"},
            {headerName:"名称",headerWidth:120,dataCode:"name", dataType: "String", hAlign: "left", vAlign: "center"},
            {headerName:"规格型号",headerWidth:80,dataCode:"specs", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"单位",headerWidth:80,dataCode:"unit", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"类型",headerWidth:80,dataCode:"gljType", dataType: "String",  hAlign: "center", vAlign: "center"}

        ];
        //生成单价列
        if(!priceProperties || priceProperties.length === 0){
            headers.push({headerName:"定额价",headerWidth:80,dataCode:"basePrice", dataType: "Number", formatter: "0.00", hAlign: "right", vAlign: "center"});
        }
        else {
            for(let priceProp of priceProperties){
                let colData = {
                    headerName: priceProp.price.dataName,
                    headerWidth: 100,
                    dataCode: priceProp.price.dataCode,
                    dataType: 'Number',
                    formatter: '0.00',
                    hAlign: 'right',
                    vAlign: 'center'
                };
                headers.push(colData);
            }
        }
        let tailHeaders = [
        ];
        headers = headers.concat(tailHeaders);
        return headers;
    },
    buildSheet: function (container) {
        let me = componentOprObj;
        //生成人材机组成物表格列头
        me.setting.header = me.initHeaders(priceProperties);
        //生成人材机组成物列映射
        sheetCommonObj.initColMapping(me, me.setting.header);
        repositoryGljObj.initPriceCols.call(me, priceProperties, me.colMapping);
        me.workBook = sheetCommonObj.buildSheet(container, me.setting, 30);
        if(priceProperties && priceProperties.length > 0){
            me.workBook.getSheet(0).frozenColumnCount(6);
        }
        me.workBook.getSheet(0).setColumnWidth(0, 20, GC.Spread.Sheets.SheetArea.rowHeader);
        me.workBook.getSheet(0).setFormatter(-1, 1, "@", GC.Spread.Sheets.SheetArea.viewport);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.EditStarting, me.onCellEditStart);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
        me.workBook.bind(GC.Spread.Sheets.Events.ButtonClicked, me.onButtonClicked);//复选框点击事件
        me.workBook.getSheet(0).getRange(-1, 0, -1, 1).cellType(new GC.Spread.Sheets.CellTypes.CheckBox());
        me.componentsBtnOpr($('#componentsConf'));
    },
    onClipboardPasting: function (sender, args) {
        args.cancel = true;
    },
    onCellEditStart: function (sender, args) {
        args.cancel = true;
    },
    onButtonClicked: function (sender, args) {
        let me = componentOprObj, re = repositoryGljObj;
        let val = args.sheet.getValue(args.row, args.col);
        let thisComponent = me.currentCache[args.row];
        thisComponent.isChecked = val;
        if(args.sheet.isEditing()){
            args.sheet.endEdit(true);
        }
        else{
            //维护选中组成物列表
            if(val === true){
                let isExist = false;
                for(let i = 0, len = me.selectedList.length; i < len; i++){
                    if(me.selectedList[i].ID === thisComponent.ID){
                        isExist = true;
                        break;
                    }
                }
                if(!isExist){
                    me.selectedList.push(thisComponent);
                }
            }
            else if(val === false){
                for(let i = 0, len = me.selectedList.length; i < len; i++){
                    if(me.selectedList[i].ID === thisComponent.ID){
                        me.selectedList.splice(i, 1);
                        break;
                    }
                }
            }
        }
    },
    setShowGljList: function (gljList, clearChecked) {
        let that = repositoryGljObj, me = componentOprObj;
        for(let i = 0; i < gljList.length; i++){
            if(machineAllowComponent.includes(that.currentGlj.gljType) && machineComponent.includes(gljList[i].gljType) ||
                materialAllowComponent.includes(that.currentGlj.gljType) && gljList[i].gljType === 201){
                let isExist = false;
                for(let j = 0; j < that.currentComponent.length; j++){
                    if(that.currentComponent[j].ID === gljList[i].ID){
                        isExist = true;
                        break;
                    }
                }
                if(!isExist){
                    if(clearChecked){
                        gljList[i].isChecked = false;
                    }
                }
                else {
                    gljList[i].isChecked = true;
                }
                me.showGljList.push(gljList[i]);
            }
        }
    },
    //初始默认radio
    initRadio: function () {
        let that = repositoryGljObj, me = componentOprObj;
        //初始化组成物列表
        me.selectedList = [].concat(that.currentComponent);
        //初始为所有工料机,机械类型可添加机械组成物，混凝土,砂浆、配合比可添加普通材料
        me.showGljList = [];
        me.setShowGljList(that.gljList, true);
        that.sortGlj(me.showGljList);

    },
    getParentCache: function (nodes) {
        let me = componentOprObj, rst = [];
        for(let i = 0; i < me.showGljList.length; i++){
            if(nodes.indexOf(me.showGljList[i].gljClass) !== -1){
                rst.push(me.showGljList[i]);
            }
        }
        rst.sort(function (a, b) {
            let rst = 0;
            if(a.code > b.code) rst = 1;
            else if(a.code < b.code)rst = -1;
            return rst;
        });
        return rst;
    },
    getCache: function() {
        let me = componentOprObj, rst = [];
        for (let i = 0; i < me.showGljList.length; i++) {
            if (me.showGljList[i].gljClass == me.gljCurTypeId) {
                rst.push(me.showGljList[i]);
            }
        }
        return rst;
    },
    showGljItems: function(data, type) {
        let me = componentOprObj, re = repositoryGljObj;
        if (me.workBook) {
            let cacheSection = data;
            re.sortGljDeep.call(me, data);
            sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
            sheetsOprObj.showData(me, me.workBook.getSheet(0), me.setting, cacheSection, re.distTypeTree);
            me.workBook.getSheet(0).setRowCount(cacheSection.length);
            cacheSection = null;
        }
    },
    //批量插入组成物
    batchUpdateComponent: function () {
        $.bootstrapLoading.start();
        let me = componentOprObj, that = gljComponentOprObj, re = repositoryGljObj,
            updateArr = [],
            IDMapping = {};
        let formData = new FormData();
        //当前工料机的工料机类型
        let currentGljType = re.currentGlj.gljType;
        let thisTypeGljList = _.filter(re.gljList, function (data) {
            return data.gljType == currentGljType;
        });
        for(let glj of thisTypeGljList){
            let gljComponent = glj.component ? glj.component : [];
            let newComponent = [];
            if(me.insertType === 'batch'){
                for(let selectedComponent of me.selectedList){
                    let isExist = false;
                    for(let gljPerComponent of gljComponent){
                        if(selectedComponent.ID === gljPerComponent.ID){
                            //newComponent.push({ID: selectedComponent.ID, consumeAmt: gljPerComponent.consumeAmt});
                            isExist = true;
                            break;
                        }
                    }
                    if(!isExist){
                        let newComponentObj = {ID: selectedComponent.ID};
                        that.initConsumeAmt(newComponentObj);
                        newComponent.push(newComponentObj);
                    }
                }
                newComponent = gljComponent.concat(newComponent);
            }
            else if(me.insertType === 'batchClear'){//去除消耗量为0的组成物
                for(let gljPerComponent of gljComponent){
                    if(hasConsumeAmt(gljPerComponent)){
                        if(!consumeAmtProperties || consumeAmtProperties.length === 0){
                            newComponent.push({ID: gljPerComponent.ID, consumeAmt: gljPerComponent.consumeAmt});
                        }
                        else {
                            newComponent.push({ID: gljPerComponent.ID, consumeAmtProperty: gljPerComponent.consumeAmtProperty});
                        }
                    }
                }
            }
            function hasConsumeAmt(component){
                if(!consumeAmtProperties || consumeAmtProperties.length === 0){
                    if(component.consumeAmt && component.consumeAmt != 0){
                        return true;
                    }
                }
                else {
                    if(component.consumeAmtProperty){
                        for(let field in component.consumeAmtProperty){
                            if(component.consumeAmtProperty[field] != 0){
                                return true;
                            }
                        }
                    }
                }
                return false;
            }
            IDMapping[glj.ID] = {component : newComponent};
            updateArr.push({ID: glj.ID, component: newComponent});
        }
        formData.append('compressData', LZString.compressToUTF16(JSON.stringify(updateArr)));
        $.ajax({
            url: 'api/batchUpdateComponent',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function(response){
                if (response.err === 0) {
                    //更新缓存数据
                    for(let glj of thisTypeGljList){
                        if(glj.ID === re.currentGlj.ID){
                            re.currentComponent =  re.getCurrentComponent(IDMapping[glj.ID]['component']);
                            sheetCommonObj.cleanData(that.workBook.getSheet(0), that.setting, -1);
                            sheetsOprObj.showData(that, that.workBook.getSheet(0), that.setting, re.currentComponent);
                        }
                        glj.component = IDMapping[glj.ID]['component'];
                    }
                    if($('#component').is(':visible')){
                        $('#component').modal('hide');
                    }
                    $.bootstrapLoading.end();
                } else {
                    if($('#component').is(':visible')){
                        $('#component').modal('hide');
                    }
                    $.bootstrapLoading.end();
                }
            },
            error: function(jqXHR){
                alert(`与服务器通信发生错误${jqXHR.status} ${jqXHR.statusText}`);
                $('#component').modal('hide');
                $.bootstrapLoading.end();
            }
        });

    },
    //组成物窗口按钮操作
    componentsBtnOpr: function (conf) {//确定、取消、关闭按钮
        let me = componentOprObj, that = gljComponentOprObj, re = repositoryGljObj;
        conf.click(function () {
            if(me.insertType === 'single'){
                let updateBasePrc = [];
                //添加选择添加的组成物
                let updateArr = [];
                let newComponent = [];
                for(let i = 0, len = me.selectedList.length; i < len; i++){
                    let isExist = false;
                    for(let j = 0, jLen = re.currentGlj.component.length; j < jLen; j++){
                        if(me.selectedList[i].ID === re.currentGlj.component[j].ID){
                            if(!consumeAmtProperties || consumeAmtProperties.length === 0){
                                let consumeAmt = typeof re.currentGlj.component[j].consumeAmt !== 'undefined' ? re.currentGlj.component[j].consumeAmt : 0;
                                newComponent.push({ID: me.selectedList[i].ID, consumeAmt: consumeAmt});
                            }
                            else{
                                let consumeAmtProperty = typeof re.currentGlj.component[j].consumeAmtProperty !== 'undefined' ? re.currentGlj.component[j].consumeAmtProperty : {};
                                newComponent.push({ID: me.selectedList[i].ID, consumeAmt: 0, consumeAmtProperty: consumeAmtProperty});
                            }
                            isExist = true;
                            break;
                        }
                    }
                    if(!isExist){
                        let obj = {ID: me.selectedList[i].ID};
                        that.initConsumeAmt(obj);
                        newComponent.push(obj);
                    }
                }
                re.currentGlj.component = newComponent;
                updateArr.push(re.currentGlj);
                that.updateComponent(updateArr);
                $('#component').modal('hide');
            }
            else {
                me.batchUpdateComponent();
            }
        });
    }
};

let componentTypeTreeOprObj = {
    onClick: function(event,treeId,treeNode) {
        let me = componentOprObj, re = repositoryGljObj, that = gljComponentOprObj, gljTypeId = treeNode.ID;
        if(me.gljCurTypeId !== treeNode.ID){
            me.gljCurTypeId = treeNode.ID;
            if (re.parentNodeIds["_pNodeId_" + treeNode.ID]) {
                me.currentOprParent = 1;
                me.currentCache = me.getParentCache(re.parentNodeIds["_pNodeId_" + treeNode.ID]);
            } else {
                me.currentOprParent = 0;
                me.currentCache = me.getCache();
            }
        }
        //me.showGljItems(me.showGljList, gljTypeId);
        me.showGljItems(me.currentCache, gljTypeId);
    }
}