/**
 * Created by zhang on 2019/9/10.
 */
let configMaterialObj = {
    GLJIDMap:{},
    relateFilterAgain:false,
    configSpread:null,
    relatedSpread:null,
    evaluateMaterialDatas:[],
    bidMaterialDatas:[],
    evaluateMaterialSetting:{
        header: [
            {headerName: "关联", headerWidth: 80, dataCode: "is_related", dataType: "String",cellType:'checkBox'},
            {headerName: "序号", headerWidth: 80, dataCode: "seq", dataType: "String",formatter: "@"},
            {headerName: "材料号", headerWidth: 80, dataCode: "code", dataType: "String",formatter: "@"},
            {headerName: "材料名称", headerWidth: 160, dataCode: "name", dataType: "String",cellType:'tipsCell'},
            {headerName: "规格型号", headerWidth: 120, dataCode: "specs", hAlign: "left", dataType: "String",cellType:'tipsCell'},
            {headerName: "单位", headerWidth: 45, dataCode: "unit", hAlign: "center", dataType: "String"},
            {headerName: "数量", headerWidth: 90, dataCode: "quantity", hAlign: "right", dataType: "Number",validator:"number"},//decimalField:'glj.quantity'
            {headerName: "暂定价", headerWidth: 70, dataCode: "marketPrice", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "合价", headerWidth: 90, dataCode: "totalPrice", hAlign: "right", dataType: "Number",validator:"number",decimalField:'bills.totalPrice'},
            {headerName: "锁定", headerWidth: 80, dataCode: "locked", hAlign: "left", dataType: "String",cellType:'checkBox'},
            {headerName: "产地", headerWidth: 80, dataCode: "originPlace", hAlign: "left", dataType: "String",visible:false},
            {headerName: "厂家", headerWidth: 80, dataCode: "vender", hAlign: "left", dataType: "String",visible:false},
            {headerName: "备注", headerWidth: 100, dataCode: "remark", hAlign: "left", dataType: "String"}
        ],
        view:{ lockColumns: ["is_related","totalPrice","originPlace","vender","quantity"]}
    },
    bidMaterialSetting:{
        header: [
            {headerName: "关联", headerWidth: 80, dataCode: "is_related", dataType: "String",cellType:'checkBox'},
            {headerName: "序号", headerWidth: 80, dataCode: "seq", dataType: "String",formatter: "@"},
            {headerName: "材料号", headerWidth: 80, dataCode: "code", dataType: "String",formatter: "@"},
            {headerName: "材料名称", headerWidth: 160, dataCode: "name", dataType: "String",cellType:'tipsCell'},
            {headerName: "规格型号", headerWidth: 120, dataCode: "specs", hAlign: "left", dataType: "String",cellType:'tipsCell'},
            {headerName: "单位", headerWidth: 45, dataCode: "unit", hAlign: "center", dataType: "String"},
            {headerName: "数量", headerWidth: 90, dataCode: "quantity", hAlign: "right", dataType: "Number",validator:"number"},//decimalField:'glj.quantity'
            {headerName: "单价", headerWidth: 70, dataCode: "marketPrice", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "合价", headerWidth: 90, dataCode: "totalPrice", hAlign: "right", dataType: "Number",validator:"number",decimalField:'bills.totalPrice'},
            {headerName: "产地", headerWidth: 80, dataCode: "originPlace", hAlign: "left", dataType: "String",visible:false},
            {headerName: "厂家", headerWidth: 80, dataCode: "vender", hAlign: "left", dataType: "String",visible:false},
            {headerName: "备注", headerWidth: 100, dataCode: "remark", hAlign: "left", dataType: "String"}
        ],
        view:{ lockColumns: ["is_related","totalPrice","originPlace","vender","quantity"]}
    },

    evaluateRelateSetting:{
        header: [
            {headerName: "关联", headerWidth: 80, dataCode: "is_related", dataType: "String",cellType:'checkBox'},
            {headerName: "编码", headerWidth: 80, dataCode: "code", dataType: "String"},
            {headerName: "类别", headerWidth: 45, dataCode: "short_name" ,hAlign: "center",dataType: "String"},
            {headerName: "名称", headerWidth: 160, dataCode: "name", dataType: "String",cellType:'tipsCell'},
            {headerName: "规格型号", headerWidth: 120, dataCode: "specs", hAlign: "left", dataType: "String",cellType:'tipsCell'},
            {headerName: "单位", headerWidth: 45, dataCode: "unit", hAlign: "center", dataType: "String"},
            {headerName: "数量", headerWidth: 90, dataCode: "quantity", hAlign: "right", dataType: "Number",decimalField:'glj.quantity'},
            {headerName: "定额价", headerWidth: 70, dataCode: "basePrice", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "市场价", headerWidth: 70, dataCode: "marketPrice", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "合价", headerWidth: 90, dataCode: "totalPrice", hAlign: "right", dataType: "Number",validator:"number",decimalField:'bills.totalPrice'},
            {headerName: "供货方式", headerWidth: 70, dataCode: "supply", hAlign: "center", dataType: "String",cellType:'comboBox',editorValueType:true,options:supplyComboMap},
            {headerName: "产地", headerWidth: 80, dataCode: "originPlace", hAlign: "left", dataType: "String"},
            {headerName: "厂家", headerWidth: 80, dataCode: "vender", hAlign: "left", dataType: "String"},
            {headerName: "备注", headerWidth: 100, dataCode: "remark", hAlign: "left", dataType: "String"}
        ],
        view:{ lockColumns: ["code","type","name","specs","unit","quantity","marketPrice","basePrice","supply","originPlace","vender","remark"]}
    },
    initSpread:function(){
        if(!this.configSpread){
            this.configSpread = SheetDataHelper.createNewSpread($("#config_material_sheet")[0],4);
            sheetCommonObj.spreadDefaultStyle(this.configSpread);
            this.relatedSpread = SheetDataHelper.createNewSpread($("#related_sheet")[0],4);
            sheetCommonObj.spreadDefaultStyle(this.relatedSpread);
        }
        this.initEvaluateMaterialSheet();
        this.initbidMaterialSheet();
        this.initEvaluateRelateSheet();
        materialAdjustObj.initPriceInfoSheet();
        materialAdjustObj.initPriceCoeSheet();
        //打开别人分享的项目，只读
        if(projectReadOnly){
            sheetCommonObj.disableSpread(this.configSpread);
            sheetCommonObj.disableSpread(this.relatedSpread);
        }else {
            this.initRightClick();
        }
    },
    initEvaluateMaterialSheet:function(){
        this.evaluateMaterialSheet = this.configSpread.getSheet(0);
        sheetCommonObj.initSheet(this.evaluateMaterialSheet,this.evaluateMaterialSetting,30);
        this.evaluateMaterialSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onEvaluateMaterialValueChange);
        this.evaluateMaterialSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onEvaluateMaterialSelectionChange);
        this.evaluateMaterialSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onEvaluateMaterialEditStarting);
        this.evaluateMaterialSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onSheetRangeChange);
        this.evaluateMaterialSheet.name('evaluateMaterialSheet');
        this.evaluateMaterialSheet.setRowHeight(0, 36, 1);
    },
    initbidMaterialSheet:function(){
        this.bidMaterialSheet = this.configSpread.getSheet(1);
        sheetCommonObj.initSheet(this.bidMaterialSheet,this.bidMaterialSetting,30);
        this.bidMaterialSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onBidEvaluateMaterialValueChange);
        this.bidMaterialSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onEvaluateMaterialSelectionChange);
        this.bidMaterialSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onBitMaterialEditStarting);
        this.bidMaterialSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onSheetRangeChange);
        this.bidMaterialSheet.name('bidMaterialSheet');
        this.bidMaterialSheet.setRowHeight(0, 36, 1);
    },
    initEvaluateRelateSheet:function () {
        this.evaluateRelateSheet = this.relatedSpread.getSheet(0);
        sheetCommonObj.initSheet(this.evaluateRelateSheet,this.evaluateRelateSetting,30);
        this.evaluateRelateSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onEvaluateRelateValueChange);
        this.evaluateRelateSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onEvaluateRelateEditStarting);
        //this.evaluateRelateSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onSheetRangeChange);
        this.evaluateRelateSheet.name('evaluateRelateSheet');
        this.evaluateRelateSheet.setRowHeight(0, 36, 1);
    },

    showEvaluateMaterialDatas:function () {
        this.configSpread.setActiveSheetIndex(0);
        let sel = this.evaluateMaterialSheet.getSelections()[0];
        let oldData = sel.row<this.evaluateMaterialDatas.length?this.evaluateMaterialDatas[sel.row]:"";
        this.evaluateMaterialDatas = this.getEvaluateMaterialDatas();
        sheetCommonObj.showData(this.evaluateMaterialSheet, this.evaluateMaterialSetting,this.evaluateMaterialDatas);
        this.evaluateMaterialSheet.setRowCount(this.evaluateMaterialDatas.length);
        sel.row = oldData?_.findIndex(this.evaluateMaterialDatas,{'ID':oldData.ID}):'';
        this.evaluateMaterialSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
    },
    showBidMaterialDatas:function () {
        this.configSpread.setActiveSheetIndex(1);
        let sel = this.bidMaterialSheet.getSelections()[0];
        let oldData = sel.row<this.bidMaterialDatas.length?this.bidMaterialDatas[sel.row]:"";
        this.bidMaterialDatas = this.getBidMaterialDatas();
        sheetCommonObj.showData(this.bidMaterialSheet, this.bidMaterialSetting,this.bidMaterialDatas);
        this.bidMaterialSheet.setRowCount(this.bidMaterialDatas.length);
        sel.row = oldData?_.findIndex(this.bidMaterialDatas,{'ID':oldData.ID}):'';
        this.bidMaterialSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
    },
    showEvaluateRelateDatas:function () {
        this.relatedSpread.setActiveSheetIndex(0);
        this.evaluateRelateDatas = this.getEvaluateRelateDatas();
        sheetCommonObj.showData(this.evaluateRelateSheet, this.evaluateRelateSetting,this.evaluateRelateDatas);
        this.evaluateRelateSheet.setRowCount(this.evaluateRelateDatas.length);
    },

    refreshSheetDatas:function () {
        if(projectGljObject.displayType == filterType.ZGCL){
            this.showEvaluateMaterialDatas();
        }else if(projectGljObject.displayType == filterType.PBCL){
            this.showBidMaterialDatas();
        }
        this.showEvaluateRelateDatas();

    },
    setNavLinkText:function (type) {
        let text = "关联暂估材料";
        switch (type){
            case filterType.ZGCL:
                text = "关联暂估材料";
                break;
            case filterType.PBCL:
                text = "关联评标材料";
                break;
            case filterType.AMAE:
                text = "关联材料";
                break;
        }
        $("#related_link").text(text);
    },
    getEvaluateRelateDatas:function () {
        //$('filterGljName')
        let name = '',datas = [],sheet=null,field='',rdata=[];
        switch (projectGljObject.displayType){
            case filterType.ZGCL:
                sheet = this.evaluateMaterialSheet;
                datas = this.evaluateMaterialDatas;
                field = "is_evaluate";
                break;
            case filterType.PBCL:
                sheet = this.bidMaterialSheet;
                datas = this.bidMaterialDatas;
                field = "is_eval_material";
                break;
            case filterType.AMAE:
                sheet = materialAdjustObj.getSheet();
                datas = materialAdjustObj.getSheetDatas();
                field = "is_contractor_material";
        }

        let sel = sheet.getSelections()[0];
        let srow = sel.row == -1||sel.row == ""?0:sel.row;
        if(gljUtil.isDef(srow) && datas.length>srow){
             name = this.relateFilterAgain== true? $('#filterGljName').val(): datas[srow].name;
             rdata = this.filterEvaluateRelate(name,datas[srow].projectGLJID,field);
        }
        if(this.relateFilterAgain== false) $('#filterGljName').val(name);
        return rdata;
    },
    filterEvaluateRelate:function (name,projectGLJID,relateField) {
        let datas = [];
        let projectGLJ =  projectObj.project.projectGLJ;
        let materialIdList = projectGLJ.datas.constData.materialIdList;
        for(let d of projectGLJ.datas.gljList){
            if (parseFloat(d.quantity) > 0 ){//材料类型//materialIdList.indexOf(d.type) >= 0 &&
                if(projectGljObject.displayType != filterType.AMAE){
                    if(materialIdList.indexOf(d.type) ==-1) continue;
                }
                if(d[relateField] == 1 && d.id != projectGLJID) continue;//排除其它已被关联的工料机
                if(name != ''){//name为''时不做过滤
                    if(d.name.indexOf(name)==-1){
                        if(!(d[relateField] == 1 && d.id == projectGLJID)) continue;//虽然不匹配，但是是关联的暂估材料，这时应该显示
                    }
                }
                let t = {
                    id:d.id,
                    code : d.code,
                    type : d.type,
                    short_name :projectGLJ.getShortNameByID(d.type),
                    name : d.name,
                    specs : d.specs,
                    unit : d.unit,
                    quantity : d.quantity,
                    supply:d.supply,
                    originPlace:d.originPlace,
                    vender:d.vender,
                    remark:d.remark,
                    from:d
                };
                t.is_related = d[relateField]?1:0;
                gljOprObj.setGLJPrice(t,d);
                t.totalPrice = scMathUtil.roundForObj(t.quantity * t.marketPrice,getDecimal('bills.totalPrice'));
                datas.push(t);
            }
        }
        return _.sortByAll(datas,'code');
    },
    getEvaluateMaterialDatas:function (projectGLJList, evaluateList, decimalObj) {
        projectGLJList = projectGLJList ? projectGLJList : projectObj.project.projectGLJ.datas.gljList;
        evaluateList = evaluateList ? evaluateList : projectObj.project.evaluate_list.datas;
        const billsDecimal = decimalObj ? decimalObj.bills.totalPrice : getDecimal('bills.totalPrice');
        let datas = [];
        let gljMap = _.indexBy(projectGLJList,'id');
        for(let e of evaluateList){
            let t = {
                ID:e.ID,
                projectID: e.projectID,
                is_related:e.is_related,//关联，1关，0不关
                projectGLJID:e.projectGLJID,//关联工料机ID
                seq:e.seq,//序号
                code:e.code,
                name:e.name,
                specs:e.specs,
                unit:e.unit,
                type:e.type,
                marketPrice:e.market_price,
                quantity:e.quantity,
                locked:e.locked,//锁定，1锁，0不锁
                remark:e.remark,
                originPlace:e.originPlace,//产地
                vender:e.vender //厂家
            };
            let pglj = gljMap[e.projectGLJID];
            if(e.is_related && pglj){
                gljOprObj.setGLJPrice(t,pglj);
                t.originPlace = pglj.originPlace;
                t.vender = pglj.vender;
                t.brand = pglj.brand;
                t.qualityGrace = pglj.qualityGrace;
                t.remark = pglj.remark;
                t.quantity = pglj.quantity;
            }
            t.totalPrice = scMathUtil.roundForObj(parseFloat(t.quantity) * parseFloat(t.marketPrice) ,billsDecimal);
            datas.push(t);
        }
        return _.sortByAll(datas,'code');
    },

    getBidMaterialDatas:function (projectGLJList, bidEvaluationList, decimalObj) {
        projectGLJList = projectGLJList ? projectGLJList : projectObj.project.projectGLJ.datas.gljList;
        bidEvaluationList = bidEvaluationList ? bidEvaluationList : projectObj.project.bid_evaluation_list.datas;
        const billsDecimal = decimalObj ? decimalObj.bills.totalPrice : getDecimal('bills.totalPrice');
        let datas = [];
        let gljMap = _.indexBy(projectGLJList,'id');
        for(let e of bidEvaluationList){
            let t = {
                ID:e.ID,
                projectID: e.projectID,
                is_related:e.is_related,//关联，1关，0不关
                projectGLJID:e.projectGLJID,//关联工料机ID
                seq:e.seq,//序号
                code:e.code,
                name:e.name,
                specs:e.specs,
                unit:e.unit,
                type:e.type,
                marketPrice:e.market_price,
                quantity:e.quantity,
                remark:e.remark,
                originPlace:e.originPlace,//产地
                is_evaluate:0,
                vender:e.vender //厂家
            };
            let pglj = gljMap[e.projectGLJID];
            if(e.is_related && pglj){
                gljOprObj.setGLJPrice(t,pglj);
                t.originPlace = pglj.originPlace;
                t.vender = pglj.vender;
                t.brand = pglj.brand;
                t.qualityGrace = pglj.qualityGrace;
                t.quantity = pglj.quantity;
                t.is_evaluate = pglj.is_evaluate;
            }
            t.totalPrice = scMathUtil.roundForObj(parseFloat(t.quantity) * parseFloat(t.marketPrice) ,billsDecimal);
            datas.push(t);
        }
        return _.sortByAll(datas,'code');
    },

    updateConfigMaterial:function (dataCode,value,recode) {
        let task = [];
        for(let t of projectObj.project.projectGLJ.datas.gljList){
            this.GLJIDMap[t.id] = t;
        }
        let glj = this.GLJIDMap[recode.id];
        if(!glj) return;
        let pdata = {doc:{},action:'update'};
        pdata['type'] = 'glj_list';
        pdata.doc[dataCode] = value;
        pdata['id'] = glj.id;
        task.push(pdata);
        this.getEvaluateUpdateTasks(value,glj,dataCode,task);
        this.updateEvaluateMaterial(task,dataCode == "is_evaluate");
    },

    updateEvaluateMaterial :async function(data,refreshEvaluate=true){
        try {
            $.bootstrapLoading.start();
            let result =  await ajaxPost('/glj/updateEvaluateMaterial',{tasks:data});
            //先刷新缓存
            let [gljs,sendPriceChange] = this.refreshCache(data);
            if(refreshEvaluate == true){
                let [rationNodes,impactGLJs] =  projectObj.project.projectGLJ.batchChangeIsEvaluate(gljs);
                projectObj.project.calcProgram.calcNodesAndSave(rationNodes, function () {
                    projectObj.mainController.refreshTreeNode(projectObj.project.mainTree.roots);
                });
            }
            projectGljObject.refreshViewsData();
            gljOprObj.refreshView();
            if(sendPriceChange == true) projectGljObject.onUnitFileChange();


        }catch (e){
            console.log(e)
        }finally {
            $.bootstrapLoading.end();
        }
    },

    refreshCache:function (tasks) {
        let gljs = [];
        let sendPriceChange = false;
        for(let t of tasks){
            if(t.type == "evaluate_list"){
                refreshDatas(projectObj.project.evaluate_list.datas,t);
            }else if(t.type == "bid_evaluation_list"){
                refreshDatas(projectObj.project.bid_evaluation_list.datas,t);
            }else if(t.type == "contractor_list"){
                refreshDatas(projectObj.project.contractor_list.datas,t);
            } else {
                if(_.isEmpty(this.GLJIDMap)) this.GLJIDMap = _.indexBy(projectObj.project.projectGLJ.datas.gljList,'id');
                //剩下两个类型只有更新操作
                if(t.type == "unit_price"){
                    let g = this.GLJIDMap[t.projectGLJID];
                    if(g) {
                        let f = updateProperty(g.unit_price,t.doc);
                        if(f == true) sendPriceChange = true;
                        gljs.push(g);
                    }
                }
                if(t.type == "glj_list"){
                    let g = this.GLJIDMap[t.id];
                    if(g){
                        let f = updateProperty(g,t.doc);
                        if(f == true) sendPriceChange = true;
                        gljs.push(g);
                    }
                }
            }
        }
        this.GLJIDMap = {};
        return [gljs,sendPriceChange];

        function refreshDatas(datas,t_t) {
            if(t_t.action == "update"){
                let e = _.find(datas,{'ID':t_t.ID});
                if(e) updateProperty(e,t_t.doc);
            }
            if(t_t.action == "add") datas.push(t_t.doc);
            if(t_t.action == "delete") _.remove(datas,{'ID':t_t.ID});
        }


        function updateProperty(obj,doc) {
            let updatePrice = false;
            for(let k in doc){
                obj[k] = doc[k];
                if(k == 'base_price' || k == 'market_price') updatePrice = true;
            }
            return updatePrice;
        }
    },
    getEvaluateUpdateTasks:function (value,glj,dataCode,task) {
        let dataList = [],modelType='evaluate_list';
        if(dataCode == 'is_evaluate'){
            dataList = projectObj.project.evaluate_list.datas;
            modelType = 'evaluate_list';
        }else if(dataCode == 'is_eval_material'){
            dataList = projectObj.project.bid_evaluation_list.datas;
            modelType = 'bid_evaluation_list';
        }
        if(value == 1){ //勾选暂估选项,查看已有的暂估材料列表中是否有名称，编号等完全相同的记录，有则直接关联，无则添加
            let evaluate = null;
            let pindex = gljUtil.getIndex(glj,gljUtil.materialKeyArray);
            for(let e of dataList){
                let eIndex = gljUtil.getIndex(e,gljUtil.materialKeyArray);
                if(pindex == eIndex){
                    evaluate = e;
                    break;
                }
            }
            if(evaluate){//有找到则更新，没有则添加
                let edata = {type:modelType,doc:{},action:"update",ID:evaluate.ID};
                edata.doc = {projectGLJID:glj.id,is_related:1};
                task.push(edata);
                if(dataCode == 'is_evaluate'){
                    let udata = {type:'unit_price',doc:{},action:"update",projectGLJID:glj.id,id : glj.unit_price.id};
                    //if(evaluate.base_price != glj.unit_price.base_price) udata.doc['base_price'] = evaluate.base_price;
                    if(evaluate.market_price != glj.unit_price.market_price) udata.doc['market_price'] = evaluate.market_price;
                    if(!_.isEmpty(udata.doc)) task.push(udata);
                }
            }else {
                let ndata = {type:modelType,doc:{},action:"add"};
                ndata.doc['ID'] = uuid.v1();
                ndata.doc['projectGLJID'] = glj.id;
                ndata.doc['is_related'] = 1;
                if(dataCode == 'is_evaluate') ndata.doc['locked'] = 0;
                ndata.doc['seq'] = glj.code;
                ndata.doc['projectID'] = glj.project_id;
                ndata.doc['code'] = glj.code;
                ndata.doc['name'] = glj.name;
                ndata.doc['specs'] = glj.specs;
                ndata.doc['unit'] = glj.unit;
                ndata.doc['quantity'] = glj.quantity;
                ndata.doc['type'] = glj.type;
                ndata.doc['market_price'] = glj.unit_price.market_price;
                ndata.doc['originPlace'] = glj.originPlace;
                ndata.doc['vender'] = glj.vender;
                ndata.doc['remark'] = glj.remark;
                task.push(ndata);
            }
        }else if(value == 0){
            let t_evaluate = null;
            for(let e of dataList){
                if(e.projectGLJID == glj.id && e.is_related == 1){
                    t_evaluate = e;
                    break;
                }
            }
            if(t_evaluate){
                let tdata = {type:modelType,doc:{is_related:0,quantity:'0'},action:"update",ID:t_evaluate.ID};
                task.push(tdata);
            }
        }
    },
    onEvaluateMaterialSelectionChange:function (sender, args) {
        let me = configMaterialObj;
        let newSel = args.newSelections[0];
        let oldSel = args.oldSelections?args.oldSelections[0]:{};
        if(newSel.row != oldSel.row){
            me.showEvaluateRelateDatas();
            me.relateFilterAgain = false;
        }
    },
    onBidEvaluateMaterialValueChange:function (e,info) {
        let me = configMaterialObj,row = info.row, col = info.col;
        let dataCode = me.bidMaterialSetting.header[col].dataCode;
        let value = info.newValue;
        let bid = me.bidMaterialDatas[row];

        if (value&&! sheetCommonObj.checkData(col,me.bidMaterialSetting,value)) {
            alert('输入的数据类型不对，请重新输入!');
            return me.showBidMaterialDatas();
        }

        if(dataCode == 'marketPrice'){
            dataCode = 'market_price';
            if(bid.is_related){//关联的情况下，直接修改工料机价格
                if(bid.is_evaluate == 1){
                    alert("当前材料市场价已被锁定，修改请先返回人材机汇总界面解除锁定。");
                    return me.showBidMaterialDatas();
                }
                return projectObj.project.projectGLJ.updatePrice(bid,dataCode,value,'rg', null,projectGljObject.refreshViewsData);
            }
            value =  scMathUtil.roundToString(value,getDecimal('glj.unitPrice'));
        }
        if(value&& dataCode === 'quantity'){//修改数量需做4舍5入
            value =  scMathUtil.roundToString(value,getDecimal('glj.quantity'));
        }

        let edata = {type:'bid_evaluation_list',doc:{},action:"update",ID:bid.ID};
        if(bid[dataCode] == value) return me.showBidMaterialDatas();
        edata.doc[dataCode] = value;
        me.updateEvaluateMaterial([edata],false);
    },
    onSheetRangeChange:function (e,args) {
        let me = configMaterialObj,updateMap = {},modelType='',setting={},datas = [],tasks = [];
        switch (projectGljObject.displayType){
            case filterType.ZGCL:
                modelType="evaluate_list";
                setting = me.evaluateMaterialSetting;
                datas = me.evaluateMaterialDatas;
                break;
            case filterType.PBCL:
                modelType="bid_evaluation_list";
                setting = me.bidMaterialSetting;
                datas = me.bidMaterialDatas;
                break;
        }
        for(let c of args.changedCells){
            let dataCode = setting.header[c.col].dataCode;
            let value= args.sheet.getCell(c.row, c.col).text();
            let recode = datas[c.row];
            if(me.editChecking(recode,dataCode,modelType == "evaluate_list")==false){
                me.refreshSheetDatas();
                return ;
            }

            if (value&&!sheetCommonObj.checkData(c.col,setting,value)) {
                alert('输入的数据类型不对，请重新输入!');
                me.refreshSheetDatas();
                return ;
            }
            if(dataCode=='marketPrice'){
                dataCode = 'market_price';
                if(recode.is_related){//关联的情况下，直接修改工料机价格 暂时不支持批量修改
                    return projectObj.project.projectGLJ.updatePrice(recode,dataCode,value,'rg',null,projectGljObject.refreshViewsData);
                }
            }else {
                let tem = updateMap[recode.ID]?updateMap[recode.ID]:{};
                if(value&&dataCode === 'quantity')  value =  scMathUtil.roundToString(value,getDecimal('glj.quantity'));//修改数量需做4舍5入
                if(value == recode[dataCode]) continue;
                tem[dataCode] = value;
                updateMap[recode.ID] = tem;
            }
        }
        for(let ID in updateMap){
            let edata = {type:modelType,doc:updateMap[ID],action:"update",ID:ID};
            tasks.push(edata);
        }
        if(tasks.length > 0)  me.updateEvaluateMaterial(tasks,false);
    },

    onEvaluateMaterialValueChange:function (e,info) {
        let me = configMaterialObj,row = info.row, col = info.col;
        let dataCode = me.evaluateMaterialSetting.header[col].dataCode;
        let value = info.newValue;
        let evaluate = me.evaluateMaterialDatas[row];

        if (value&&! sheetCommonObj.checkData(col,me.evaluateMaterialSetting,value)) {
            alert('输入的数据类型不对，请重新输入!');
            return me.showEvaluateMaterialDatas();
        }

        if(dataCode == 'locked')  value = value == true?1:0;
        if(dataCode == 'marketPrice'){
            dataCode = 'market_price';
            if(evaluate.is_related){//关联的情况下，直接修改工料机价格
                return projectObj.project.projectGLJ.updatePrice(evaluate,dataCode,value,'rg',null,projectGljObject.refreshViewsData);
            }
        }
        if(value && dataCode === 'quantity'){//修改数量需做4舍5入
            value=  scMathUtil.roundToString(value,getDecimal('glj.quantity'));
        }

        let edata = {type:'evaluate_list',doc:{},action:"update",ID:evaluate.ID};
        if(evaluate[dataCode] == value) return me.showEvaluateMaterialDatas();
        edata.doc[dataCode] = value;
        me.updateEvaluateMaterial([edata],false);
    },
    onEvaluateRelateValueChange:function (e,info){
        let me = configMaterialObj,row = info.row, col = info.col;
        let value = info.newValue;
        let sheet = null,datas = [],field = "",type="";
        switch (projectGljObject.displayType){
            case filterType.ZGCL:
                sheet = me.evaluateMaterialSheet;
                datas = me.evaluateMaterialDatas;
                field = "is_evaluate";
                type="evaluate_list";
                break;
            case filterType.PBCL:
                sheet = me.bidMaterialSheet;
                datas = me.bidMaterialDatas;
                field = "is_eval_material";
                type="bid_evaluation_list";
                break;
            case filterType.AMAE:
                sheet = materialAdjustObj.getSheet();
                datas = materialAdjustObj.getSheetDatas();
                field = "is_contractor_material";
                type = "contractor_list";
        }

        let sel = sheet.getSelections()[0];
        let srow = sel.row == -1||sel.row == ""?0:sel.row;
        let task = [];
        value = value == true?1:0;
        if(datas.length>srow){
            let evaluate = datas[srow];
            let relate = me.evaluateRelateDatas[row];
            let pdata = {id:relate.id,doc:{},action:'update',type:"glj_list"};
            pdata.doc[field] = value;
            task.push(pdata);
            let tdata = {type:type,doc:{},action:"update",ID:evaluate.ID};
            if(value == 0){//如果是0的话
                tdata.doc = {is_related:0,quantity:'0'};
            }else {
                if(relate.unit != evaluate.unit){//检查单位是否相同，如果不同不能关联
                    alert("单位不一致，不允许关联！");
                    return me.showEvaluateRelateDatas();
                }
                //如果已经关联了其它项目工料机，要把那个项目工料机的是否暂估标记为否
                if(evaluate.is_related == 1){
                    let tdoc = {};
                    tdoc[field] = 0;
                    task.push({id:evaluate.projectGLJID,doc:tdoc,action:'update',type:"glj_list"});
                }
                //更新暂估材料的工料机ID，和关联标记
                tdata.doc = {projectGLJID:relate.id,is_related:1};
                if(projectGljObject.displayType == filterType.ZGCL){
                    //更新新关联工料机的市场价格
                    let udata = {type:'unit_price',doc:{},action:"update",projectGLJID:relate.from.id,id : relate.from.unit_price.id};
                    //if(evaluate.base_price != relate.from.unit_price.base_price) udata.doc['base_price'] = evaluate.base_price;
                    if(evaluate.marketPrice != relate.from.unit_price.market_price) udata.doc['market_price'] = evaluate.marketPrice;
                    if(!_.isEmpty(udata.doc)) task.push(udata);
                }
            }
            task.push(tdata);
            me.updateEvaluateMaterial(task);
        }
    },
    deleteMaterial:function (row) {
        let me = configMaterialObj;
        let evaluate = {},task=[],type='',field='';
        switch (projectGljObject.displayType){
            case filterType.ZGCL:
                evaluate = me.evaluateMaterialDatas[row];
                field = "is_evaluate";
                type="evaluate_list";
                break;
            case filterType.PBCL:
                evaluate = me.bidMaterialDatas[row];
                field = "is_eval_material";
                type="bid_evaluation_list";
                break;
            case  filterType.AMAE:
                let t_datas = materialAdjustObj.getSheetDatas();
                evaluate = t_datas[row];
                field = "is_contractor_material";
                type="contractor_list";
        }
        if(evaluate){
            task.push({type:type,action:"delete",ID:evaluate.ID});
            if(evaluate.is_related == 1){//如果关联了工料机，则要把工料机标记为不是暂估
                let tdoc = {};
                tdoc[field] = 0;
                task.push({id:evaluate.projectGLJID,doc:tdoc,action:'update',type:"glj_list"})
            }
            me.updateEvaluateMaterial(task);
        }
    },
    onEvaluateMaterialEditStarting:function (sender, args) {
        let me = configMaterialObj;
        let row = args.row,col = args.col;
        let evaluate = me.evaluateMaterialDatas[row];
        let dataCode = me.evaluateMaterialSetting.header[col].dataCode;
        if(me.editChecking(evaluate,dataCode,true)==false) args.cancel = true;
    },
    editChecking:function (record,dataCode,checkLock = false) {//return false 为不能编辑
        if(checkLock && record.locked) return false;
        if((dataCode == 'quantity'||dataCode == 'unit') && record.is_related) return false;//在关联的情况下，数量和单位不可编辑
        return true;
    },
    onBitMaterialEditStarting:function (sender, args) {
        let me = configMaterialObj;
        let row = args.row,col = args.col;
        let bid = me.bidMaterialDatas[row];
        let dataCode = me.bidMaterialSetting.header[col].dataCode;
        if(me.editChecking(bid,dataCode)==false) args.cancel = true;
    },
    onEvaluateRelateEditStarting:function (sender, args) {
        let me = configMaterialObj;
        let row = args.row,col = args.col;
        args.cancel = true;
    },
    insertEmptyRow:function () {
        let m_t = "";
        switch (projectGljObject.displayType){
            case filterType.ZGCL:
                m_t="evaluate_list";
                break;
            case filterType.PBCL:
                m_t="bid_evaluation_list";
                break;
        }
        let ndata = {type:m_t,doc:{},action:"add"};
        ndata.doc['ID'] = uuid.v1();
        ndata.doc['is_related'] = 0;
        if(m_t == "evaluate_list")ndata.doc['locked'] = 0;
        ndata.doc['seq'] = "";
        ndata.doc['projectID'] = projectObj.project.ID();
        ndata.doc['code'] = "";
        ndata.doc['name'] = "";
        ndata.doc['unit'] = "";
        ndata.doc['originPlace'] = "";
        ndata.doc['vender'] = "";
        ndata.doc['remark'] = "";
        configMaterialObj.updateEvaluateMaterial([ndata],false);
    },
    initRightClick : function() {
        let me = this;
        $.contextMenu({
            selector: '#config_material_sheet',
            build: function ($trigger, e) {
                me.rightClickTarget = SheetDataHelper.safeRightClickSelection($trigger, e, me.configSpread);
                return me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.viewport ||
                    me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                "addFromGLJ":{
                    name: '从人材机汇总中选择',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        return false;
                    },
                    callback: function (key, opt) {
                        if(projectGljObject.displayType == filterType.AMAE){
                            materialAdjustObj.checkedDefualtOption("glj_sel_input");
                            $("#selectFromGLJ").modal('show');
                        }else {
                            materialAdjustObj.checkedDefualtOption("pglj_sel_input");
                            $("#selectPGLJ").modal('show');
                        }
                    }
                },
                "insertRow":{
                    name: '插入',
                    icon: 'fa-sign-in',
                    disabled: function () {
                        return false;
                    },
                    callback: function (key, opt) {
                        if(projectGljObject.displayType == filterType.AMAE){
                            materialAdjustObj.insertEmptyRow();
                        }else {
                            configMaterialObj.insertEmptyRow();
                        }
                    }
                },
                "deleteAdjust": {
                    name: "删除",
                    icon: 'fa-trash-o',
                    disabled: function () {
                        return me.rightClickTarget.row === undefined;
                    },
                    callback: function (key, opt) {
                        let row = me.rightClickTarget.row;
                        me.deleteMaterial(row);
                    }
                }
            }
        });
    }
};

let pgljSelObj={
    spread:null,
    sheet:null,
    datas:[],
    setting:{
        header: [
            {headerName: "选择", headerWidth: 45, dataCode: "select", hAlign: "center", dataType: "String",cellType:'checkBox'},
            {headerName: "编码", headerWidth: 80, dataCode: "code", dataType: "String"},
            {headerName: "类型", headerWidth: 30, dataCode: "short_name", hAlign: "center", dataType: "String"},
            {headerName: "名称", headerWidth: 160, dataCode: "name", dataType: "String",cellType:'tipsCell'},
            {headerName: "规格型号", headerWidth: 100, dataCode: "specs", hAlign: "left", dataType: "String",cellType:'tipsCell'},
            {headerName: "单位", headerWidth: 45, dataCode: "unit", hAlign: "center", dataType: "String"},
            {headerName: "总消耗量", headerWidth: 90, dataCode: "quantity", hAlign: "right", dataType: "Number",decimalField:'glj.quantity'},
            {headerName: "市场价", headerWidth: 70, dataCode: "marketPrice", hAlign: "right", dataType: "Number",validator:"number"},//,decimalField:"glj.unitPrice"
            {headerName: "供货方式", headerWidth: 70, dataCode: "supply", hAlign: "center", dataType: "String",cellType:'comboBox',editorValueType:true,options:supplyComboMap},
            {headerName: "暂估", headerWidth: 45, dataCode: "is_evaluate", hAlign: "center", dataType: "String",cellType:'checkBox'},
            {headerName: "产地", headerWidth: 80, dataCode: "originPlace", hAlign: "left", dataType: "String"},
            {headerName: "厂家", headerWidth: 80, dataCode: "vender", hAlign: "left", dataType: "String"},
            {headerName: "备注", headerWidth: 100, dataCode: "remark", hAlign: "left", dataType: "String"}
        ],
        view: {
            lockColumns: ["is_evaluate"]
        }
    },
    checkType:"取消",//记住点击过的按钮的text
    initSpread:function () {
        if(!this.spread){
            this.spread = SheetDataHelper.createNewSpread($("#pglj_from_sheet")[0]);
            sheetCommonObj.spreadDefaultStyle(this.spread);
        }else {
            this.spread.refresh();
        }
        this.sheet = this.spread.getSheet(0);
        sheetCommonObj.initSheet(this.sheet,this.setting);
        this.sheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onEditStarting);
        this.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasting, this.onClipboardPasting);
        this.sheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onValueChanged);
        this.sheet.setRowHeight(0, 36, 1);
        disableRightMenu("pglj_from_sheet",this.spread);
    },
    onEditStarting:function (e,args) {
        args.cancel = true;
    },
    onClipboardPasting:function (e,args) {
        args.cancel = true;
    },
    onValueChanged:function (e,args) {
        let me = pgljSelObj;
        let value = args.newValue;
        value = value == true?1:0;
        me.datas[args.row].select = value;
    },
    showDatas:function () {
        this.datas = [];
        let gljList = projectObj.project.projectGLJ.datas.gljList;
        gljList = this.filterGLJ(gljList);
        gljList = sortProjectGLJ(gljList);
        for(let glj of gljList){
            this.datas.push(this.getSheetDatas(glj));
        }
        this.refreshDatas();
    },
    filterGLJ:function (gljList) {
        let typeMap = {};
        for(let ch of $(".pglj_sel_input:checked")){
            typeMap[$(ch).val()] = true;
        }
        let inputV = $("#pglj_sel_input").val();
        return _.filter(gljList,function (item) {
            if(item.quantity === 0 || item.quantity === '0') return false;
            let firstS = (item.type+"").substring(0,1);
            if(!typeMap[firstS]) return false;
            if(inputV!=""){//输入的关键字过滤
                if(item.code.indexOf(inputV)==-1 && item.name.indexOf(inputV)==-1) return false
            }
            return true;
        });
    },
    refreshDatas:function () {
        this.checkByType(this.checkType);
        sheetCommonObj.showData(this.sheet, this.setting,this.datas);
        this.sheet.setRowCount(this.datas.length);
    },
    getSheetDatas(glj){
        let projectGLJ = projectObj.project.projectGLJ;
        let materialIdList = projectGLJ.datas.constData.materialIdList;
        let data = materialAdjustObj.getCommonObject(glj);
        data.select = projectGljObject.displayType == filterType.ZGCL?glj.is_evaluate:glj.is_eval_material;
        data.from = glj;
        data.short_name = projectGLJ.getShortNameByID(glj.type);
        // 只有材料才显示是否暂估
       // if (materialIdList.indexOf(glj.type) >= 0) data.is_evaluate = glj.is_evaluate;
        data.is_eval_material = glj.is_eval_material;
        data.is_evaluate = glj.is_evaluate;
        return data;
    },
    checkByType:function (type) {
        for(let d of this.datas){
            d.select = 0;
            switch (type){
                case "全选":
                    d.select = 1;
                    break;
                case "全选主材":
                    if(d.type == 4) d.select = 1;
                    break;
                case "全选设备":
                    if(d.type == 5) d.select = 1;
                    break;
                case "取消":
                    d.select = projectGljObject.displayType == filterType.ZGCL?d.is_evaluate:d.is_eval_material;
                    break;
            }
        }
        //this.refreshDatas();
    },
    confirmSelect:function () {
        let tasks = [];
        let datas = [],modelType= '',field= '';
        switch (projectGljObject.displayType){
            case filterType.ZGCL:
                datas = projectObj.project.evaluate_list.datas;
                field = "is_evaluate";
                modelType="evaluate_list";
                break;
            case filterType.PBCL:
                datas =projectObj.project.bid_evaluation_list.datas;
                field = "is_eval_material";
                modelType="bid_evaluation_list";
                break;
        }

        let evaluateMap = _.indexBy(datas,"projectGLJID");
        let evaluateKeyMap = {};//关键字映射表
        for(let e of datas){
            let eIndex = gljUtil.getIndex(e,gljUtil.materialKeyArray);
            evaluateKeyMap[eIndex] = e;
        }
        for(let d of this.datas){
            if(d.select == 1){//如果是选中状态
                if(d[field] == 1) {//如果已经标记为暂估或评标材料，查看是否已经存在关联的材料
                    let evl = evaluateMap[d.id];
                    if(evl){
                        //这里应该是错误检查的保证，按正常是不应该出现这种情况的
                        if(evl.is_related !=1) tasks.push({type:modelType,doc:{projectGLJID:d.id,is_related:1},action:"update",ID:evl.ID});
                    }else {
                        tasks.push(getNewEval(d,modelType))
                    }
                }else {//如果不是暂估，要改成暂估
                    let pdata = {id:d.id,doc:{},action:'update',type:"glj_list"};
                    pdata.doc[field] = 1;
                    tasks.push(pdata);
                    let evaluate = evaluateKeyMap[gljUtil.getIndex(d,gljUtil.materialKeyArray)];
                    if(evaluate) {//如果已经存在5个关键字相同的暂估材料，则自动关联起来
                        let edata = {type:modelType,doc:{projectGLJID:d.id,is_related:1},action:"update",ID:evaluate.ID};
                        tasks.push(edata);
                        if(modelType == 'evaluate_list'){
                            let udata = {type:'unit_price',doc:{},action:"update",projectGLJID:d.id,id : d.from.unit_price.id};
                            if(evaluate.market_price != d.from.unit_price.market_price) udata.doc['market_price'] = evaluate.market_price;
                            if(!_.isEmpty(udata.doc)) tasks.push(udata);
                        }
                    }else {//如果不存在，则生成一条新的
                        tasks.push(getNewEval(d,modelType));
                    }
                }
            }else {//未选中状态的，检查一下是否存在关联的情况，取消关联
                let tdoc = {};
                tdoc[field] = 0;
                if(d[field] == 1)  tasks.push({id:d.id,doc:tdoc,action:'update',type:"glj_list"});
                let evl = evaluateMap[d.id];
                if(evl){
                    if(evl.is_related ==1) tasks.push({type:modelType,doc:{is_related:0},action:"update",ID:evl.ID});
                }
                let evaluate = evaluateKeyMap[gljUtil.getIndex(d,gljUtil.materialKeyArray)];
                if(evaluate) {
                    if(evaluate.is_related ==1) tasks.push({type:modelType,doc:{is_related:0},action:"update",ID:evaluate.ID});
                }
            }
        }
        if(tasks.length > 0) configMaterialObj.updateEvaluateMaterial(tasks);


        function getNewEval(d,m_t) {
            let ndata = {type:m_t,doc:{},action:"add"};
            ndata.doc['ID'] = uuid.v1();
            ndata.doc['projectGLJID'] = d.id;
            ndata.doc['is_related'] = 1;
            if(m_t == "evaluate_list")ndata.doc['locked'] = 0;
            ndata.doc['seq'] = d.code;
            ndata.doc['projectID'] = d.from.project_id;
            ndata.doc['code'] = d.code;
            ndata.doc['name'] = d.name;
            ndata.doc['specs'] = d.specs;
            ndata.doc['unit'] = d.unit;
            ndata.doc['quantity'] = d.quantity;
            ndata.doc['type'] = d.type;
            ndata.doc['market_price'] = d.from.unit_price.market_price;
            ndata.doc['originPlace'] = d.originPlace;
            ndata.doc['vender'] = d.vender;
            ndata.doc['remark'] = d.remark;
            return ndata;
        }
    }
};



$(function () {
  $("#filterAgain").click(function(){
      configMaterialObj.relateFilterAgain = true;//重新过滤标记
      configMaterialObj.showEvaluateRelateDatas();
  })

    $('#selectPGLJ').on('shown.bs.modal',function(e){
        pgljSelObj.checkType="取消";
        pgljSelObj.initSpread();
        pgljSelObj.showDatas();
    });

    $(".pglj_sel_input").change(function () {
        let check = $(this).prop("checked");
        if($(this).val() == 0){//勾选的是全选，其它的勾选项跟着改变
            for(let a of $(".pglj_sel_input")){
                $(a).prop("checked",check)
            }
        }else {//勾选其它选项
            let a_checked = true;
            for(let o of $(".pglj_sel_input_other")){//如果其它的有一个不勾选，则所有项也不打勾
                if($(o).prop("checked") === false){
                    a_checked = false;
                    break;
                }
            }
            $("#pglj_sel_all").prop("checked",a_checked);
        }

        pgljSelObj.showDatas();
    });

    $("#pglj_sel_btn_find").click(function () {
        pgljSelObj.showDatas();
    });

    $(".pglj_sel_check_btn").click(function () {
        pgljSelObj.checkType = $(this).text();
        pgljSelObj.refreshDatas();
    })

    $("#pglj_sel_confirm").click(function () {
        pgljSelObj.confirmSelect();
    })

});


