/**
 * Created by zhang on 2018/11/16.
 */
let locateObject={
    bills_setting:{
        header:[
            {headerName: "编码", headerWidth: 120, dataCode: "code", dataType: "String"},
            {headerName: "项目名称", headerWidth: 100, dataCode: "name", dataType: "String"},
            {headerName: "单位", headerWidth: 50, dataCode: "unit", dataType: "String",hAlign: "center"},
            {headerName: "工程量", headerWidth: 65, dataCode: "quantity", dataType: "Number", hAlign: "right"},
            {headerName: "综合单价", headerWidth: 65, dataCode: "unitPrice", dataType: "Number", hAlign: "right"},
            {headerName: "综合合价", headerWidth: 65, dataCode: "totalPrice", dataType: "Number", hAlign: "right"}
        ],
        view: {
            lockColumns: [0,1,2,3,4,5],
            colHeaderHeight:30
        }
    },
    ration_setting:{
        header:[
            {headerName: "定额编码", headerWidth: 100, dataCode: "code", dataType: "String"},
            {headerName: "定额名称", headerWidth: 180, dataCode: "name", dataType: "String"},
            {headerName: "单位", headerWidth: 50, dataCode: "unit", dataType: "String",hAlign: "center"},
            {headerName: "工程量", headerWidth: 65, dataCode: "quantity", dataType: "Number", hAlign: "right",decimalField: "ration.quantity"}
        ],
        view: {
            lockColumns: [0,1,2,3],
            colHeaderHeight:30
        }
    },
    ration_glj_setting:{
        header:[
            {headerName: "编码", headerWidth: 120, dataCode: "code", dataType: "String"},
            {headerName: "名称", headerWidth: 80, dataCode: "name", dataType: "String"},
            {headerName: "规格型号", headerWidth: 80, dataCode: "specs", dataType: "String"},
            {headerName: "单位", headerWidth: 50, dataCode: "unit", dataType: "String",hAlign: "center"},
            {headerName: "市场价", headerWidth: 65, dataCode: "marketPrice", dataType: "Number", hAlign: "right"}
        ],
        view: {
            lockColumns: [0,1,2,3,4],
            colHeaderHeight:30
        }
    },
    datas:[],
    bookMarkSetting:{
        header:[
            {headerName: "编码", headerWidth: 120, dataCode: "code", dataType: "String"},
            {headerName: "书签名称", headerWidth: 200, dataCode: "name", dataType: "String"},
        ],
        view: {
            lockColumns: [0,1],
            colHeaderHeight:30
        }
    },
    bookmarkDatas:[],
    seletedNodeID:null,//右键设置书签时选中的节点ID临时存储
    //为了兼容旧项目，这里给个默认值
    bookmarkPropertySetting:{
        settingList :[
            {background:"E2F2C5",describe:""},
            {background:"F9E2CF",describe:""},
            {background:"F2EFD9",describe:""},
            {background:"F5D1DA",describe:""},
            {background:"E3E3E3",describe:""},
            {background:"B6F3F2",describe:""},
            {background:"ECE0F5",describe:""}
        ],
        selected:"E2F2C5"
    },
    getDescribeByColor: function (color) {
        const setting = projectObj.project.property.bookmarkSetting ? projectObj.project.property.bookmarkSetting : locateObject.bookmarkPropertySetting;
        const item = setting.settingList.find(item => item.background === color);
        return item && item.describe ? item.describe : '描述';
    },
    initMainSpread:function(){
        if(!this.mainSpread){
            this.mainSpread = SheetDataHelper.createNewSpread($("#locate_result")[0],3);
            sheetCommonObj.spreadDefaultStyle(this.mainSpread);
            this.initMainSheet();
        }else {
            this.mainSpread.refresh();
        }
    },
    initMainSheet:function () {
       //初始化清单表格
        sheetCommonObj.initSheet(this.mainSpread .getSheet(0),this.bills_setting);
        this.mainSpread .getSheet(0).setRowCount(0);
        //初始化定额表格
        sheetCommonObj.initSheet(this.mainSpread .getSheet(1),this.ration_setting);
        this.mainSpread .getSheet(1).setRowCount(0);
        //初始化人材机表格
        sheetCommonObj.initSheet(this.mainSpread.getSheet(2),this.ration_glj_setting);
        this.mainSpread .getSheet(2).setRowCount(0);
        this.mainSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick,this.onSheetDoubleClick);
        this.mainSpread .getSheet(2).bind(GC.Spread.Sheets.Events.SelectionChanged,this.gljSelectionChange);
    },
    initSubSpread:function () {
        if(!this.subSpread){
            this.subSpread = SheetDataHelper.createNewSpread($("#locate_sub")[0]);
            sheetCommonObj.spreadDefaultStyle(this.subSpread);
            this.initSubSheet();
            this.subSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick,this.onSheetDoubleClick);
        }else {
            this.subSpread.refresh();
        }
    },
    initBookmarkSpread:function(){
        if(!this.bookmarkSpread){
            this.bookmarkSpread = SheetDataHelper.createNewSpread($("#bookmarkSpread")[0]);
            sheetCommonObj.spreadDefaultStyle(this.bookmarkSpread);
            this.initBookmarkSheet();
            this.bookmarkSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick,this.onSheetDoubleClick);
            if(!projectReadOnly) this.initBookmarkRightClick();
        }else {
            this.bookmarkSpread.refresh();
        }
        this.showBookmarkDatas();
    },
    refreshWorkBook: function () {
        if (this.mainSpread) this.mainSpread.refresh();
        if (this.subSpread) this.subSpread.refresh();
        if (this.bookmarkSpread) this.bookmarkSpread.refresh();
    },
    initSubSheet:function () {
        this.subSheet = this.subSpread .getSheet(0);
        sheetCommonObj.initSheet( this.subSheet, this.ration_setting);
        this.subSheet.setRowCount(0);
        this.subSheet.name('locate_sub');
    },
    initBookmarkSheet:function () {
        this.bookmarkSheet = this.bookmarkSpread .getSheet(0);
        sheetCommonObj.initSheet( this.bookmarkSheet, this.bookMarkSetting);
        this.bookmarkSheet.setRowCount(0);
        this.bookmarkSheet.name('bookmark');
        this.bookmarkSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.bookmarkSelectionChange);
    },
    initOutstanding:function () {
        if(!projectObj.project.property.locateSetting) return;
        let outstd = projectObj.project.property.locateSetting;
        $("#outstanding").prop("checked",outstd.outstanding);
        $("#outInp").val(parseFloat(outstd.outInp));
    },
    initBookmarkSetting:function () {
        $("#bookmarkSettingList").empty();
        let setting = projectObj.project.property.bookmarkSetting?projectObj.project.property.bookmarkSetting:this.bookmarkPropertySetting;
        for(let s of setting.settingList){
            let b = `<div class="input-group input-group-sm mb-2" style="width:200px">
                          <div class="input-group-prepend">
                              <span class="input-group-text " style="background: #${s.background}">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                          </div>
                          <input type="text" class="form-control" id="${s.background}"  placeholder="描述" value="${s.describe}">
                     </div>`;
            $("#bookmarkSettingList").append(b);
            $("#"+s.background).bind('focus', bookmarkSelected);
        }
    },
    showMainData:function (datas,setting) {
        sheetCommonObj.showData(this.mainSpread.getActiveSheet(),setting,datas);
        this.mainSpread.getActiveSheet().setRowCount(datas.length);
    },
    showSubRateDatas:function () {
        this.subRationDatas = this.getSubRationDatas();
        sheetCommonObj.showData(this.subSheet,this.ration_setting,this.subRationDatas);
        this.subSheet.setRowCount(this.subRationDatas.length);
    },
    showBookmarkDatas:function(refresh = false){
        let sheet = this.bookmarkSheet;
        let sel = sheet.getSelections()[0];
        let oldData = sel.row<this.bookmarkDatas.length?this.bookmarkDatas[sel.row]:null;
        this.bookmarkDatas = this.getBookmarkDatas();
        sheetCommonObj.showData(sheet, this.bookMarkSetting,this.bookmarkDatas);
        let selectedID = null;
        let focus = false;
        if(oldData) selectedID = oldData.ID;
        if(this.seletedNodeID && refresh == false){
            selectedID =  this.seletedNodeID;
            this.seletedNodeID = null;
            focus = true;
        }
        sel.row = selectedID?_.findIndex(this.bookmarkDatas,{'ID':selectedID}):0;
        const locatedRow = sel.row === -1 ? 0 : sel.row;
        sheet.setSelection(locatedRow,sel.col,sel.rowCount,sel.colCount);
        sheet.setRowCount(this.bookmarkDatas.length);
        sheet.showRow(locatedRow, GC.Spread.Sheets.VerticalPosition.bottom)
        this.showAnnotation(locatedRow,focus);
    },
    getBookmarkDatas:function(){
        let datas = [];
        let nodes = projectObj.project.mainTree.items;
        for(let n of nodes){
            if(!_.isEmpty(n.data.bookmarkBackground)){
                let tem = {
                    ID:n.data.ID,
                    code:n.data.code,
                    type:n.sourceType,
                    name:n.data.name,
                    bookmarkAnnotation:n.data.bookmarkAnnotation,
                    bgColour:"#"+n.data.bookmarkBackground
                };
                datas.push(tem);
            }
        }
        return datas;
    },
    getSubRationDatas:function () {
        let datas = [];
        let sheet = this.mainSpread.getActiveSheet();
        let oldSel = sheet.getSelections()[0];
        if(this.gljDatas && this.gljDatas.length > 0){
            let glj = this.gljDatas[oldSel.row];
            if(!glj) return datas;
            let  nodes = projectObj.project.projectGLJ.getImpactRationNodes([glj.reference]);
            for(let n of nodes){
                datas.push(this.getShowRationDatas(n.data));
            }
        }
        return datas;
    },

    refreshView: function (options, refreshWorkBook) {
        let me = this;
        let mainHeight = $(window).height()-$(".header").height()-$(".toolsbar").height()-$("#searchPanel").height();
        let subHeight = 0;
        if(options == "bookmark"){
            loadHeight(getBookmarkResize());
        }else {
            $('#locateTopDiv').height(mainHeight);
            $('#locate_result').height(mainHeight);
            $('#locateBottomDiv').height(subHeight);
            $('#locate_sub').height(subHeight - 7);
            if(options == "ration_glj"){
                loadHeight(getLocateLibResize());
            }
        }
        if (refreshWorkBook) {
            me.refreshWorkBook();
        }

        function loadHeight(libResize) {
            SlideResize.loadVerticalHeight(libResize.eleObj.module, libResize.eleObj, libResize.limit, function () {
                locateObject.refreshWorkBook();
            });
        }
    },
    init:function () {
        let me = this;
        let options = $("input[name='content_type']:checked").val();
        let callback = function () {
            me.refreshView(options, false);
            me.initMainSpread();
            me.initSubSpread();
            me.initBookmarkSpread();
        };
        if(options == 'bookmark'){
            $("#aboutLocateDiv").hide();
            $("#outstandingOptions").hide();
            me.initBookmarkSetting();
            $("#aboutBookmarkDiv").show(0,callback);
        }else {
            $("#aboutBookmarkDiv").hide();
            $("#aboutLocateDiv").show(0,function () {
                if(options == "bills") me.initOutstanding();
                options == "bills"?$("#outstandingOptions").show(0,callback):$("#outstandingOptions").hide(0,callback);
            });
        }

    },
    findRecodes:function () {
        let options = $("input[name='content_type']:checked").val();
        let keyword = $("#locateInput").val();
        switch (options){
            case "bills":
                this.billsDatas = this.findBills(keyword);
                this.showMainData(this.billsDatas,this.bills_setting);
                break;
            case "ration":
                this.rationDatas = this.findRations(keyword);
                this.showMainData(this.rationDatas,this.ration_setting);
                break;
            case "ration_glj":
                this.gljDatas = this.findGLJs(keyword);
                this.showMainData(this.gljDatas,this.ration_glj_setting);
                this.showSubRateDatas();
                break;
        }
    },
    onshow:function () {
        locateObject.init();
    },
    matchItem:function (keyword,i) {//true 匹配上，false匹配失败
        let match = false;
        if(keyword && keyword !="") {//如果keyword为空，匹配所有
            if (i.code && i.code.indexOf(keyword) != -1) match = true;
            if (i.name && i.name.indexOf(keyword) != -1) match = true;
            if(match == false) return false
        }
        return true;
    },
    findGLJs:function(keyword){
        let datas = [];
        let gljList = projectObj.project.projectGLJ.datas.gljList;
        gljList =  sortProjectGLJ(gljList);
        for(let glj of gljList){
           // if(glj.quantity == 0 || glj.quantity == '0') continue;  2019-07-01 需求改成消耗量为0也显示
            let match = this.matchItem(keyword,glj);
            if(match == false) continue;
            let data = getGLJDatas(glj);
            gljOprObj.setGLJPrice(data,glj);
            datas.push(data);
        }
        return datas;
        function getGLJDatas(tem) {
            return{
                ID:tem.id,
                name:tem.name,
                code:tem.code,
                unit:tem.unit,
                specs:tem.specs,
                reference:tem
            }
        }

    },
    findRations:function (keyword) {
        let datas = [];
        let items = projectObj.project.mainTree.items;
        for(let  i of items){
            if(i.sourceType == ModuleNames.ration){
                let match = this.matchItem(keyword,i.data);
                if(match == false) continue;
                let bills = this.getShowRationDatas(i.data);
                datas.push(bills);
            }
        }
        return datas;
    },
    getShowRationDatas:function(data){
        return{
            ID:data.ID,
            name:data.name,
            code:data.code,
            unit:data.unit,
            quantity:data.quantity
        }
    },
    findBills:function(keyword){
        let datas = [],priceMap={};
        let items = projectObj.project.mainTree.items;
        for(let  i of items){
            if(i.sourceType == ModuleNames.bills){
                let match = this.matchItem(keyword,i.data);
                if(match == false) continue;
                let bills = getBillData(i.data);
                priceMap = setPriceMap(bills,priceMap);
                datas.push(bills);
            }
        }
        setBgColour(datas,priceMap);
        datas =  _.sortByAll(datas,['code']);
        return datas;


        function setBgColour(bills,map) {
            let outStd = $("#outstanding").prop("checked");
            let outInp = $("#outInp").val();
            if(outStd == true && outInp && outInp!=""){
                for(let b of bills){
                    if(b.code && b.code.length >= 9){
                        let key = b.code.substr(0,9);
                        if(map[key] && map[key].count > 1){
                            let avg = map[key].total/map[key].count;
                            let unitPrice = b.unitPrice?parseFloat(b.unitPrice):0;
                            if(unitPrice ==0 ) continue;
                            if(Math.abs(unitPrice - avg)/avg * 100  >= parseFloat(outInp)) b.bgColour = "#FFFACD"
                        }
                    }
                }
            }
        }
        function setPriceMap (bills,map) {
            if(bills.code && bills.code.length >= 9){
                let key = bills.code.substr(0,9);
                let unitPrice = bills.unitPrice?parseFloat(bills.unitPrice):0;
                if(map[key]){
                    map[key].total += unitPrice;
                    map[key].count ++;
                }else {
                    map[key] = {total:unitPrice,count:1}
                }

            }

            return map;
        }

        function getBillData(data) {
            return{
                ID:data.ID,
                name:data.name,
                code:data.code,
                unit:data.unit,
                quantity:data.quantity,
                unitPrice:data.feesIndex&&data.feesIndex.common?data.feesIndex.common.unitFee:"",
                totalPrice:data.feesIndex&&data.feesIndex.common?data.feesIndex.common.totalFee:"",
                bgColour:"white"
            }
        }
    },
    onSheetDoubleClick:function (e,args) {
        let me = locateObject;
        let options = $("input[name='content_type']:checked").val();
        let sheetName = args.sheet.name()
        if(options == "ration_glj"&&sheetName != "locate_sub" ) return;
        let datas = options == "bills"? me.billsDatas:me.rationDatas;
        if( args.sheet.name() == "locate_sub") datas = me.subRationDatas;
        if(args.sheet.name() == "bookmark") datas = me.bookmarkDatas;
        me.locateNode(datas[args.row].ID);
    },
    gljSelectionChange:function (e,args) {
        let me = locateObject;
        let newSel = args.newSelections[0];
        let oldSel = args.oldSelections?args.oldSelections[0]:{};
        if(newSel.row != oldSel.row){
            me.showSubRateDatas();
        }
    },
    bookmarkSelectionChange:function (e,args) {
        let me = locateObject;
        let newSel = args.newSelections[0];
        let oldSel = args.oldSelections?args.oldSelections[0]:{};
        if(newSel.row != oldSel.row){
            me.showAnnotation(newSel.row);
        }
    },
    showAnnotation:function (row,focus = false) {
        let me = locateObject;
        let recode =   me.bookmarkDatas[row];
        if(recode){
            $("#annotationTextarea").val(recode.bookmarkAnnotation);
            $("#bookmarkNodeID").val(recode.ID);
            $("#bookmarkNodeType").val(recode.type);
            if(focus) $("#annotationTextarea").focus();
        } else {
            $("#annotationTextarea").val('');
        }
    },
    locateNode:function (ID) {
        let node =  projectObj.project.mainTree.findNode(ID);
        if(node) projectObj.loadFocusLocation(node.serialNo(),1);
    },
    updateProjectProperty:function(fieldID,property){
        let updateData = {type:ModuleNames.project,data:{'ID' : projectObj.project.ID()}};//,'property.locateSetting':outstd
        updateData.data["property."+fieldID] = property;
        $.bootstrapLoading.start();
        projectObj.project.updateNodes([updateData],function () {
            $.bootstrapLoading.end();
            projectObj.project.property[fieldID] = property;
        });
    },
    updateOutStanding:function (outstanding,outInp) {
        let outstd = {outstanding:outstanding,outInp:outInp};
        this.updateProjectProperty('locateSetting',outstd);
    },
    updateBookmarkSetting:function () {
        let setting = projectObj.project.property.bookmarkSetting?projectObj.project.property.bookmarkSetting:locateObject.bookmarkPropertySetting;
        for(let s of setting.settingList){
            s.describe = $("#"+s.background).val();
        }
        setting.selected = $("#bookmarkSelected").val();
        this.updateProjectProperty("bookmarkSetting",setting);
    },
    // background为null则为取消书签批注
    setOrCancelBookmark:function(node, background){
        $("#bookmark").prop("checked", true);
        const updateData = {type: node.sourceType, data: {ID: node.data.ID, bookmarkBackground: background}};
        if(!background) {
            updateData.data.bookmarkAnnotation = null;
        }
        $.bootstrapLoading.start();
        projectObj.project.updateNodes([updateData],function () {
            $.bootstrapLoading.end();
            node.data.bookmarkBackground = background;
            projectObj.mainController.refreshTreeNode([node]);
            locateObject.seletedNodeID = node.data.ID;
            //如果没有打开，自动打开书签批注设置
            $('#locate').is(':visible')?locateObject.init():$("#locateTab").click();
        });
    },
    initBookmarkRightClick:function(){
        //如果当前行是无组成物的“普通材料”、“绿化苗木”、“外购砼构件”、“商品混凝土”、“商品砂浆”，则右键“添加计算材料”按钮有效。
        let me = this;
        $.contextMenu({
            selector: '#bookmarkSpread',
            build: function ($trigger, e) {
                me.rightClickTarget = SheetDataHelper.safeRightClickSelection($trigger, e, me.bookmarkSpread);
                return me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.viewport ||
                    me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                "deleteBookmark": {
                    name: "删除书签批注",
                    icon: 'fa-remove',
                    disabled: function () {
                        return  me.bookmarkDatas.length == 0;
                    },
                    callback: function (key, opt) {
                        me.deleteSelectedBookmark();
                    }
                },
                "deleteAllBookmarks": {
                    name: "删除所有书签批注",
                    icon: 'fa-remove',
                    disabled: function () {
                        return  me.bookmarkDatas.length == 0;
                    },
                    callback: function (key, opt) {
                        me.deleteBookmarkByDatas(me.bookmarkDatas);
                    }
                }
            }
        });
    },
    deleteSelectedBookmark:function () {
        let sel = this.bookmarkSheet.getSelections()[0];
        if(sel.row != -1 && this.bookmarkDatas.length>sel.row){
            let record = this.bookmarkDatas[sel.row];
            this.deleteBookmarkByDatas([record]);
        }
    },
    deleteBookmarkByDatas:function(datas){
        let postDatas = [];
        for(let d of datas){
            let tem = {
                type:d.type,
                data:{
                    'ID':d.ID,
                    'bookmarkAnnotation':null,
                    'bookmarkBackground':null
                }
            };
            postDatas.push(tem);
        }
        this.updateBookmarkNodes(postDatas);
    },
    updateBookmarkNodes:function (postDatas,refreshsNode = true) {
        $.bootstrapLoading.start();
        projectObj.project.updateNodes(postDatas,function () {
            $.bootstrapLoading.end();
            let nodes = [];
            for(let p of postDatas){
                let node =  projectObj.project.mainTree.findNode(p.data.ID);
                if(!node) continue;
                for(let key in p.data){
                    if(key == 'ID') continue;
                    node.data[key] = p.data[key];
                }
                nodes.push(node);
            }
            locateObject.showBookmarkDatas();
            if(refreshsNode) projectObj.mainController.refreshTreeNode(nodes);
        });
    }
};


$("#locate_btn").click(function () {
    locateObject.findRecodes();
});

//回车键搜索
$('#locateInput').bind('keypress', function (event) {
    if(event.keyCode === 13){
        $(this).blur();
        locateObject.findRecodes();
    }
});

$("input[name='content_type']").each(function(){
    $(this).click(function(){
        let options = $(this).val();
        switch (options){
            case "bills":
                locateObject.mainSpread.setActiveSheetIndex(0);
                break;
            case "ration":
                locateObject.mainSpread.setActiveSheetIndex(1);
                break;
            case "ration_glj":
                locateObject.mainSpread.setActiveSheetIndex(2);
                break;
        }
        locateObject.init();
    });
});


$('#outInp').change(function(){
    let me = locateObject;
    let process = getDecimal('process');
    var newVal = $(this).val();
    let outInp = scMathUtil.roundForObj(newVal,process);
    let outStd = $("#outstanding").prop("checked");
    me.updateOutStanding(outStd,outInp);
});
$('#outstanding').change(function(){
    let me = locateObject;
    let outInp = $("#outInp").val();
    let outStd = $("#outstanding").prop("checked");
    me.updateOutStanding(outStd,scMathUtil.roundForObj(outInp,getDecimal('process')));
});

$("#annotationTextarea").change(function(){
    let updateData = {type:$("#bookmarkNodeType").val(),data:{'ID' :$("#bookmarkNodeID").val(),'bookmarkAnnotation':$(this).val()}};
    let node =  projectObj.project.mainTree.findNode($("#bookmarkNodeID").val());
    if(!node) return;
    locateObject.updateBookmarkNodes([updateData],false);
});

$('#bookmarkSettingDropdown').on('shown.bs.dropdown', function showDropdown() {
    locateObject.initBookmarkSetting();
    let setting = projectObj.project.property.bookmarkSetting?projectObj.project.property.bookmarkSetting:locateObject.bookmarkPropertySetting;
    $("#"+setting.selected).focus();
});

$("#bookmarkSettingConfirm").click(function () {
    locateObject.updateBookmarkSetting();
    $("#bookmarkSettingDropdown").click();
});


function bookmarkSelected() {
    $("#bookmarkSelected").val($(this)[0].id);
}