/**
 * Created by chen on 2017/7/25.
 */

var gljContextMenu = {
    selectedRow :null,
    selectedCol:null,
    clipboard:null,
    loadGLJSpreadContextMenu: function () {
        $.contextMenu({
            selector: '#subSpread',
            build: this.onbuild,
            items: {
                "replace_glj": {
                    name: '替换',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        var sheetData = gljOprObj.sheetData;
                        const selected = projectObj.project.mainTree.selected;
                        if(gljOprObj.isInstallationNode(selected) || OVER_HEIGHT.isOverHeight(selected)){
                            return true;
                        }
                        if(subSpread.getActiveSheetIndex()==0&&sheetData!=null&&sheetData.length>0&&gljContextMenu.selectedRow<sheetData.length){
                            if(sheetData[gljContextMenu.selectedRow].isMixRatio==true){
                                return true;
                            }
                            return false;
                        }
                        return true;
                    },
                    callback: function () {
                        getGLJData('replace', null, true, null);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='ration_glj';
                    }
                },
                "add_glj": {
                    name: '添加',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        var selected = projectObj.project.mainTree.selected;
                        var sheetData = gljOprObj.sheetData;
                        if(selected){
                            if(selected.sourceType!=ModuleNames.ration){
                                return true;
                            }else if(selected.data.type!=rationType.ration){
                                return true;
                            }
                        }
                        if(subSpread.getActiveSheetIndex()==0&&sheetData!=null&&sheetData.length>0&&gljContextMenu.selectedRow<sheetData.length){
                            if(sheetData[gljContextMenu.selectedRow].isMixRatio==true){
                                return true;
                            }
                        }
                        return false;
                    },
                    callback:function () {
                        getGLJData('add', null, true, null);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='ration_glj';
                    }
                },
                "delete_glj": {
                    name: '删除',
                    icon: 'fa-remove',
                    disabled: function () {
                        var sheetData = gljOprObj.sheetData;
                        const selected = projectObj.project.mainTree.selected;
                        if(gljOprObj.isInstallationNode(selected) || OVER_HEIGHT.isOverHeight(selected)){
                            return true;
                        }
                        if(subSpread.getActiveSheetIndex()==0&&sheetData!=null&&sheetData.length>0&&gljContextMenu.selectedRow<sheetData.length){
                            if( sheetData[gljContextMenu.selectedRow].isMixRatio==true){
                                return true;
                            }
                            return false;
                        }else {
                            return true;
                        }

                    },
                    callback: function () {
                        var sheetData = gljOprObj.sheetData;
                        var deleteRow = sheetData[gljContextMenu.selectedRow];
                        projectObj.project.ration_glj.updataOrdelete(deleteRow);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='ration_glj';
                    }
                },
                "m_replace_glj": {
                    name: '批量替换',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        let sheetData = gljOprObj.sheetData;
                        const selected = projectObj.project.mainTree.selected;
                        if(gljOprObj.isInstallationNode(selected) || OVER_HEIGHT.isOverHeight(selected)){
                            return true;
                        }
                        if(subSpread.getActiveSheetIndex()==0&&sheetData!=null&&sheetData.length>0&&gljContextMenu.selectedRow<sheetData.length){
                            if(sheetData[gljContextMenu.selectedRow].isMixRatio==true){
                                return true;
                            }
                            return false;
                        }
                        return true;
                    },
                    callback: function () {
                        getGLJData('m_replace', null, true, null);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='ration_glj';
                    }
                },
                "addMixRatio": {
                  name: '添加组成物',
                  icon: 'fa-sign-in',
                  disabled: function () {
                      let sheetData = gljOprObj.sheetData;
                      const selected = projectObj.project.mainTree.selected;
                      if(gljOprObj.isInstallationNode(selected) || OVER_HEIGHT.isOverHeight(selected)){
                          return true;
                      }
                      if(subSpread.getActiveSheetIndex()==0&&sheetData!=null&&sheetData.length>0&&gljContextMenu.selectedRow<sheetData.length){
                          if(sheetData[gljContextMenu.selectedRow].isMixRatio == true) return false;
                          if(!sheetData[gljContextMenu.selectedRow].subList)  return true;
                          return false;
                      }
                      return true;
                  },
                  callback: function () {
                      let t = gljOprObj.sheetData[gljContextMenu.selectedRow];
                      if(t.isMixRatio){
                        projectGljObject.selectedProjectGLJ = t.parentGLJ;
                        for(let rg of  gljOprObj.sheetData){
                          if(rg.projectGLJID == t.parentGLJ.id) {
                            projectGljObject.subList = rg.subList;
                            break;
                          }
                        } 

                      }else{
                        projectGljObject.selectedProjectGLJ = t;
                        projectGljObject.subList = t.subList;
                      }
                      getGLJData('addMix', null, true, null);
                  },
                  visible: function(key, opt){
                      return subSpread.getActiveSheet().name()=='ration_glj';
                  }
                },
                "deleteMixRatio": {
                  name: '删除组成物',
                  icon: 'fa-sign-in',
                  disabled: function () {
                      let sheetData = gljOprObj.sheetData;
                      const selected = projectObj.project.mainTree.selected;
                      if(gljOprObj.isInstallationNode(selected) || OVER_HEIGHT.isOverHeight(selected)){
                          return true;
                      }
                      if(subSpread.getActiveSheetIndex()==0&&sheetData!=null&&sheetData.length>0&&gljContextMenu.selectedRow<sheetData.length){
                          if(sheetData[gljContextMenu.selectedRow].isMixRatio == true) return false;
                      }
                      return true;
                  },
                  callback: function () {
                     gljOprObj.deleteRatio(gljContextMenu.selectedRow);
                  },
                  visible: function(key, opt){
                      return subSpread.getActiveSheet().name()=='ration_glj';
                  }
                },
               "add_to_lib": {
                    name: '保存到我的人材机库',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        var sheetData = gljOprObj.sheetData;
                        const selected = projectObj.project.mainTree.selected;
                        if(gljOprObj.isInstallationNode(selected) || OVER_HEIGHT.isOverHeight(selected)){
                            return true;
                        }
                        if(subSpread.getActiveSheetIndex()==0&&sheetData!=null&&sheetData.length>0&&gljContextMenu.selectedRow<sheetData.length){
                            var recode = sheetData[gljContextMenu.selectedRow];
                            if(!(recode.isMixRatio!=true&&recode.isAdd==true)){
                                return true
                            }
                            return false;
                          //  disable= recode.isMixRatio!=true&&recode.isAdd==true?false:true
                        }
                        return true;
                    },
                    callback: function () {
                        var sheetData = gljOprObj.sheetData;
                        var recode = sheetData[gljContextMenu.selectedRow];
                        showGLJClassTree(recode);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='ration_glj';
                    }
                },
                "insert_detail": {
                    name: '插入行',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        if(subSpread.getActiveSheet().name()=='quantity_detail'){
                            var sheetData = gljOprObj.detailData;
                            if(gljOprObj.detailSheetReadonly()){
                                return true
                            }else {
                                return  gljContextMenu.selectedRow>sheetData.length;
                            }
                        }
                       return false
                    },
                    callback: function () {
                        projectObj.project.quantity_detail.insertQuantityDetail(gljContextMenu.selectedRow);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='quantity_detail';
                    }
                },
                "delete_detail": {
                    name: '删除行',
                    icon: 'fa-remove',
                    disabled: function () {
                        if(subSpread.getActiveSheet().name()=='quantity_detail'){
                            var sheetData = gljOprObj.detailData;
                            return gljContextMenu.selectedRow>sheetData.length-1;
                        }
                       return false
                    },
                    callback:function () {
                        projectObj.project.quantity_detail.deleteQuantityDetail(gljContextMenu.selectedRow);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='quantity_detail';
                    }
                },
                "move_up": {
                    name: '上移',
                    icon: 'fa-arrow-up',
                    disabled: function () {
                        if(subSpread.getActiveSheet().name()=='quantity_detail'){
                            var sheetData = gljOprObj.detailData;
                            return gljContextMenu.selectedRow==0||gljContextMenu.selectedRow>sheetData.length-1;
                        }
                       return false;
                    },
                    callback: function () {
                        projectObj.project.quantity_detail.moveUp(gljContextMenu.selectedRow);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='quantity_detail';
                    }
                },
                "move_down": {
                    name: '下移',
                    icon: 'fa-arrow-down',
                    disabled: function () {
                        if(subSpread.getActiveSheet().name()=='quantity_detail'){
                            var sheetData = gljOprObj.detailData;
                            return gljContextMenu.selectedRow>sheetData.length-2;
                        }
                      return false;
                    },
                    callback: function () {
                        projectObj.project.quantity_detail.moveDown(gljContextMenu.selectedRow);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='quantity_detail';
                    }
                },
                "copy": {
                    name: '复制',
                    icon: 'fa-files-o',
                    disabled: function () {
                        if(subSpread.getActiveSheet().name()=='quantity_detail'){
                            let sheet = subSpread.getActiveSheet();
                            let sheetData = gljOprObj.detailData;
                            let value = sheet.getCell(gljContextMenu.selectedRow,gljContextMenu.selectedCol).value();
                            if(gljContextMenu.selectedRow>sheetData.length-1||value==null){
                                return true;
                            }
                            if(gljOprObj.detailSetting.header[gljContextMenu.selectedCol].dataCode == 'isSummation'){//累加列恢显
                                return true;
                            }
                        }
                        return false;
                    },
                    callback: function () {
                        gljContextMenu.clipboard={
                            row:gljContextMenu.selectedRow,
                            col:gljContextMenu.selectedCol
                        };
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='quantity_detail';
                    }
                },
                "paste": {
                    name: '粘贴',
                    icon: 'fa-clipboard',
                    disabled: function () {
                        if(subSpread.getActiveSheet().name()=='quantity_detail'){
                            let sheetData = gljOprObj.detailData;
                            let dataCode = gljOprObj.detailSetting.header[gljContextMenu.selectedCol].dataCode;
                            if(gljContextMenu.selectedRow>sheetData.length||gljContextMenu.clipboard==null){
                                return true;
                            }
                            //结果列和累加列灰显
                            if(dataCode == 'result' || dataCode == 'isSummation'){
                                return true;
                            }
                        }
                        return false;
                    },
                    callback: function () {
                        var sheet = subSpread.getActiveSheet();
                        var c=gljContextMenu.clipboard;
                        console.log(sheet.getCell(c.row,c.col).value());
                        var args={
                            'row':gljContextMenu.selectedRow,
                            'col':gljContextMenu.selectedCol,
                            'editingText':sheet.getCell(c.row,c.col).value()
                        }
                        gljOprObj.onEditDetailSheet(args);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='quantity_detail';
                    }
                },
                "modify_rule": {
                    name: '修改规则',
                    icon: 'fa-sign-in',
                    disabled: function () {//当选中空行或者ruleID为空的情况下，灰显
                        if(subSpread.getActiveSheet().name()=='rationInstallSheet'){
                            let sheetData = installationFeeObj.rationInstallData;
                            if(gljContextMenu.selectedRow>sheetData.length-1){
                                return true
                            }
                            let ri = sheetData[gljContextMenu.selectedRow];
                            if(!ri.ruleId||ri.ruleId==''){
                                return true;
                            }
                        }
                        return false;
                    },
                    callback: function () {
                        $("#modify_feeRule").modal({show:true});
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='rationInstallSheet';
                    }
                },
                "apply_to_FX": {
                    name: '应用到当前分项',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        if(subSpread.getActiveSheet().name()=='rationInstallSheet'){
                            let sheetData = installationFeeObj.rationInstallData;
                            if(gljContextMenu.selectedRow>sheetData.length-1){
                                return true;
                            }
                            if(sheetData[gljContextMenu.selectedRow].unifiedSetting == 1){
                                return true;
                            }
                        }
                        return false;
                    },
                    callback: function () {
                        installationFeeObj.applyRuleTo('FX',gljContextMenu.selectedRow);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='rationInstallSheet';
                    }
                },
                "apply_to_FB": {
                    name: '应用到当前分部',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        if(subSpread.getActiveSheet().name()=='rationInstallSheet'){
                            let sheetData = installationFeeObj.rationInstallData;
                            if(gljContextMenu.selectedRow>sheetData.length-1){
                                return true;
                            }
                            if(sheetData[gljContextMenu.selectedRow].unifiedSetting == 1){
                                return true;
                            }
                        }
                        return false;
                    },
                    callback: function () {
                        installationFeeObj.applyRuleTo('FB',gljContextMenu.selectedRow);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='rationInstallSheet';
                    }
                },
                "apply_to_PRO": {
                    name: '应用到当前项目',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        if(subSpread.getActiveSheet().name()=='rationInstallSheet'){
                            let sheetData = installationFeeObj.rationInstallData;
                            if(gljContextMenu.selectedRow>sheetData.length-1){
                                return true;
                            }
                            if(sheetData[gljContextMenu.selectedRow].unifiedSetting == 1){
                                return true;
                            }
                        }
                        return false;
                    },
                    callback: function () {
                        installationFeeObj.applyRuleTo('PJ',gljContextMenu.selectedRow);
                    },
                    visible: function(key, opt){
                        return subSpread.getActiveSheet().name()=='rationInstallSheet';
                    }
                }
            }
        });
    },
    onbuild:function ($trigger, e) {
        var target = SheetDataHelper.safeRightClickSelection($trigger, e, subSpread);
        gljContextMenu.selectedRow = target.row;
        gljContextMenu.selectedCol = target.col;
        if(subSpread.getActiveSheet().name() == 'ration_glj'){
            gljOprObj.sheetInitSelection({row: target.row, col: target.col});
        }
        //controller.setTreeSelected(controller.tree.items[target.row]);
        return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
    },
    initGLJSelectView: function () {
        if (gljOprObj.gljLibSpresd == undefined) {
            gljOprObj.gljLibSpresd = sheetCommonObj.buildSheet($('#gljLibSheet')[0], gljOprObj.gljLibSheetSetting, gljOprObj.stdGLJ.length + gljOprObj.complementaryGLJs.length);
            sheetCommonObj.spreadDefaultStyle(gljOprObj.gljLibSpresd);
            gljOprObj.gljLibSpresd.bind(GC.Spread.Sheets.Events.ButtonClicked, gljOprObj.onButtonClick);
            gljOprObj.gljLibSheet = gljOprObj.gljLibSpresd.getSheet(0);
            gljOprObj.gljLibSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, gljOprObj.onSelectionChanged);
            gljOprObj.gljLibSheet.bind(GC.Spread.Sheets.Events.TopRowChanged, _.debounce(gljOprObj.onTopRowChanged, 100));
            gljOprObj.gljLibSheet.setColumnWidth(0, 20, GC.Spread.Sheets.SheetArea.rowHeader);
            gljOprObj.gljLibSheet.options.isProtected = true;
            gljOprObj.gljLibSheet.name('glj_lib');
            sheetCommonObj.setSheetBySetting(gljOprObj.gljLibSheet, gljOprObj.gljLibSheetSetting);
        }
        let gljClass = 0,
            selected,
            connect_key;
        const actionType = $('#actionType').val();
        const addActions = ['add', 'insert', 'addMix','unitPriceAddMix'];
        const replaceActions = ['m_replace', 'replace'];
        if (addActions.includes(actionType)) {//插入，添加，添加组成物（项目人材机页面）
            gljOprObj.GLJSelection = [];
        } else if(replaceActions.includes(actionType)){//替换、批量替换
            selected = gljOprObj.sheetData[gljContextMenu.selectedRow];
            connect_key = gljOprObj.getIndex(selected, gljKeyArray);
            gljOprObj.GLJSelection = [connect_key];
            // 找到定位的分类树
            const locatedItem = gljOprObj.AllRecode.find(item => gljOprObj.getIndex(item, gljLibKeyArray) === connect_key);
            if (locatedItem) {
                gljClass = locatedItem.gljClass;
                locatedItem.select = 1;
            }
        }
        //替换，焦点定位至当前选中人材机
        if (replaceActions.includes(actionType)) {
            gljOprObj.locateZTree(gljClass);
            sheetCommonObj.appendData(gljOprObj.gljLibSheet, 0, 0, gljOprObj.gljLibSheetSetting, gljOprObj.AllRecode);
            const index = gljOprObj.AllRecode.findIndex(item => gljOprObj.getIndex(item, gljLibKeyArray) === connect_key);
            gljOprObj.gljLibSheet.showRow(index, GC.Spread.Sheets.VerticalPosition.center);
            gljOprObj.gljLibSheet.setActiveCell(index, 0);
            gljOprObj.initSelection({row: index});
            gljOprObj.gljLibSpresd.focus(true);
        } else if (actionType === 'add' || actionType === 'insert' || actionType === 'addMix'|| actionType === 'unitPriceAddMix') {
            gljOprObj.locateZTree(null);
            sheetCommonObj.appendData(gljOprObj.gljLibSheet, 0, 0, gljOprObj.gljLibSheetSetting, gljOprObj.AllRecode);
            gljOprObj.gljLibSheet.showRow(0, GC.Spread.Sheets.VerticalPosition.top);
            gljOprObj.gljLibSheet.setActiveCell(0, 0);
            gljOprObj.initSelection({row: 0});
        } else {
            gljOprObj.showLibGLJSheetData();
        }
    }
}

function getGLJData(actionType,getLibFunc, initLibs, gljLibID) {
    if (actionType === 'change') {
        actionType = $('#actionType').val();
    }
    $('#actionType').val(actionType);
    // 清除选中人材机缓存数据
    gljOprObj.GLJSelection = [];
    $.bootstrapLoading.start();
    let location = false;
    // 需要定位
    const locateActions = ['replace', 'm_replace'];
    if (locateActions.includes(actionType)) {
        location = true;
    }
    const init = true;
    const reset = true;
    const condition = gljOprObj.getPagingCondition(init, reset, location, 0, initLibs, gljLibID);
    if(!getLibFunc)getLibFunc = projectObj.project.ration_glj.getGLJDataPaging;
    getLibFunc(condition, function (gljData, result) {
        if (gljOprObj.treeData.std.length) {
            gljOprObj.initClassTree(gljOprObj.treeData.std);
        } else if (gljOprObj.treeData.comple.length) {
            gljOprObj.initClassTree(gljOprObj.treeData.comple);
        }
        if (initLibs) {
            initLibOptions(result.libData);
            $('#modalCon').width($(window).width()*0.5);
            if(actionType == "m_replace"){
                $('#glj_selected_conf').hide();
                $('#replace_next_btn').show();
            } else {
                $('#glj_selected_conf').show();
                $('#replace_next_btn').hide();
            }
            $("#glj_tree_div").modal({show:true});
            setTimeout(function(){
                gljOprObj.gljLibSpresd ? gljOprObj.gljLibSpresd.refresh() : '';
            }, 200);
        } else {
            gljContextMenu.initGLJSelectView();
        }
        $.bootstrapLoading.end();
    });
}

function initLibOptions(libData) {
    const html = libData.reduce((acc, lib) => acc += `<option ${lib.isDefault ? 'selected="selected"' : ''} value="${lib.gljLibId}">${lib.name}</option>`, '');
    $('#glj-lib-select').html(html);
}

function showGLJClassTree(record) {
    let engineerID = projectObj.project.projectInfo.property.engineering_id;
    CommonAjax.post('/rationGlj/getGLJClass/'+engineerID,record, function (data) {
        if(data.exist==true){
            alert("当前人材机已存在。");
        }else {
            gljOprObj.selectedGLJClass = record;
            $("#glj_class_div").modal({show:true});
            zTreeHelper.createTree(data.items, gljOprObj.gljTreeSetting, "classTree", gljOprObj);
        }
    })
}