/**
 * Created by zhang on 2018/5/30.
 */

let zmhs_obj = {
    module: 'subZmhs',
    coeSpread:null,
    coeSheet:null,
    coeSheetData:[],
    coeSetting: {
        header: [
            {headerName: "调整", headerWidth: 35, dataCode: "isAdjust", dataType: "String", cellType: "checkBox"},
            {headerName: "条件", headerWidth: 140, dataCode: "name", dataType: "String", cellType: "button",getText:'forName'},
            {headerName: "内容", headerWidth: 110, dataCode: "content", dataType: "String", hAlign: "left",getText:'forContent',cellType:'tipsCell'}
        ],
        view: {
            lockColumns:[0,1,2],
            rowHeaderWidth:25
        },
        getText:{
            forContent:function (item) {//所选人材机，内容和条件互换位置
               if(gljUtil.isDef(item.option_codes)&&item.option_codes!=""){
                   return item.name;
               }else if(item.assistCode &&item.assistCode!="" ){//是辅助定额行，显示实际值
                    return item.actualValue;
               } else {
                   return item.content;
               }
            },
            forName:function (item) {
                if(gljUtil.isDef(item.select_code)&&item.select_code!=""){
                    let option = _.find(item.option_list,{"value":item.select_code})
                    return option?option.text:item.select_code;
                }else {
                    return item.name;
                }
            }
        },
        emptyRowHeader: true,
        autoFit:true,
        fitRow:['name']
    },
    cusSpread:null,
    cusSheet:null,
    cusSheetData:null,
    cusSetting:{
        header: [
            {headerName: "类型", headerWidth: 100, dataCode: "coeType", dataType: "String",hAlign: "left"},
            {headerName: "系数", headerWidth: 80, dataCode: "amount", dataType: "String", hAlign: "right",validator:"number"}
        ],
        view: {
            lockColumns:["coeType"],
            rowHeaderWidth:25
        },
        emptyRowHeader: true
    },
    assSpread:null,
    assSheet:null,
    assFirstIndex:0,
    assSheetData: [],
    assSetting: {
        header: [
            {headerName: "调整名称", headerWidth: 100, dataCode: "name", dataType: "String"},
            {headerName: "定额值", headerWidth: 80, dataCode: "stdValue", hAlign: "right", dataType: "String"},
            {headerName: "实际值", headerWidth: 80, dataCode: "actualValue", hAlign: "right", dataType: "String"}
        ],
        view: {
            lockColumns: [0, 1],
            rowHeaderWidth:25
        },
        emptyRowHeader: true
    },
    initSpread:function () {
        this.initCoeSpread();
        this.initAssSpread();
    },
    initCoeSpread:function () {
        if(zmhs_obj.coeSpread == null){
            this.coeSpread = SheetDataHelper.createNewSpread($("#coeSpread")[0]);
            sheetCommonObj.spreadDefaultStyle(this.coeSpread);
            this.coeSheet = this.coeSpread.getSheet(0);
            sheetCommonObj.initSheet(this.coeSheet, this.coeSetting, 30);
            this.coeSheet.name('ration_coe');
            //this.coeSheet.bind(GC.Spread.Sheets.Events.CellClick, this.onCoeCellClick);  配合自定义系数使用，现在自定义系数不在这显示了
            this.coeSpread.bind(GC.Spread.Sheets.Events.ButtonClicked, this.onButtonClick);
            this.coeSheet.bind(GC.Spread.Sheets.Events.ValueChanged,this.onCoeValueChange);
            this.coeSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, function (e,args) {
                args.sheet.repaint();
            });
            SheetDataHelper.protectdSheet(this.coeSheet);
        }
    },
    initCusSpread:function () {
        if(zmhs_obj.cusSpread == null){
            this.cusSpread = SheetDataHelper.createNewSpread($("#cusSpread")[0]);
            sheetCommonObj.spreadDefaultStyle(this.cusSpread);
            this.cusSheet = this.cusSpread.getSheet(0);
            sheetCommonObj.initSheet(this.cusSheet, this.cusSetting, 30);
            this.cusSheet.name('ration_cus');
            this.cusSheet.bind(GC.Spread.Sheets.Events.ValueChanged,this.onCusValueChange);
            this.cusSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onCusRangeChanged);
            SheetDataHelper.protectdSheet(this.cusSheet);
        }
    },
    initAssSpread:function () {
        if(zmhs_obj.assSheet == null){
            this.assSpread = SheetDataHelper.createNewSpread($("#assSpread")[0]);
            sheetCommonObj.spreadDefaultStyle(this.assSpread);
            this.assSheet = this.assSpread.getSheet(0);
            sheetCommonObj.initSheet(this.assSheet, this.assSetting, 30);
            this.assSheet.bind(GC.Spread.Sheets.Events.EditEnded, this.onAssEditEnded);
            this.assSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onAssRangeChanged);
            this.assSheet.name('ration_ass');
            SheetDataHelper.protectdSheet(this.assSheet);
        }
    },
    showCoeData:function (node) {
        let preSelections = this.coeSheet.getSelections();
        let selected = node?node:projectObj.project.mainTree.selected;
        let ration_coe = projectObj.project.ration_coe;
        let coeList = [];
        this.coeSheet.suspendPaint();
        this.coeSheet.suspendEvent();
        if(selected&&selected.sourceType == "ration"){
            let ration = selected.data;
            let assList = this.getAssList(node); //2019-01-23 新需求，将辅助定额合并到一个表显示  -- 20191206 辅助定额放前面
            // this.assFirstIndex = coeList.length;//没改前这里要记录辅助定额的起始下标，现在调整顺序后，默认就是0
            coeList = ration_coe.getCoeByRationID(ration.ID);
            _.remove(coeList,{"coeID":-1})//2018-12-24 新需求，把自定义乘系数分离出来，这里排除自定义乘系数行
            coeList = assList.concat(coeList)  //2019-01-23 新需求，将辅助定额合并到一个表显示
        }
        this.coeSheet.setRowCount(0);
        sheetCommonObj.showData(this.coeSheet, this.coeSetting,coeList);
        if (coeList.length > 0) {
            for(let i =0;i<coeList.length;i++ ){
                if(gljUtil.isDef(coeList[i].option_codes)&&coeList[i].option_codes!=""){
                    this.getComboBoxForCodes(coeList[i],i);//设置可选类型的下拉框
                    //  sheet.setValue(row, col, val, ch);
                } else if(coeList[i].assistCode && coeList[i].assistCode !=''){//是辅助定额列
                    this.coeSheet.getCell(i, 2, GC.Spread.Sheets.SheetArea.viewport).locked(false);
                } else if(coeList[i].coeID == -1){ //自定义系数列
                    this.coeSheet.getCell(i, 1, GC.Spread.Sheets.SheetArea.viewport).locked(false);
                    this.coeSheet.setCellType(i, 1, sheetCommonObj.getCustomerCoeCellType(this.generateHtmlString,this.bindCusEditorValue,this.updateCusCoeAfterEditor), GC.Spread.Sheets.SheetArea.viewport);
                }
            }
        }
        this.coeSheetData = coeList;
        if(projectReadOnly){
            sheetCommonObj.disableSpread(zmhs_obj.coeSpread);
        }
        if(preSelections){//定位光标到之前的位置
            this.coeSheet.setSelection(preSelections[0].row,preSelections[0].col,preSelections[0].rowCount,preSelections[0].colCount);
        }
        this.coeSheet.resumeEvent();
        this.coeSheet.resumePaint();
    },
    showCusData:function (node) {
        let selected = node?node:projectObj.project.mainTree.selected;
        let ration_coe = projectObj.project.ration_coe;
        let cusList = [];
        if(selected&&selected.sourceType == "ration"){
            let ration = selected.data;
            let coeList = ration_coe.getCoeByRationID(ration.ID);
            this.cusSheetData = _.find(coeList,{"coeID":-1});
            if(this.cusSheetData) cusList = this.cusSheetData.coes;
        }
        sheetCommonObj.showData(this.cusSheet, this.cusSetting,cusList);
        this.cusSheet.getRange(cusList.length,-1,this.cusSheet.getRowCount()-cusList.length, -1, GC.Spread.Sheets.SheetArea.viewport).locked(true);
        if(projectReadOnly){
            sheetCommonObj.disableSpread(zmhs_obj.cusSpread);
        }
    },

    getComboBoxForCodes:function (coe,i) {
        this.coeSheet.getCell(i, 1, GC.Spread.Sheets.SheetArea.viewport).locked(false);
        let options = coe.option_list; //coe.option_codes.split("|");
        let combo =  new GC.Spread.Sheets.CellTypes.ComboBox();//sheetCommonObj.getDynamicCombo(true);  2019-4-1 这里用普通的下拉框，一直显示
        let buttonRow =  this.coeSheet.getViewportBottomRow(1);
        combo.editorValueType(GC.Spread.Sheets.CellTypes.EditorValueType.value);
        combo.items(options).maxDropDownItems(buttonRow - i -1 < 3 ?3:buttonRow - i -1 );//itemHeight(options.length).
        this.coeSheet.setCellType(i, 1, combo, GC.Spread.Sheets.SheetArea.viewport);
        this.coeSheet.setValue(i, 1, coe.select_code);

    },
    showAssData:function (node) {
        this.assSheet.suspendPaint();
        this.assSheet.suspendEvent();
        let selected = node?node:projectObj.project.mainTree.selected;
        let assList = selected&&selected.data.rationAssList ? selected.data.rationAssList : [];
        this.assSheet.setRowCount(0);
        sheetCommonObj.showData(this.assSheet, this.assSetting, assList);
        this.assSheetData = assList;
        this.assSheet.getRange(assList.length,-1,this.assSheet.getRowCount()-assList.length, -1, GC.Spread.Sheets.SheetArea.viewport).locked(true);
        this.assSheet.resumePaint();
        this.assSheet.resumeEvent();
        if(projectReadOnly){
            sheetCommonObj.disableSpread(this.assSpread);
        }
    },
    getAssList:function (node) {
        let selected = node?node:projectObj.project.mainTree.selected;
        let assList = selected&&selected.data.rationAssList ? selected.data.rationAssList : [];
        this.assSheetData = assList;
        return assList;
    },
    refreshAfterUpdate:function(result,reload){
        let ration_glj = projectObj.project.ration_glj;
        let calcInstall = false;//是否记录安装增加费
        let nodes = projectObj.project.updateNodesCache([{type:ModuleNames.ration,data:result.ration}]);
        if(result.add && result.add.length > 0){//需添加定额工料机的情况
            ration_glj.datas = ration_glj.datas.concat(result.add);
            gljOprObj.sheetData = gljOprObj.sheetData.concat(result.add);
        }
        if(result.delete && result.delete.length > 0 && this.deleteGLJs(result.delete)) calcInstall = true; //这样保证delete返回值是true的时候才改变变量类型
        if(result.replace && result.replace.length > 0){ //替换工料机的情况
            for(let r of result.replace){//替换缓存内容
                ration_glj.datas.splice(_.findIndex(ration_glj.datas,{'ID': r.ID}),1,r);
                gljOprObj.sheetData.splice(_.findIndex(gljOprObj.sheetData,{'ID': r.ID}),1,r);
                let node = ration_glj.updateGLJNodeAfterReplace(r);
                if(node)  nodes.push(node);
            }
        }
        projectObj.mainController.refreshTreeNode(nodes, false);

        let rationID = result.ration.ID;
        ration_glj.updateCacheAfterAdjust(result.ration_glj);
        if(result.projectGLJList && result.projectGLJList.length > 0){//有添加、替换、工料机等需重新加载的情况
            projectObj.project.projectGLJ.loadNewProjectGLJToCaches(result.projectGLJList,true);
            if(result.add && result.add.length > 0) ration_glj.addToMainTree(result.add);//这个方法有再去项目工料机那里取价格，所以要在回调里调用，不像替换工料的情况
            ration_glj.reCalcWhenGLJChange({rationID:rationID});
            if(result.delete && result.delete.length > 0 && calcInstall) installationFeeObj.calcInstallationFee();//如果是删除节点的话，
        }else {
            ration_glj.reCalcWhenGLJChange({rationID:rationID});
        }
        gljOprObj.showRationGLJSheetData(true);
    },

    deleteGLJs:function (IDs) {
        let ration_glj = projectObj.project.ration_glj;
        let glj_list = ration_glj.datas;
        let calcInstall = false;
        let oldData = _.remove(glj_list, function (o) {
            return _.includes(IDs,o.ID);
        });
        _.remove(gljOprObj.sheetData, function (o) {
            return _.includes(IDs,o.ID);
        });
        for (let o of oldData) {
            if (ration_glj.needShowToTree(o)) {
                let node = ration_glj.findGLJNodeByID(o.ID);  //找到对应的树节点
                projectObj.mainController.deleteNode(node, null);
                calcInstall = true;
            }
        }
        return calcInstall;
    },


    refresh:function () {
        $('#coeSpread').is(':visible')&&this.coeSpread?this.coeSpread.refresh():'';
        $('#coeSpread').is(':visible')&&this.coeSpread?this.showDatas():'';//这里combobox下拉框要重新加载一下
        $('#cusSpread').is(':visible')&&this.cusSpread?this.cusSpread.refresh():'';
        $('#assSpread').is(':visible')&&this.assSpread?this.assSpread.refresh():'';
    },
    showDatas:function () {
        if($('#itemCharacterText').is(':visible'))MaterialController.showItemCharacterText();
        if($('#coeSpread').is(':visible')) this.showCoeData();
        if($('#cusSpread').is(':visible')) this.showCusData();
        if($('#assSpread').is(':visible')) this.showAssData();
    },
    showZMHSData:function (node) {
        if(this.coeSpread&& this.assSpread && $('#linkZMHS').hasClass('active')){
            this.showCoeData(node);
            this.showAssData(node);
        }
    },
    onCoeCellClick: function (sender, args) {
        let me = zmhs_obj;
        let sheet = args.sheet, row = args.row, col = args.col;
        if(sheet.getCell(row, col).locked() !=true){
            if(!sheet.isEditing()) sheet.startEdit();
        }
    },
    onButtonClick:function (sender, args) {
        let me = zmhs_obj;
        let sheet = args.sheet, row = args.row, col = args.col;
        let cellType = sheet.getCellType(row, col);
        if (args.sheetName == 'ration_coe' && cellType instanceof GC.Spread.Sheets.CellTypes.CheckBox) {
            me.onCoeCheckBoxClick(sender, args)
        }
    },
    bindCusEditorValue:function(context){
        let me = zmhs_obj;
        if(me.coeSheetData[context.row]){
            let data = me.coeSheetData[context.row];
            for(let c of data.coes){
                $("#"+ c.coeType).val(c.amount);
            }
            /*$('#coe_ration').val(data.coes[0].amount);
            $('#manual').val(data.coes[1].amount);
            $('#material').val(data.coes[2].amount);
            $('#manchine').val(data.coes[3].amount);
            $('#mainM').val(data.coes[4].amount);
            $('#equipment').val(data.coes[5].amount);*/
        }
    },
    updateCusCoeAfterEditor:function(){
        let me = zmhs_obj;
        let result = me.checkIfNeedUpdate();
        if (result.isNeed) {
            projectObj.project.ration_coe.updateCustomerCoe(result);
        }
    },
    onInputChange(id, name){
        var coe = _.find(zmhs_obj.coeSheetData, function (c) {
            return c.coeID == -1;
        });
        if(coe){
            let newValue = zmhs_obj.numberValueChecking($('#' + id).val());
            if (newValue) {
                newValue = _.round(newValue, 2);
                if (newValue == coe.coes[name].amount) return;
                if (id == '定额') {
                    for(let c of coe.coes){
                        $('#'+c.coeType).val(newValue)
                    }
                } else {
                    $('#' + id).val(newValue);
                }
            } else {
                $('#' + id).val(coe.coes[name].amount);
            }
        }
    },
    onInputClick(ele){//点中系数单元格，则默认选中系数值
        setSelection(ele,0,$(ele).val().length)
    },
    checkIfNeedUpdate(){
        let data = _.find(zmhs_obj.coeSheetData, function (c) {
            return c.coeID == -1;
        });
        let result = {isNeed: false};
        if(data){
            for(let c of data.coes){
                let amount = $("#"+c.coeType).val();
                if(amount!=c.amount){
                    result.isNeed = true;
                    c.amount = amount;
                }
            }
            if (result.isNeed) {
                result.doc = {
                    coes: data.coes
                };
                result.query = {
                    projectID: data.projectID,
                    ID: data.ID,
                    rationID: data.rationID
                };
            }
        }
        return result;

    },
    numberValueChecking: function (val) {
        var newval = Number(val);
        if (number_util.isNumber(newval)) {
            return newval;
        } else {
            if (val) {
                alert('您输入的数据类型不正确，请重新输入。');
            }
            newval = null;
        }
        return newval;
    },
    onCoeCheckBoxClick:function (sender, args) {
        let me = zmhs_obj;
        let checkboxValue = args.sheet.getCell(args.row, args.col).value();
        let newval = 0;
        if (checkboxValue) {
            newval = 0;
            args.sheet.getCell(args.row, args.col).value(newval);
        } else {
            newval = 1;
            args.sheet.getCell(args.row, args.col).value(newval);
        }
        let recode = me.coeSheetData[args.row];
        recode.assistCode && recode.assistCode != "" ? me.adjustAssClick(args,newval) : projectObj.project.ration_coe.adjustCoeClick(recode, newval);
    },
    generateHtmlString: function (context,cellRect,$editor) {//这里要改成动态的了，根据自定义系数内容生成对应的输入框
        let me = zmhs_obj;
        let height = cellRect.height;
        let offect = 0;
        let newString = "<form style='margin-top:1px' ><table  width='100%'  cellpadding='0'  border='1px' bordercolor='#CCCCCC' cellspacing='0px' style='border-collapse:collapse;'>";
        let cus_coe =  me.coeSheetData[context.row];
        if(cus_coe){
            for(let i =0;i< cus_coe.coes.length;i++){
                newString += me.getOneRow(cus_coe.coes[i].coeType, i, cus_coe.coes[i].coeType,height);
                offect += height +3
            }
        }
        newString += "</table></form><div style='height:"+ height+"px'><div onclick='zmhs_obj.coeSheet.endEdit()' style='margin:-1px 1px 0px'>自定义系数</div></div>";
        $editor.html(newString);
        $editor.css("margin-top",-(offect+2));
        return newString;
    },
    getOneRow: function (text, name, id,inputHeight) {
        var rowstr = "<tr ><td style='width: 50%'>" + text
            + "：</td><td style='width: 50%' align='right'><input class='text-right' type='text' value='1' name=" + name
            + " style='width:100%;border:0;height:"+ inputHeight+"px;' align='right' id=" + id + " onchange='zmhs_obj.onInputChange(this.id,this.name)' onclick='zmhs_obj.onInputClick(this)' autocomplete='off'></td></tr>";
        return rowstr;

    },
    coeStartEdit(){
        if(zmhs_obj.coeSheet.isEditing()){
            return;
        }else {
            zmhs_obj.coeSheet.startEdit();
        }
    },
    onCoeValueChange:function (e,args) {
        let fieldID =  zmhs_obj.coeSetting.header[args.col].dataCode;
        let recode = zmhs_obj.coeSheetData[args.row];
        if(gljUtil.isDef(recode.option_codes)&&recode.option_codes!=""&& fieldID == 'name'){//说明是选择了下拉框
            projectObj.project.ration_coe.adjustCoeClick(recode, 1,{'select_code':args.newValue});
        }else if(recode.assistCode &&recode.assistCode!=""){//编辑的是辅助定额
            zmhs_obj.updateRationAss({editingText:args.newValue,row:args.row - zmhs_obj.assFirstIndex})//转换一下
        }
    },
    onCusValueChange:function (e,args) {
      zmhs_obj.changeCusValue([{row:args.row,col:args.col,value:args.newValue}]);
    },
    changeCusValue:function (datas) {//[{row:,col,value}]
        if(this.cusSheetData){
            let tem_coes = _.cloneDeep(this.cusSheetData.coes);
            for(let d of datas){
                if(d.value&&!sheetCommonObj.checkData(d.col,this.cusSetting,d.value)){
                    this.showDatas();
                    alert('输入的数据类型不对，请重新输入!');
                    return;
                }
                if(gljUtil.isDef(d.value)&&d.value !=""){
                    if(tem_coes[d.row].coeType=="定额"){
                        for(let t of tem_coes){
                            t.amount = d.value;
                        }
                    }else {
                        tem_coes[d.row].amount = d.value;
                    }
                }
            }
            let doc = {'coes':tem_coes,'content':this.generationContent(tem_coes)};
            projectObj.project.ration_coe.adjustCoeClick(this.cusSheetData, 1,doc);
        }
    },
    generationContent:function (coes) {
        let rationAmount = coes[0].amount;
        let string ='';
        if(_.every(coes,'amount',rationAmount)){
            string = coes[0].coeType + 'x'+rationAmount;
        }else {
            let context_arr =[];
            for(let i =1;i<coes.length;i++){
                context_arr.push( coes[i].coeType + 'x'+coes[i].amount);
            }
            string = context_arr.join(',');

        }
        return string;
    },
    onAssEditEnded:function (e,args) {
        var me = zmhs_obj;
        if (args.row >= me.assSheetData.length) {
            me.assSheet.getCell(args.row, args.col).value(null);
            return;
        }
        if (me.assSetting.header[args.col].dataCode == 'actualValue') {//实际值
            me.updateRationAss(args);
        }
    },
    onCusRangeChanged:function (e,args) {
        let datas = [];
        for(let c of args.changedCells){
            let value=  args.sheet.getCell(c.row, c.col).text();
            datas.push({row:c.row,col:c.col,value:value})
        }
        zmhs_obj.changeCusValue(datas);
    },
    onAssRangeChanged:function (e,args) {
        let me = zmhs_obj;
        if (args.action == GC.Spread.Sheets.RangeChangedAction.clear) {
            args.editingText = null;
        }else if(args.action == GC.Spread.Sheets.RangeChangedAction.paste){
            args.editingText = args.sheet.getCell(args.row,args.col).value();
        }
        if (args.sheetName == 'ration_ass') {
            me.updateRationAss(args);
        }
    },
    adjustAssClick:function (args,newval) {
        let me = zmhs_obj, row = args.row - me.assFirstIndex;
        projectObj.project.ration_ass.updateActualValue(me.assSheetData, row,null,newval);
    },
    updateRationAss: function (args) {
        var me = zmhs_obj;
        var newval;
        newval = me.numberValueChecking(args.editingText);
        var recode = me.assSheetData[args.row];
        if (args.editingText === null) {
            newval = parseFloat(recode.stdValue);
        }
        var isValidate = false;
        if (newval) {
            isValidate = me.checkingActualValue(recode, newval)
        }
        if (isValidate) {
            newval = scMathUtil.roundTo(newval, -2);
            projectObj.project.ration_ass.updateActualValue(me.assSheetData, args.row, newval);
        } else {
           me.showDatas()
        }
    },
    checkingActualValue(record, newval){
        let minExist = record.minValue && record.minValue != '0' ? true : false;
        let maxExist = record.maxValue && record.maxValue != '0' ? true : false;
        let minValue = parseFloat(record.minValue);
        let maxValue = parseFloat(record.maxValue);

        if (!maxExist && minExist) {
            if (newval < minValue) {
                alert('实际值应≥' + minValue);
                return false;
            }
        }
        if (maxExist && !minExist) {
            if (newval > maxValue) {
                alert('实际值应≤' + maxValue);
                return false;
            }
        }
        if (maxExist && minExist) {
            if (newval < minValue || newval > maxValue) {
                alert('实际值应介于' + minValue + '~' + maxValue + '之间');
                return false;
            }
        }
        return true;
    },
    getSideResize: function () {
        let zmhs_sideResizeEles = {};
        zmhs_sideResizeEles.eleObj = {
            module: zmhs_obj.module,
            resize: $('#zmhsResize'),
            parent: $('#tabZMHS'),
            left: $('#coeSpread'),
            right: $('#assDiv')
        };
        zmhs_sideResizeEles.limit = {
            min: 100,
            max: `$('#tabZMHS').width()-100`
        };
        return zmhs_sideResizeEles;
    },
    loadSideResize: function () {
        let resizeObj = this.getSideResize();
        SlideResize.loadHorizonWidth(resizeObj.eleObj.module, [resizeObj.eleObj.resize], [resizeObj.eleObj.left, resizeObj.eleObj.right]);
    }
};

/*let zmhsResize = zmhs_obj.getSideResize();
SlideResize.horizontalSlide(zmhsResize.eleObj, zmhsResize.limit, function () {
    zmhs_obj.refresh();
});*/

