/**
 * Created by zhang on 2018/7/20.
 */
let quantityEditObj = {
    spread:null,
    datas:[],
    setting:{
        header:[
            {headerName: "基数名称", headerWidth: 250, dataCode: "name", dataType: "String"},
            {headerName: "代码", headerWidth: 150, dataCode: "code", dataType: "String"},
        ],
        view: {
            lockColumns: [0,1]
        }
    },
    initSpread:function () {
        if(!this.spread){
            this.spread = SheetDataHelper.createNewSpread($("#quantityEditSpread")[0]);
            this.initSheet();
        }else {
            this.spread.refresh();
        }
        this.showData();
    },
    initSheet:function () {
        this.sheet = this.spread .getSheet(0);
        sheetCommonObj.initSheet( this.sheet, this.setting, 30);
        this.sheet.bind(GC.Spread.Sheets.Events.CellDoubleClick,this.onCellDoubleClick);
        this.sheet.name('quantityEdit');
        // console.log(cell.value());
    },
    showData:function () {
        this.datas = [];//{name:'工程量明细合计',code:'GCLMXHJ'}这里暂时只有清单量一个选项
        let selected = projectObj.project.mainTree.selected;
        if(selected.sourceType == ModuleNames.ration){
            this.datas.push({name:'清单量',code:'QDL'});
        }
        sheetCommonObj.showData(this.sheet, this.setting,this.datas);
        this.sheet.setRowCount(this.datas.length);

    },
    onCellDoubleClick:function (e,info) {
        if(quantityEditObj.datas[info.row]){
            $("#quantityEXPValue").focus();
            quantityEditObj.setToQuantityEXP(quantityEditObj.datas[info.row].code);
            quantityEditObj.spread.focus(false);
        }
    },
    setToQuantityEXP:function (value) {
        let oldVal = $("#quantityEXPValue").val();
        let startIndex = getCursor($("#quantityEXPValue")[0]);//取光标位置
        let strartString = oldVal.substring(0,startIndex);
        let endString = oldVal.substring(startIndex);
        $("#quantityEXPValue").val(strartString+value+endString);
        setCursor($("#quantityEXPValue")[0],startIndex+value.length);//设置回光标位置
    },
    getQuantityEditCellType:function () {//这个需配合整个表的selection change事件，当change的时候会repaint,按钮会显示
        var ns = GC.Spread.Sheets;
        function QuantityEditCellType() {
            var init=false;
            this.clickTime = 0; //点击事件时间戳
        }
        QuantityEditCellType.prototype = new ns.CellTypes.Text();
        QuantityEditCellType.prototype.paint = function (ctx, value, x, y, w, h, style, options) {
            if(!projectReadOnly){
                if(options.sheet.getActiveRowIndex()==options.row&&options.sheet.getActiveColumnIndex()==options.col){
                    var image = document.getElementById('f_btn'),imageMagin = 3;
                    var imageHeight = 15;
                    var imageWidth = 25;
                    var imageX = x + w - imageWidth- imageMagin, imageY = y + h / 2 - imageHeight / 2;
                    ctx.save();
                    ctx.fillStyle = style.backColor;
                    ctx.fillRect(x,y,w,h);
                    ctx.drawImage(image, imageX, imageY,imageWidth,imageHeight);
                    ctx.beginPath();
                    ctx.arc(imageX+imageWidth/2,imageY+imageHeight/2,1,0,360,false);
                    ctx.arc(imageX+imageWidth/2-4,imageY+imageHeight/2,1,0,360,false);
                    ctx.arc(imageX+imageWidth/2+4,imageY+imageHeight/2,1,0,360,false);
                    ctx.fillStyle="black";//填充颜色,默认是黑色
                    ctx.fill();//画实心圆
                    ctx.closePath();
                    ctx.restore();
                    w = w - imageWidth - imageMagin;
                }
            }
            GC.Spread.Sheets.CellTypes.Text.prototype.paint.apply(this, arguments);
        };
        QuantityEditCellType.prototype.getHitInfo = function (x, y, cellStyle, cellRect, context) {
            return {
                x: x,
                y: y,
                row: context.row,
                col: context.col,
                cellStyle: cellStyle,
                cellRect: cellRect,
                sheetArea: context.sheetArea
            };
        };

        //2018 -09 -26  修改工程量这个输入控件，删除悬浮提示注释，还原时通过git 历史
        QuantityEditCellType.prototype.processMouseDown = function (hitinfo) {
            let me=quantityEditObj;
            if(hitinfo.sheet.getActiveRowIndex()==hitinfo.row&&hitinfo.sheet.getActiveColumnIndex()==hitinfo.col){
                var offset=hitinfo.cellRect.x+hitinfo.cellRect.width-6;
                var imageWidth = 25;
                if(hitinfo.x<offset&&hitinfo.x>offset-imageWidth){
                    if(!projectReadOnly){
                        me.showSelectModal(hitinfo);
                    }
                }
            }
        };
        return new QuantityEditCellType();
    },
    showSelectModal:function (hitinfo) {
        //锁定的清单不显示
        let project = projectObj.project;
        if(project.mainTree.selected.sourceType == ModuleNames.bills && project.isBillsLocked() && project.withinBillsLocked(project.mainTree.selected)){
            return;
        }
        this.initModalContent(hitinfo);
        $("#quantityEXPEdit").modal({show:true});
    },
    initModalContent:function (hitinfo) {
        //现在改成有可能点击时，还没选中节点，所以要靠row来判断
        let selected = projectObj.project.mainTree.items[hitinfo.row];
        if(selected.sourceType == ModuleNames.ration){//暂时只有定额才有基数选择,所以其它的先隐藏表格
            $("#quantityEditSpread").show();//quantityEditSpread
        }else {
            $("#quantityEditSpread").hide();
        }
        $("#quantityEXPValue").val(selected.data.quantityEXP);
        selected.data.quantityEXP == "GCLMXHJ" || selected.data.quantityEXP =="MBGCL"?$("#quantityEXPValue").attr("disabled","disabled"):$("#quantityEXPValue").removeAttr("disabled");


    },
    checkingAndUpdate(quantityEXP,node){
        let me = this;
       /* if(quantityEXP === node.data.quantityEXP){ //没有变化，不做任何操作
            projectObj.mainController.refreshTreeNode([node]);
            return true;
        }*/
        quantityEXP = quantityEXP?quantityEXP.toUpperCase():'';//非空判断
        quantityEXP =replaceAll('（','(',quantityEXP);//转换中文左右符号
        quantityEXP =replaceAll('）',')',quantityEXP);
        quantityEXP = quantityEXP.replace(/[\s\r\n]/g, "")//去掉空格回车换行等字符
        let value = me.evalQuantityExp(quantityEXP,node);
        if(value!=='evalError'){
            if(node.data.hasOwnProperty('isFromDetail')&&node.data.isFromDetail==1){
                hintBox.infoBox('操作确认', '已有工程量明细，是否清空明细表？', 2, function () {
                    node.data.isFromDetail=0;
                    me.updateQuantityEXP(value,quantityEXP,node);
                }, function () {
                    projectObj.mainController.refreshTreeNode([node]);
                },['确定','取消'],false);
                return true;
            }
            me.updateQuantityEXP(value,quantityEXP,node);
            return true;
        }else {
            projectObj.mainController.refreshTreeNode([node]);
        }
        return false;
    },
    evalQuantityExp(quantityEXP,node){
        let evalString = quantityEXP;
        if( node.sourceType == ModuleNames.ration && quantityEXP.indexOf('QDL')!=-1){
            let billNode = node.parent;
            let bQuantity = 0;
            if(billNode.updateData.quantity){
                bQuantity = scMathUtil.roundForObj(billNode.updateData.quantity,getDecimal("quantity",billNode));
            }else {
                bQuantity = billNode.data.quantity?scMathUtil.roundForObj(billNode.data.quantity,getDecimal("quantity",billNode)):0;
            }
            evalString = replaceAll("QDL","("+bQuantity+")",evalString);
        }
        try {
            let value = undefined;
            if(evalString&&evalString!=""){
                let exp = new Expression('');
                exp.Expression(evalString);
                value = Number(exp.Evaluate());
            }
            return value;
        }catch (error){
            alert("输入的表达式有误，请重新输入！");
            return "evalError";
        }
    },
    updateQuantityEXP:function (value,quantityEXP,node) {
        let quantity_detail = projectObj.project.quantity_detail;
        if(node.data.hasOwnProperty('isFromDetail')&&node.data.isFromDetail==1) quantity_detail.cleanQuantityDetail(node,true);
        if(node.sourceType === ModuleNames.bills){
            if(quantityEXP!=""&& node.data.unit == "公路公里" && quantityEditObj.infoShowing!==true){
              quantityEditObj.infoShowing = true
                hintBox.infoBox('操作确认', '是否将所有单位等于"公路公里"的项目的工程量都设为该值？', 2, function () {
                    quantity_detail.updateBillQuantity(value,node,quantityEXP,quantityEXP,true);
                    quantityEditObj.infoShowing = false
                }, function () {
                    quantity_detail.updateBillQuantity(value,node,quantityEXP,quantityEXP);
                    quantityEditObj.infoShowing = false
                },['是','否']);
                return;
            }
            quantity_detail.updateBillQuantity(value,node,quantityEXP,quantityEXP);
        }else {
            quantity_detail.updateRationQuantity(value,node,quantityEXP,quantityEXP);
        }
    }

};
$(function(){
    $('#quantityEXPEdit').on('shown.bs.modal', function (e) {
        projectObj.mainSpread.focus(false);
        quantityEditObj.initSpread();
        $("#quantityEXPValue").focus();
    });

    $('#operation_p').children("button").bind('click',function (){
        quantityEditObj.setToQuantityEXP($(this).text());
        $("#quantityEXPValue").focus();
    });

    $("#quantityEditConf").bind('click',function () {
        let selected = projectObj.project.mainTree.selected;
        let result = quantityEditObj.checkingAndUpdate($("#quantityEXPValue").val(),selected);
        if(result == true){
            $("#quantityEXPEdit").modal('hide');
        }
    })
    $('#quantityEXPEdit').bind('keypress', function (event) {
        if(event.keyCode === 13){
            $("#quantityEditConf").click();
            event.preventDefault();
        }

    });

});

function getCursor(elem) {
    //IE 9 ，10，其他浏览器
    if (elem.selectionStart !== undefined) {
        return elem.selectionStart;
    } else { //IE 6,7,8
        var range = document.selection.createRange();
        range.moveStart("character", -elem.value.length);
        var len = range.text.length;
        return len;
    }
}

function setCursor(elem, index) {
    //IE 9 ，10，其他浏览器
    if (elem.selectionStart !== undefined) {
        elem.selectionStart = index;
        elem.selectionEnd = index;
    } else { //IE 6,7,8
        var range = elem.createTextRange();
        range.moveStart("character", -elem.value.length); //左边界移动到起点
        range.move("character", index); //光标放到index位置
        range.select();
    }
}


function setSelection(elem, leftIndex, rightIndex) {
    if (elem.selectionStart !== undefined) { //IE 9 ，10，其他浏览器
        elem.selectionStart = leftIndex;
        elem.selectionEnd = rightIndex;
    } else { //IE 6,7,8
        var range = elem.createTextRange();
        range.move("character", -elem.value.length); //光标移到0位置。
        //这里一定是先moveEnd再moveStart
        //因为如果设置了左边界大于了右边界，那么浏览器会自动让右边界等于左边界。
        range.moveEnd("character", rightIndex);
        range.moveStart("character", leftIndex);
        range.select();
    }
}