/**
 * Created by zhang on 2018/9/12.
 */
let MaterialController = {
    moduleName: 'subRcj', //模块名
    subSpreadDivWidth:"",
    showItemText:false,
    //规则相关映射
    rule1: function (node) {
        let itemText = node.data.itemCharacterText;
        let name = this.getKeyString(itemText,"材质及规格:");
        if(name){
            return{name:name,specs:""}//规格型号变成空的
        }
        return null;
    },
    rule2:function (node) {
        let itemText = node.data.itemCharacterText;
        let name = this.getKeyString(itemText,"混凝土种类:");
        let specs = this.getKeyString(itemText,"混凝土强度等级:");
        if(name||specs){
            let doc ={};
            if(name) doc["name"] = name;
            if(specs) doc["specs"] = specs;
            return doc;
        }
        return null
    },
    replaceMaterial:function(nodes){
        let me = this;
        this.getMaterial(nodes,function (result) {
            if(!_.isEmpty(result)){
                me.startReplace(nodes,result);
            }
        });
    },
    startReplace:function (nodes,result) {//其实应该是批量修改工料机属性，与替换工料机不同
        let me = this,updateData = [];
        for(let n of nodes){
            let code = n.data.code;
            if(code.length >= 9){
                let r_list = this.eachNode(n,result[code.substr(0,9)]);
                if(r_list.length > 0) updateData.push(...r_list);
            }
        }
        me.postReplace(updateData);
    },
    postReplace:function (updateData) {
        let me = this;
        if(updateData.length == 0) return;
        $.bootstrapLoading.start();
        CommonAjax.post("/material/replace",updateData,function(result){
            $.bootstrapLoading.end();
            me.updateCacheAfterReplace(result)
        })
    },
    updateCacheAfterReplace:function (result){
        let nodes = [];
        for(let data of result){
            let node = projectObj.project.ration_glj.refreshRationNode(data.name,data.adjustState,data.rationID);//刷新定额名称和子目调整状态
            if(node) nodes.push(node);
            if(data.ration_gljs.length > 0) this.refreshRationGLJ(data.ration_gljs);
        }
        if(nodes.length >0){
            projectObj.project.projectGLJ.loadData(function () {
                projectObj.project.calcProgram.calcNodesAndSave(nodes,function(){
                    installationFeeObj.calcInstallationFee();
                });
                gljOprObj.refreshView();
            })
        }
    },
    refreshRationGLJ:function(ration_gljs){
        let ration_glj_model = projectObj.project.ration_glj;
        for(let rg of ration_gljs){
             let glj = ration_glj_model.refreshByID(rg.ID,rg.doc);
            ration_glj_model.refreshTreeNodeIfNeeded(glj);//刷新造价书上的树节点(如果需要)
        }
    },
    eachNode:function (node,item) {
        let replaceDatas =[];
        if(item && item.bills.rule){
             let replace_property = this["rule"+item.bills.rule](node);//按清单设置的规则获取要修改的属性
             if(replace_property){
                 replaceDatas = this.getReplaceData(node.data.ID,item.materialMap,replace_property);
             }
        }
        return replaceDatas;
    },
    getReplaceData:function (billsItemID,materialMap,replace_property) {
        let list = [];
        let replace_glj_list = this.findMatchRationGLJ(billsItemID,materialMap);//取出需要替换的工料机和对替换的材料内容
        for(let r of replace_glj_list){
            let doc = this.getDoc(r.glj,r.material,replace_property);//获取要修改的字段
            list.push({glj:gljOprObj.setGLJPrice(r.glj),doc:doc});
        }
        return list;
    },
    getDoc:function (glj,material,replace_property) {//取定额工料机中需要修改的内容
        let doc = {},keyList = ['name','specs','type','unit'];
        for(let key of keyList){
            if(glj[key] != material[key]) doc[key] = material[key];
        }
        for(let rkey in replace_property){
            doc[rkey] = replace_property[rkey]
        }
        return doc;

    },
    findMatchRationGLJ:function (billsItemID,materialMap) {//查找清单下匹配的需要替换的定额工料机
        let replaceList=[];
        for(let g of projectObj.project.ration_glj.datas){
            if(g.billsItemID == billsItemID && materialMap[g.original_code]) {
                replaceList.push({glj:g,material:materialMap[g.original_code]});
            }
        }
        return replaceList;
    },
    getMaterial:function (nodes,callback) {
        let data = [],materialMap= null;
        for(let n of nodes){
            let code = n.data.code;
            if(code.length >= 9 && n.data.billsLibId){
                let billCode = code.substr(0,9);
                data.push({code:billCode,billsLibId:n.data.billsLibId});
            }
        }
        if(data.length>0){
            //data 按编码去重
            let dataMap = _.indexBy(data,'code');
            CommonAjax.post("/material/getMaterial",dataMap,function (result) {
                callback(result);
            })
        }else {
            callback(null);
        }
    },
    getKeyString:function (itemText,matchStr) {//截取关键数据
        itemText = itemText.replace(/：/g, ":");//中文字符转换为英文字符
        itemText = itemText.replace(matchStr,"@$@");//用特殊符号取代关键字，方便截取
        let index = itemText.indexOf("@$@");
        if(index == -1) return null;
        let temString = itemText.substr(index+3);
        let strArray =  temString.split(/\n/);
        let keyString = this.trim(strArray[0]);
        return keyString===""?null:keyString;
    },
    trim:function (str) {
        return str.replace(/(^\s*)|(\s*$)/g, "");
    },
    //--------------2018-10-08新加替换表格-----------------
    setting:{
        header:[
            {headerName: "项目特征", headerWidth: 120, dataCode: "character", dataType: "String"},
            {headerName: "内容", headerWidth: 240, dataCode: "context", dataType: "String"},
            {headerName: "名称", headerWidth: 50, dataCode: "name", dataType: "String",hAlign: "center",cellType:"replaceButton"},
            {headerName: "规格", headerWidth: 50, dataCode: "specs", dataType: "String",hAlign: "center",cellType:"replaceButton"},
        ],
        view: {
            lockColumns: [0,1,2,3],
            rowHeaderWidth:25
        }
    },
    spread:null,
    sheet:null,
    datas:[],
    showReplaceDiv:function (node) {
        if(!($('#linkGLJ').hasClass('active'))){
            return;
        }
        $("#subSpread").addClass("ration_glj_spread");
        $('#itemTextDiv').show();
        $("#replaceM").show();
        $("#rgResize").show();// 拖动调整大小功能添加
        // 2018-11-07 需求变更，这个项目特征替换表格暂时隐藏不删除，以后可能还要用，先把项目初始化这句注释掉
       // if(node) this.showReplaceSpread(node);//如果不是只刷新页面
        this.showItemCharacterText(node);//只显示文本
        refreshSubSpread();
    },
    hideReplaceDiv:function(){
        $("#subSpread").removeClass("ration_glj_spread");
        $("#subSpread").css("width",""); //左右拖动调整表格大小的时候会设置css属性，所以隐藏这个div的时候也要把这个属性给去掉
        $("#replaceM").hide();
        //refreshSubSpread();   //提升焦点变换性能 2019年4月15日
    },
    showReplaceSpread:function(node){
        $("#replaceM").addClass("ovf-hidden");
        this.initSpread();
        this.showData(node);
    },
    initSpread:function () {
        if(!this.spread){
            this.spread = SheetDataHelper.createNewSpread($("#replaceM")[0]);
            sheetCommonObj.spreadDefaultStyle(this.spread);
            this.initSheet();
        }else {
            this.spread.refresh();
        }
    },
    initSheet:function(){
        this.sheet = this.spread .getSheet(0);
        sheetCommonObj.initSheet( this.sheet, this.setting);
        this.spread.bind(GC.Spread.Sheets.Events.ButtonClicked, this.onReplaceButtonClick);
        this.sheet.name('materialReplace');
    },
    showData:function(node){
        this.datas = [];
        let selected = node?node:projectObj.project.mainTree.selected;
        let parent = selected.parent;
        if(selected&&parent){
            this.getItems(parent.data.itemCharacterText);
        }
        sheetCommonObj.showData(this.sheet, this.setting,this.datas);
        this.sheet.setRowCount(this.datas.length);
    },
    showItemCharacterText:function (node) {
        let text="";
        let selected = node?node:projectObj.project.mainTree.selected;
        let parent = selected.parent;
        if(selected&&parent){
            text = parent.data.itemCharacterText?parent.data.itemCharacterText.replace(/\n/g,"<br>"):"";
        }
       /* if(text == "") {//为空的时候不显示
            $("#replaceM").hide();
            $("#subSpread").removeClass("ration_glj_spread");
            $('#subSpread').css('width','');
            return;
        }*/
        //$('#replaceM').css('margin-top',0);
        //this.toggleItemInit();
        $("#itemCharacterText").html(text);
    },
    //初始化人材机和项目特征文本两个区域的宽度,改变窗口大小时调用此方法，实时刷新
    initItemWidth: function () {
        //总宽度
        let totalWidth = $('#subItems').width();
        //人材机和项目特征文本比例
        const openWidth = 30;//打开项目特征工具条
        let textVisible = $('#replaceText').is(':visible'),
            //默认比例
            textPercent = '15%',
            rcjPercent = '85%';
        //文本没显示，则打开工具条固定30px转换百分比
        if (!textVisible) {
            textPercent = openWidth / totalWidth;
            rcjPercent = 1 - textPercent;
            textPercent = textPercent * 100 + '%';
            rcjPercent = rcjPercent * 100 + '%';
        }
        //设置特征及内容与排版规则的比例
        if ($('#replaceM').is(':visible')) {//显示工具条
            $('#subSpread').css('width', rcjPercent);
            $('#itemTextDiv').css('width', textPercent);
            //打开了项目特征，则继续加载人材机表和项目特征文本具体比例
            if (this.showItemText === true) {
                let rg_sideResizeEles = MaterialController.getSideResize();
                SlideResize.loadHorizonWidth(rg_sideResizeEles.eleObj.module,
                    [rg_sideResizeEles.eleObj.resize], [rg_sideResizeEles.eleObj.left, rg_sideResizeEles.eleObj.right]);
            }
        } else {//不显示工具条
            $('#subSpread').css('width', '100%');
        }

    },
    toggleItemInit:function () {
        if(this.showItemText == true){
            $("#replaceM").removeClass("ovf-hidden");
            $("#openItemText").hide();
            $("#replaceText").show();
            $("#closeItemText").show();
            $("#rgResize").show();
            this.initItemWidth();
        }else {
            $("#replaceM").addClass("ovf-hidden");
            $("#openItemText").show();
            $("#replaceText").hide();
            $("#closeItemText").hide();
            $("#rgResize").hide();
            this.initItemWidth();
        }
    },
    getItems:function(characterText){
        if(!characterText) return;
        let strArray =  characterText.split(/\n/);
        for(let tem of strArray){
            tem = tem.replace(/：/g, ":");//中文字符转换为英文字符
            if(tem.indexOf(":") != -1){//有：号才提取
                let proArr = tem.split(":");
                //如果内容为空的话也不提取
                let context = this.trim(proArr[1]);
                if(context!="") this.datas.push({character:proArr[0],context:context,name:"换",specs:"换"})
            }
        }
    },
    onReplaceButtonClick:function(e, args){
        //项目只读
        if(projectReadOnly) {
            return;
        }
        let me = MaterialController;
        let sheet = args.sheet, row = args.row, col = args.col;
        let dataCode = me.setting.header[col].dataCode, item = me.datas[row], doc = {};
        if(dataCode && item){
            doc[dataCode] = item.context;
            me.replaceByClick(doc);
        }
    },
    replaceByClick:function (tem) {
        let ration_glj = gljOprObj.getSelectedRationGlj();
        let doc = {};
        if(ration_glj && !ration_glj.isMixRatio){//有选中并且不是组成物
            if(gljOprObj.isExtraType(ration_glj.type)) return; //如果是“企业管理费”“利润”“一般风险费”类型，不能替换
            for(let key in tem){//检查属性是否做了改变，如果没有改变不用提交替换
                if(ration_glj[key] != tem[key]) doc[key] = tem[key]
            }
            if(!_.isEmpty(doc)) this.postReplace([{glj:ration_glj,doc:doc}]);
        }
    },
    getSideResize: function () {
        let rg_sideResizeEles = {};
        rg_sideResizeEles.eleObj = {
            module: this.moduleName,
            resize: $('#rgResize'),
            parent: $('#subItems'),
            left: $('#subSpread'),
            right: $('#itemTextDiv')
        };
        rg_sideResizeEles.limit = {
            min: 100,
            max: `$('#subItems').width()-100`
        };
        return rg_sideResizeEles;
    }
};

let rg_sideResizeEles = MaterialController.getSideResize();
SlideResize.horizontalSlide(rg_sideResizeEles.eleObj, rg_sideResizeEles.limit, function(){
    MaterialController.subSpreadDivWidth = $('#subSpread').css('width');
    refreshSubSpread();
});

$(function (){
    $("#openItemText").click(function () {
        MaterialController.showItemText = true;
        MaterialController.toggleItemInit();
        refreshSubSpread();
    });

    $("#closeItemText").click(function () {
        MaterialController.showItemText = false;
        MaterialController.toggleItemInit();
        refreshSubSpread();
    });

})