/**
 * Created by Zhong on 2017/8/25.
 */

let gljSelOprObj = {
    distTypeTree: null,
    parentNodeIds: {},
    treeObj:null,
    rootNode: null,//分类树根节点
    workBook: null,
    selectedList: [],//选中的工料机
    setting: {
        header: [
            {headerName:"选择", headerWidth: 40, dataCode: "select", hAlign: "center", vAlign: "center"},
            {headerName:"编码",headerWidth:80,dataCode:"code", dataType: "String", formatter: "@", hAlign: "left", vAlign: "center"},
            {headerName:"名称",headerWidth:120,dataCode:"name", dataType: "String", hAlign: "left", vAlign: "center"},
            {headerName:"规格型号",headerWidth:80,dataCode:"specs", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"单位",headerWidth:80,dataCode:"unit", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"单价",headerWidth:80,dataCode:"basePrice", dataType: "Number", formatter: "0.00", hAlign: "right", vAlign: "center"},
            {headerName:"类型",headerWidth:80,dataCode:"gljType", dataType: "String",  hAlign: "center", vAlign: "center"}
        ]
    },
    setProp: function (prop, value, gljList) {
        for(let i = 0, len = gljList.length; i < len; i++){
            gljList[i][prop] = value;
        }
    },
    sortGlj: function(gljList) {
        gljList.sort(function(a, b){
            let rst = 0;
            if (a.code > b.code) rst = 1
            else if (a.code < b.code) rst = -1;
            return rst;
        });
    },
    switchToGljId: function (gljList) {
        for(let glj of gljList){
            glj.gljId = glj.ID;
            delete glj.ID;
        }
    },
    initClassTree: function (type, treeData) {
        let me = this;
        if (me.treeObj) {
            me.treeObj.destroy();
            me.parentNodeIds = {};
        }
        zTreeHelper.createTree(treeData, gljSelTreeOprObj.setting, "selGljTree", me);
        let rootNode = me.treeObj.getNodes()[0];
        if(rootNode && rootNode.isParent && rootNode.isFirstNode){
            me.rootNode = rootNode;
        }
        if(me.rootNode){
            me.treeObj.selectNode(me.rootNode);
            if ((me.stdGljList && me.stdGljList.length > 0) ||
                (me.complementaryGljList && me.complementaryGljList.length > 0)) {
                gljSelTreeOprObj.setting.callback.onClick(null, 'selGljTree', me.rootNode);
            }
        }
    },
    buildSheet: function (container) {
        let me = gljSelOprObj;
        me.workBook = sheetCommonObj.buildSheet(container, me.setting, 30);
        sheetCommonObj.spreadDefaultStyle(me.workBook);
        me.workBook.getSheet(0).setColumnWidth(0, 20, GC.Spread.Sheets.SheetArea.rowHeader);
        me.workBook.getSheet(0).setFormatter(-1, 1, "@", GC.Spread.Sheets.SheetArea.viewport);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.EditStarting, me.onCellEditStart);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
        me.workBook.bind(GC.Spread.Sheets.Events.ButtonClicked, me.onButtonClicked);//复选框点击事件
        me.bindBtnOpr($('#gljSelY'));
    },
    setGLJItems: function(stdGLJs, complementaryGLJs) {
        this.stdGljList = stdGLJs;
        //兼容多单价，计算补充定额价格时，套多单价人材机的时候，默认取第一个价格
        for(let sGlj of this.stdGljList){
            if(sGlj.priceProperty && typeof sGlj.priceProperty.price1 !== 'undefined'){
                sGlj.basePrice = sGlj.priceProperty.price1;
            }
        }
        this.complementaryGljList = complementaryGLJs;
        this.switchToGljId(this.stdGljList);
        this.switchToGljId(this.complementaryGljList);
        this.setProp('type', 'std', this.stdGljList);
        this.setProp('type', 'complementary', this.complementaryGljList);
        this.sortGlj(this.stdGljList);
        this.sortGlj(this.complementaryGljList);
    },
    initLibOptions: function (libData) {
        const html = libData.reduce((acc, lib) => acc += `<option ${lib.isDefault ? 'selected="selected"' : ''} value="${lib.gljLibId}">${lib.name}</option>`, '');
        $('#glj-lib-select').html(html);
    },
    // 初始化选择页面
    initView: async function (gljLibId, isInitial) {
        try {
            $.bootstrapLoading.start();
            const { libData, treeData, distTypeTree, stdGLJ, complementaryGLJs } = await this.getViewData(gljLibId);
            if (isInitial) {
                this.initLibOptions(libData);
                $('#gljSearchKeyword').val('');
                setTimeout(() => $('#selGlj').modal('show'), 200);
            }
            if (!this.workBook) {
                this.buildSheet($('#gljSelSheet')[0]);
            }
            this.distTypeTree = distTypeTree;
            this.setGLJItems(stdGLJ, complementaryGLJs);
            this.selectedList = [].concat(rationGLJOprObj.cache['_GLJ_' + rationGLJOprObj.currentRationItem.ID]);
            this.showGljList = [];
            this.setShowGljList(this.stdGljList, true);
            if (treeData.std.length) {
                this.initClassTree('std', treeData.std);
            } else if (treeData.comple.length) {
                this.initClassTree('comple', treeData.comple);
            } else {
                throw '没有有效的分类树。';
            }
            this.filterDatasAndShow();
        } catch (err) {
            console.log(err);
            alert(err);
        } finally {
            $.bootstrapLoading.end();
        }
    },
    getViewData: async function (gljLibId) {
        const url = `/rationGlj/getGLJData/${commonConstants.COMPILATION}/${gljLibId}/true`;
        const data = await ajaxGet(url);
        return data.datas;
    },
    onClipboardPasting: function (sender, args) {
        args.cancel = true;
    },
    onCellEditStart: function (sender, args) {
        args.cancel = true;
    },
    onButtonClicked: function (sender, args) {
        let me = gljSelOprObj;
        let val = args.sheet.getValue(args.row, args.col);
        let thisGlj = me.currentCache[args.row];
        thisGlj.isChecked = val;
        if(args.sheet.isEditing()){
            args.sheet.endEdit(true);
        }
        else{
            //设置选中
            if(val === true){
                let isExist = false;
                for(let i = 0, len = me.selectedList.length; i < len; i++){
                    if(me.selectedList[i].gljId === thisGlj.gljId){
                        isExist = true;
                        break;
                    }
                }
                if(!isExist){
                    thisGlj.consumeAmt = 0;
                    me.selectedList.push(_.cloneDeep(thisGlj));
                }
            }
            else if(val === false){
                for(let i = 0, len = me.selectedList.length; i < len; i++){
                    if(me.selectedList[i].gljId === thisGlj.gljId){
                        me.selectedList.splice(i, 1);
                        break;
                    }
                }
            }
        }
    },
    setShowGljList: function (gljList, clearChecked) {
        //初始为所有工料机
        let  me = this;
        let curRationGlj = rationGLJOprObj.cache['_GLJ_' + rationGLJOprObj.currentRationItem.ID];
        for(let i = 0; i < gljList.length; i++){
            //去除与已添加的组成物重复的条目
            let isExist = false;
            for(let j = 0; j < curRationGlj.length; j++){
                if(curRationGlj[j].gljId === gljList[i].gljId){
                    isExist = true;
                    break;
                }
            }
            if(!isExist){
                if(clearChecked){
                    gljList[i].isChecked = false;
                }
            }
            else {
                gljList[i].isChecked = true;
            }
            me.showGljList.push(gljList[i]);
        }
    },
    filterDatasAndShow: function () {
        const gljLib = $('#glj-lib-select').val();
        let me = gljSelOprObj;
        //选择改变，数据重新筛选显示
        me.showGljList = [];
        if (gljLib === commonConstants.COMPLEMENTARY_LIB) {
            me.setShowGljList(me.complementaryGljList);
        } else {
            me.setShowGljList(me.stdGljList);
        }
        //搜索匹配
        let searchStr = $('#gljSearchKeyword').val();
        if(searchStr && searchStr.trim() != ''){
            let reg = new RegExp(searchStr);
            me.showGljList = _.filter(me.showGljList, function (data) {
                return reg.test(data.code) || reg.test(data.name);
            });
        }
        //me.sortGlj(me.showGljList);
        //重新显示
        me.showGljItems(me.showGljList, me.gljCurTypeId);
        if (me.currentOprParent = 1) {
            if(me.parentNodeIds["_pNodeId_" + me.gljCurTypeId]){
                me.currentCache = me.getParentCache(me.parentNodeIds["_pNodeId_" + me.gljCurTypeId]);
            }
            else{
                me.currentCache = [];
            }
        } else {
            me.currentCache = me.getCache();
        }
    },
    getParentCache: function (nodes) {
        let me = gljSelOprObj, rst = [];
        for(let i = 0; i < me.showGljList.length; i++){
            if(nodes.indexOf(me.showGljList[i].gljClass) !== -1){
                rst.push(me.showGljList[i]);
            }
        }
        rst.sort(function (a, b) {
            let rst = 0;
            if(a.code > b.code) rst = 1;
            else if(a.code < b.code)rst = -1;
            return rst;
        });
        return rst;
    },
    getCache: function() {
        let me = gljSelOprObj, rst = [];
        for (let i = 0; i < me.showGljList.length; i++) {
            if (me.showGljList[i].gljClass == me.gljCurTypeId) {
                rst.push(me.showGljList[i]);
            }
        }
        return rst;
    },
    showGljItems: function(data, type) {
        let me = gljSelOprObj;
        if (me.workBook) {
            let cacheSection = [];
            let pArr = me.parentNodeIds["_pNodeId_" + type];
            for (let i = 0; i < data.length; i++) {
                if (pArr && pArr.indexOf(data[i].gljClass) >= 0) {
                    cacheSection.push(data[i]);
                } else if (type == data[i].gljClass) {
                    cacheSection.push(data[i]);
                }
            }
            //sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
            sheetsOprObj.showDataForGljSel(me.workBook.getSheet(0), me.setting, cacheSection, rationGLJOprObj.distTypeTree);
            me.workBook.getSheet(0).setRowCount(cacheSection.length);
            cacheSection = null;
        }
    },
    //组成物窗口按钮操作
    bindBtnOpr: function (conf) {//确定、取消、关闭按钮
        let me = gljSelOprObj, that = rationGLJOprObj;
        conf.click(function () {
            that.cache['_GLJ_' + that.currentRationItem.ID] = me.selectedList;
            that.updateRationItem(function () {
                that.sheet.getParent().focus();
                sheetCommonObj.cleanData(that.sheet, that.setting, -1);
                that.showGljItems(that.currentRationItem.ID);
                $('#selGlj').modal('hide');
            });
        });
    }
};

let gljSelTreeOprObj = {
     setting: {
        view: {
            expandSpeed: "",
            selectedMulti: false
        },
        edit: {
            enable: false,
            editNameSelectAll: true,
            showRemoveBtn: true,
            showRenameBtn: true,
            removeTitle: "删除节点",
            renameTitle: "更改名称"
        },
        data: {
            keep: {
                parent:true,
                leaf:true
            },
            key: {
                children: "items",
                name: "Name"
            },
            simpleData: {
                enable: false,
                idKey: "ID",
                pIdKey: "ParentID",
                rootPId: -1
            }
        },
        callback:{
            onClick: function(event,treeId,treeNode) {
                let me = gljSelOprObj, gljTypeId = treeNode.ID;
                if(me.gljCurTypeId !== treeNode.ID){
                    me.gljCurTypeId = treeNode.ID;
                    if (me.parentNodeIds["_pNodeId_" + treeNode.ID]) {
                        me.currentOprParent = 1;
                        me.currentCache = me.getParentCache(me.parentNodeIds["_pNodeId_" + treeNode.ID]);
                    } else {
                        me.currentCache = me.getCache();
                    }
                }
                me.showGljItems(me.showGljList, gljTypeId);
            }
        }
    }
};

$(document).ready(function () {
    $('#glj-lib-select').change(function () {
        const gljLibId = $(this).val();
        gljSelOprObj.initView(gljLibId, false);
    });
    /* $('#gljSearchKeyword').change(function () {
        gljSelOprObj.filterDatasAndShow();
    });
    $('#gljSearchKeyword').bind('keypress', function (e) {
        if(e.keyCode === 13){
            $(this).blur();
            return false;
        }
    }); */
    $('#gljSearchKeyword').on('keyup', _.debounce(function () {
        gljSelOprObj.filterDatasAndShow();  
    }, 300));
    $('#selGlj').on('shown.bs.modal', function () {
        if (gljSelOprObj.workBook) {
            gljSelOprObj.workBook.refresh();
        }
    });
});