| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481 | 'use strict';/** * 材料调差 - 调差清单设置 * * @author EllisRan * @date 2022/1/7 * @version */function getStageId() {    return window.location.pathname.split('/')[5];}function findNotJoinLeafXmj(x, type = '') {    if (type === 'index') {        return notJoinList.findIndex(function (item) {            return item.gcl_id === x.gcl_id && item.xmj_id === x.id && (x.mx_id === undefined || (x.mx_id !== undefined && x.mx_id === item.mx_id));        });    }    return notJoinList.find(function (item) {        return item.gcl_id === x.gcl_id && item.xmj_id === x.id && (x.mx_id === undefined || (x.mx_id !== undefined && x.mx_id === item.mx_id));    });}function findNotChangeLeafXmj(x, type = '') {    if (type === 'index') {        return notChangeList.findIndex(function (item) {            return item.gcl_id === x.gcl_id && item.xmj_id === x.id && (x.mx_id === undefined || (x.mx_id !== undefined && x.mx_id === item.mx_id));        });    }    return notChangeList.find(function (item) {        return item.gcl_id === x.gcl_id && item.xmj_id === x.id && (x.mx_id === undefined || (x.mx_id !== undefined && x.mx_id === item.mx_id));    });}function getPasteHint (str, row = '') {    let returnObj = str;    if (row) {        returnObj.msg = '清单第' + (row+1) + '行' + (str.msg ? str.msg : str);    }    return returnObj;}function makeChecklistData(lists, checklists) {    let html = '';    if (lists.length > 0) {        for(const [i,l] of lists.entries()) {            const checklistInfo = _.find(checklists, { b_code: l.b_code, name: l.name, unit: l.unit, unit_price: l.unit_price });            const isChecked = checklistInfo ? ' checked' : '';            const isDisabled = checklistInfo && checklistInfo.had_bills === 1 ? ' disabled' : '';            html += '<tr>\n' +                '                                    <td><div class="text-center custom-control custom-checkbox mb-2">\n' +                '                                            <input type="checkbox" id="lists_'+ i +'" value="'+ i +'" name="customCheckbox" class="custom-control-input"'+ isChecked + isDisabled +'>\n' +                '                                            <label class="custom-control-label" for="lists_'+ i +'"></label>\n' +                '                                        </div></td>\n' +                '                                    <td class="text-center">'+ (i+1) +'</td>\n' +                '                                    <td>'+ l.b_code +'</td>\n' +                '                                    <td>'+ l.name +'</td>\n' +                '                                    <td class="text-center">'+ (l.unit ? l.unit : '') +'</td>\n' +                '                                    <td class="text-right">'+ (l.unit_price ? l.unit_price : '') +'</td>\n' +                '                                    <td class="text-right">'+ (l.quantity ? l.quantity : '') +'</td>\n' +                '                                    <td class="text-right">'+ (l.total_price ? l.total_price : '') +'</td>\n' +                '                                </tr>';        }    }    $('#lists_data').html(html);}// 清单搜索隐藏清单table部分值function remakeChecklistData(lists, showListData = lists) {    // 先加载台账数据    if (lists.length > 0) {        for (const [index,gcl] of lists.entries()) {            const isShow = _.find(showListData, gcl);            $('#lists_data tr').eq(index).css('display', (isShow ? 'table-row' : 'none'));        }    }}$(document).ready(() => {    function TipCellType()    {    }    TipCellType.prototype = new GC.Spread.Sheets.CellTypes.ColumnHeader();    TipCellType.prototype.getHitInfo = function (x, y, cellStyle, cellRect, context) {        return { x: x, y: y, row: context.row, col: context.col, cellRect: cellRect, sheetArea: context.sheetArea, sheet: context.sheet };    };    TipCellType.prototype.processMouseEnter = function (hitInfo){        if (!this._toolTipElement) {            var div = document.createElement("div");            $(div).css("position", "absolute")                .css("border", "1px #C0C0C0 solid")                .css("box-shadow", "1px 2px 5px rgba(0,0,0,0.4)")                .css("font", "9pt Arial")                .css("background", "#fff")                // .css("color", "#fff")                .css("z-index", "1000")                .css("padding", 5);            this._toolTipElement = div;        }        $(this._toolTipElement).text("单位数量:每一单位清单下所需工料消耗量。")            .css("top", hitInfo.y + 15)            .css("left", hitInfo.x - 15);        $(this._toolTipElement).hide();        // document.body.insertBefore(this._toolTipElement, null);        $('#material-spread-div').append(this._toolTipElement, null);        $(this._toolTipElement).show("fast");    };    TipCellType.prototype.processMouseLeave = function (hitInfo) {        if (this._toolTipElement) {            this._toolTipElement.remove();            this._toolTipElement = null;        }    };    autoFlashHeight();    // 清单table    const ledgerSpread = SpreadJsObj.createNewSpread($('#ledger-spread')[0]);    const ledgerSpreadSetting = {        cols: [            {title: '清单编号', colSpan: '1', rowSpan: '2', field: 'b_code', hAlign: 0, width: 80, formatter: '@'},            {title: '名称', colSpan: '1', rowSpan: '2', field: 'name', hAlign: 0, width: 220, formatter: '@'},            {title: '单位', colSpan: '1', rowSpan: '2', field: 'unit', hAlign: 1, width: 60, formatter: '@'},            {title: '单价', colSpan: '1', rowSpan: '2', field: 'unit_price', hAlign: 2, width: 70, type: 'Number'},            {title: '工程量', colSpan: '1', rowSpan: '2', field: 'quantity', hAlign: 2, width: 90, type: 'Number'},            {title: '台账金额', colSpan: '1', rowSpan: '2', field: 'total_price', hAlign: 2, width: 110, type: 'Number'},        ],        emptyRows: 0,        headRows: 1,        headRowHeight: [25, 25],        defaultRowHeight: 21,        headerFont: '12px 微软雅黑',        font: '12px 微软雅黑',        readOnly: true,    };    SpreadJsObj.initSheet(ledgerSpread.getActiveSheet(), ledgerSpreadSetting);    // 加载清单数据 - 暂时统一加载,如有需要,切换成动态加载并缓存    postData(window.location.pathname + '/load', { sid: isStageSelf ? materialStageData[0].sid : null }, function (result) {        ledger = result.ledger;        curLedgerData = result.curLedgerData;        pos = result.pos;        curPosData = result.curPosData;        // materialListData = result.materialListData;        notJoinList = result.materialNotJoinListData;        notChangeList = result.materialNotChangeListData;        materialChecklistData = result.materialChecklistData;        gclList = result.gclList;        if (isStageSelf) {            // updateBillsData(ms_id);            const newGclGatherListData = [];            for (const [index, s] of result.ledgerListData.entries()) {                gclGatherModel.loadLedgerData(_.cloneDeep(ledger), s);                gclGatherModel.loadPosData(_.cloneDeep(pos), result.posListData[index]);                const oneGclGatherData = gclGatherModel.gatherGclData().filter(item => {                    return item.qc_qty || item.contract_qty || item.qc_minus_qty                });                newGclGatherListData.push(oneGclGatherData);            }            gclGatherListData = newGclGatherListData;        }        // 解析清单汇总数据        gclGatherModel.loadLedgerData(ledger, curLedgerData);        gclGatherModel.loadPosData(pos, curPosData);        // gclGatherData = gclGatherModel.gatherGclData().filter(function (item) {        //     return item.unit_price || item.quantity;        // });        gclGatherData = gclGatherModel.gatherGclData();        console.log(gclGatherData);        const hadBillsidList = _.uniq(_.map(gclList, 'gcl_id'));        console.log(hadBillsidList, materialChecklistData);        // 对比清单设置和调差清单,还要和台账对比,显示已选清单列表 不同则更新到清单设置页中        const pushData = [];        const updateData = [];        for (const hb of hadBillsidList) {            const gcl = _.find(gclGatherData, function (item) {                return item.leafXmjs && item.leafXmjs.length > 0 && _.findIndex(item.leafXmjs, { gcl_id : hb }) !== -1;            });            if (gcl) {                const mc = _.find(materialChecklistData, { b_code: gcl.b_code, name: gcl.name, unit: gcl.unit, unit_price: gcl.unit_price });                // const newOrder = _.indexOf(gclGatherData, gcl);                // console.log(newOrder);                if (!mc && _.findIndex(pushData, { b_code: gcl.b_code, name: gcl.name, unit: gcl.unit, unit_price: gcl.unit_price }) === -1) {                    pushData.push({ b_code: gcl.b_code, name: gcl.name, unit: gcl.unit, unit_price: gcl.unit_price, quantity: (gcl.quantity ? gcl.quantity : null), total_price: (gcl.total_price ? gcl.total_price : null), had_bills: 1 });                }            }        }        const removeData = [];        for (const mc of materialChecklistData) {            const gcl = _.find(gclGatherData, { b_code: mc.b_code, name: mc.name, unit: mc.unit, unit_price: mc.unit_price });            // 判断是否已不存在工料清单,台账修改过后删除之            if (!gcl) {                removeData.push(mc.id);            } else {                const gcl_ids = gcl.leafXmjs ? _.uniq(_.map(gcl.leafXmjs, 'gcl_id')) : [];                const jiaoji = _.intersection(gcl_ids, hadBillsidList);                // const leafXmjs = gcl.leafXmjs ? gcl.leafXmjs.filter(item => item.gather_qty) : [];                // 更新had_bills值                const updateObj = { id: mc.id };                if (mc.had_bills === 1) {                    if (jiaoji.length === 0) {                        updateObj.mid = materialID;                        updateObj.had_bills = 0;                        // updateData.push({ id: mc.id, mid: materialID, had_bills: 0 });                    }                } else if (mc.had_bills === 0) {                    if (jiaoji.length !== 0) {                        updateObj.had_bills = 1;                    }                }                // 更新工程量及台账金额                if (mc.quantity !== (gcl.quantity ? gcl.quantity : null)) {                    updateObj.quantity = gcl.quantity ? gcl.quantity : null;                    updateObj.total_price = gcl.total_price ? gcl.total_price : null;                }                if(!_.isEqual(updateObj,{ id: mc.id })) updateData.push(updateObj);            }        }        console.log(pushData, removeData, updateData);        setChecklistData(pushData, removeData, updateData, true);    });    function setChecklistData(pushData, removeData, updateData = [], sendmsg = false) {        if (pushData.length > 0 || removeData.length > 0 || updateData.length > 0) {            postData(window.location.pathname + '/save', { type: 'resetChecklist', pushData, removeData, updateData }, function (result2) {                if (sendmsg && pushData.length > 0) {                    toastr.success('已同步历史调差清单数据至本页中');                }                if (sendmsg && removeData.length > 0) {                    toastr.warning('已删除部分与台账清单不匹配的清单数据');                }                materialChecklistData = result2;                showSjsData();            })        } else {            showSjsData();        }    }    function showSjsData() {        SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), SpreadJsObj.DataType.Data, materialChecklistData);        SpreadJsObj.resetTopAndSelect(ledgerSpread.getActiveSheet());        if (materialChecklistData.length > 0) {            const index = _.findIndex(gclGatherData, { b_code: materialChecklistData[0].b_code, name: materialChecklistData[0].name, unit: materialChecklistData[0].unit, unit_price: materialChecklistData[0].unit_price });            loadMaterialData(index, 0);        } else {            loadMaterialData(-1, 0);        }        const sheet = materialSpread.getActiveSheet();        sheet.suspendPaint();        sheet.setCellType(1, 3, new TipCellType(), spreadNS.SheetArea.colHeader);        sheet.resumePaint();    }    // 调差清单工料table    const materialSpread = SpreadJsObj.createNewSpread($('#material-spread')[0]);    const materialSpreadSetting = {        cols: [            {title: '清单工料含量|编号', colSpan: '5|1', rowSpan: '1|1', field: 'code', hAlign: 0, width: 80, formatter: '@', readOnly: true},            {title: '|名称', colSpan: '|1', rowSpan: '|1', field: 'name', hAlign: 0, width: 100, formatter: '@', readOnly: true},            {title: '|单位', colSpan: '|1', rowSpan: '|1', field: 'unit', hAlign: 1, width: 60, formatter: '@', readOnly: true},            {title: '|数量 �', colSpan: '|1', rowSpan: '|1', field: 'quantity', hAlign: 2, width: 80, type: 'Number', readOnly: 'readOnly.isEdit'},            {title: '|计算式', colSpan: '1', rowSpan: '|1', field: 'expr', hAlign: 2, width: 120, formatter: '@', readOnly: 'readOnly.isEdit'},        ],        emptyRows: 0,        headRows: 2,        headRowHeight: [25, 25],        defaultRowHeight: 21,        headerFont: '12px 微软雅黑',        font: '12px 微软雅黑',    };    const materialBase = {        isEdit: function (data) {            // 是否本期添加的工料            return data.order === stage_order;        }    };    const materialCol = {        readOnly: {            isEdit: function (data) {                // return !(!readOnly && materialBase.isEdit(data));                return readOnly;            },        },    };    SpreadJsObj.initSpreadSettingEvents(materialSpreadSetting, materialCol);    // 获取项目节数据    let materialList = [];    function loadMaterialData(iGclRow, iLXmjRow) {        const gcl = gclGatherData[iGclRow];        // const leafXmjs = gcl && gcl.leafXmjs ? gcl.leafXmjs.filter(item => {        //     return item.qc_qty || item.contract_qty        // }) : null;        if (gcl && gcl.leafXmjs) {            const gcl_ids = gcl.leafXmjs ? _.uniq(_.map(gcl.leafXmjs, 'gcl_id')) : [];            // const xmj2 = gcl.leafXmjs[iLXmjRow];            materialList = [];            const newMaterialList = _.uniqBy(_.filter(gclList, function (m) {                return _.indexOf(gcl_ids, m.gcl_id) !== -1;            }), 'mb_id');            for(const m of newMaterialList) {                const bills = _.find(materialBillsData, { id: m.mb_id });                if(bills) {                    m.code = bills.code;                    m.name = bills.name;                    m.unit = bills.unit;                }            }            console.log(newMaterialList);            materialList = newMaterialList;            // const leafXmjs = gcl.leafXmjs.filter(item => {            //     return item.qc_qty || item.contract_qty            // });            // const xmj = leafXmjs[iLXmjRow];            // materialList = _.filter(materialListData, function (m) {            //     return xmj && m.gcl_id === xmj.gcl_id && m.xmj_id === xmj.id && ((xmj.mx_id !==undefined && m.mx_id === xmj.mx_id) || xmj.mx_id === undefined);            // });            // 对清单调差工料table的单位数量进行改变            materialSpreadSetting.cols[materialSpreadSetting.cols.length - 2].title = '|' + '每' + gcl.unit + '数量 �';            SpreadJsObj.initSheet(materialSpread.getActiveSheet(), materialSpreadSetting);            SpreadJsObj.loadSheetData(materialSpread.getActiveSheet(), SpreadJsObj.DataType.Data, materialList);        } else {            materialSpreadSetting.cols[materialSpreadSetting.cols.length - 2].title = '数量 �';            SpreadJsObj.initSheet(materialSpread.getActiveSheet(), materialSpreadSetting);            SpreadJsObj.loadSheetData(materialSpread.getActiveSheet(), SpreadJsObj.DataType.Data, []);        }        SpreadJsObj.resetTopAndSelect(materialSpread.getActiveSheet());    }    // 对添加工料表格赋值    function changeMaterialTable() {        $('#materialBills tr').removeClass('table-secondary');        $('#materialBills').find('input').removeAttr('disabled');        $('#materialBills').find('input').prop('checked', false);        for (const ml of materialList) {            const mbIndex = _.findIndex(materialBillsData, {id : ml.mb_id });            if (mbIndex !== -1) {                $('#materialBills tr').eq(mbIndex).addClass('table-secondary');                $('#materialBills').find('input').eq(mbIndex).attr('disabled', true);                $('#materialBills').find('input').eq(mbIndex).prop('checked', true);            }        }    }    // 选中清单并添加    $('#set_checklist_btn').click(function () {        const select_checklist = $('#lists_data').find('input:checked:not(:disabled)');        const pushData = [];        for (const sc of select_checklist) {            const order = parseInt($(sc).val());            const checklistInfo = _.find(materialChecklistData, { b_code: gclGatherData[order].b_code, name: gclGatherData[order].name, unit: gclGatherData[order].unit, unit_price: gclGatherData[order].unit_price });            if (!checklistInfo) {                pushData.push({                    b_code: gclGatherData[order].b_code,                    name: gclGatherData[order].name,                    unit: gclGatherData[order].unit,                    unit_price: gclGatherData[order].unit_price,                    quantity: gclGatherData[order].quantity ? gclGatherData[order].quantity : null,                    total_price: gclGatherData[order].total_price ? gclGatherData[order].total_price : null,                    had_bills: 0,                })            }        }        const notSelect_checklist = $('#lists_data').find('input:not(:checked):not(:disabled)');        const removeData = [];        for (const nsc of notSelect_checklist) {            const order = parseInt($(nsc).val());            // const order = parseInt($(nsc).attr('data-index'));            const checklistInfo = _.find(materialChecklistData, { b_code: gclGatherData[order].b_code, name: gclGatherData[order].name, unit: gclGatherData[order].unit, unit_price: gclGatherData[order].unit_price });            if (checklistInfo) {               removeData.push(checklistInfo.id);            }        }        setChecklistData(pushData, removeData);        $('#addtclist').modal('hide');    });    // 筛选无调差工料清单    $('#notBills_checkList').click(function () {        const isCheck = $(this).is(':checked');        let newMaterialChecklistData = materialChecklistData;        if (isCheck) {            $('#bills0_checkList').prop('checked', false);            newMaterialChecklistData = _.filter(materialChecklistData, { had_bills: 0 });        }        SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), SpreadJsObj.DataType.Data, newMaterialChecklistData);        SpreadJsObj.resetTopAndSelect(ledgerSpread.getActiveSheet());        if (newMaterialChecklistData.length > 0) {            const index = _.findIndex(gclGatherData, { b_code: newMaterialChecklistData[0].b_code, name: newMaterialChecklistData[0].name, unit: newMaterialChecklistData[0].unit, unit_price: newMaterialChecklistData[0].unit_price });            loadMaterialData(index, 0);        } else {            loadMaterialData(-1, 0);        }    });    // 筛选调差工料清单为0    $('#bills0_checkList').click(function () {        const isCheck = $(this).is(':checked');        let newMaterialChecklistData = materialChecklistData;        if (isCheck) {            newMaterialChecklistData = [];            $('#notBills_checkList').prop('checked', false);            const materialList0 = _.uniq(_.map(_.filter(gclList, { quantity: 0 }), 'gcl_id'));            if (materialList0.length > 0) {                const hadMaterialChecklistData = _.filter(materialChecklistData, { had_bills: 1 });                for (const h of hadMaterialChecklistData) {                    const gcl = _.find(gclGatherData, { b_code: h.b_code, name: h.name, unit: h.unit, unit_price: h.unit_price });                    if (gcl && gcl.leafXmjs.length > 0 && _.indexOf(materialList0, gcl.leafXmjs[0].gcl_id) !== -1) {                        newMaterialChecklistData.push(h);                    }                }            }        }        SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), SpreadJsObj.DataType.Data, newMaterialChecklistData);        SpreadJsObj.resetTopAndSelect(ledgerSpread.getActiveSheet());        if (newMaterialChecklistData.length > 0) {            const index = _.findIndex(gclGatherData, { b_code: newMaterialChecklistData[0].b_code, name: newMaterialChecklistData[0].name, unit: newMaterialChecklistData[0].unit, unit_price: newMaterialChecklistData[0].unit_price });            loadMaterialData(index, 0);        } else {            loadMaterialData(-1, 0);        }    });    // 添加调差工料    $('#add_material_bill').click(function () {        // 获取已选工料        $('#materialBills').find('input:disabled').prop('checked', false);        const selectList = $('#materialBills').find('input:checked');        if (selectList.length === 0) {            toastr.warning('请选择调差工料');            $('#materialBills').find('input:disabled').prop('checked', true);            return false;        }        const mb_id = [];        for (let s = 0; s < selectList.length; s++) {            mb_id.push($('#materialBills').find('input:checked').eq(s).val());        }        // 获取当前项目节或部位明细id        const sheet = ledgerSpread.getActiveSheet();        const select = SpreadJsObj.getSelectObject(sheet);        const gclIndex = _.findIndex(gclGatherData, { b_code: select.b_code, name: select.name, unit: select.unit, unit_price: select.unit_price });        const gcl = gclGatherData[gclIndex].leafXmjs;        const ms_id = isStageSelf ? materialStageData[0].id : null;        const index = materialChecklistData.indexOf(select);        const datas = [];        for (const xmj of gcl) {            const notx = findNotJoinLeafXmj(xmj);            const notx2 = findNotChangeLeafXmj(xmj);            const data = {                xmj_id: xmj.id,                gcl_id: xmj.gcl_id,                mx_id: xmj.mx_id !== undefined ? xmj.mx_id : '',                contract_qty: xmj.contract_qty,                qc_qty: xmj.qc_qty,                qc_minus_qty: xmj.qc_minus_qty,                gather_qty: xmj.gather_qty,                is_join: notx !== undefined ? 0 : notx2 !== undefined ? 2 : 1,            };            if (ms_id) data.ms_id = ms_id;            datas.push(data);        }        if (isStageSelf) {            // 取所有的gclGatherData才行,然后获取下的值            const gclData = gclGatherData[gclIndex];            for (const [index, ms] of materialStageData.entries()) {                if (ms.id !== ms_id) {                    const gclOther = _.find(gclGatherListData[index], { b_code: gclData.b_code, name: gclData.name, unit: gclData.unit, unit_price: gclData.unit_price });                    if (gclOther) {                        const leafXmjs = gclOther.leafXmjs.filter(item => {                            return item.qc_qty || item.contract_qty || item.qc_minus_qty                        });                        for (const xmj of leafXmjs) {                            const notx = findNotJoinLeafXmj(xmj);                            const notx2 = findNotChangeLeafXmj(xmj);                            const data = {                                xmj_id: xmj.id,                                gcl_id: xmj.gcl_id,                                mx_id: xmj.mx_id ? xmj.mx_id : '',                                contract_qty: xmj.contract_qty,                                qc_qty: xmj.qc_qty,                                qc_minus_qty: xmj.qc_minus_qty,                                gather_qty: xmj.gather_qty,                                is_join: notx !== undefined ? 0 : notx2 !== undefined ? 2 : 1,                                ms_id: ms.id,                            };                            datas.push(data);                        }                    }                }            }        }        // 上传到数据库        console.log(datas, gcl);        postData(window.location.pathname + '/save', {type: 'adds', checklist: { id: select.id, had_bills: 1 }, postData: {xmjs: datas, mbIds: mb_id}}, function (result) {            // materialListData = result;            gclList = result;            materialChecklistData[index].had_bills = 1;            loadMaterialData(gclIndex, 0);            // SpreadJsObj.reLoadRowData(ledgerSpread.getActiveSheet(), index);            $('#addgl').modal('hide');        });        $('#materialBills').find('input:disabled').prop('checked', true);    });    if (!readOnly) {        // material-spread右键功能        const materialSpreadObj = {            del: function () {                const materialSheet = materialSpread.getActiveSheet();                const materialSelect = SpreadJsObj.getSelectObject(materialSheet);                const sheet = ledgerSpread.getActiveSheet();                const select = SpreadJsObj.getSelectObject(sheet);                const index = materialChecklistData.indexOf(select);                const gclIndex = _.findIndex(gclGatherData, { b_code: select.b_code, name: select.name, unit: select.unit, unit_price: select.unit_price });                const gcl = gclGatherData[gclIndex].leafXmjs;                const datas = [];                const ms_id = isStageSelf ? materialStageData[0].id : null;                for (const xmj of gcl) {                    const data = {                        xmj_id: xmj.id,                        gcl_id: xmj.gcl_id,                        mx_id: xmj.mx_id !== undefined ? xmj.mx_id : '',                    };                    if (ms_id) data.ms_id = ms_id;                    datas.push(data);                }                if (isStageSelf) {                    // 取所有的gclGatherData才行,然后获取下的值                    const gclData = gclGatherData[gclIndex];                    for (const [index, ms] of materialStageData.entries()) {                        if (ms.id !== ms_id) {                            const gclOther = _.find(gclGatherListData[index], { b_code: gclData.b_code, name: gclData.name, unit: gclData.unit, unit_price: gclData.unit_price });                            if (gclOther) {                                const leafXmjs = gclOther.leafXmjs.filter(item => {                                    return item.qc_qty || item.contract_qty || item.qc_minus_qty                                });                                for (const xmj of leafXmjs) {                                    const data = {                                        xmj_id: xmj.id,                                        gcl_id: xmj.gcl_id,                                        mx_id: xmj.mx_id ? xmj.mx_id : '',                                    };                                    if (_.indexOf(datas, data) === -1) {                                        datas.push(data);                                    }                                }                            }                        }                    }                }                const xmj = gcl[0];                const materialCount = _.size(_.filter(gclList, function (m) {                    return m.gcl_id === xmj.gcl_id;                }));                // const materialCount = _.size(_.filter(materialListData, function (m) {                //     return m.gcl_id === xmj.gcl_id && m.xmj_id === xmj.id && ((xmj.mx_id !==undefined && m.mx_id === xmj.mx_id) || xmj.mx_id === undefined);                // }));                let checklist = false;                if (materialCount === 1) {                    checklist = {                        id: select.id,                        had_bills: 0,                    }                }                console.log(datas, materialSelect.mb_id, checklist);                postData(window.location.pathname + '/save', {type: 'dels', checklist, postData: { xmjs: datas, mb_id: materialSelect.mb_id }, ms_id: isStageSelf ? materialStageData[0].id : null }, function (result) {                    // materialListData = result;                    gclList = result;                    if (checklist) materialChecklistData[index].had_bills = checklist.had_bills;                    loadMaterialData(gclIndex, 0);                    // SpreadJsObj.reLoadRowData(ledgerSpread.getActiveSheet(), index);                });            },            deletePress: function (sheet) {                return;            },            editStarting: function (e, info) {                const col = info.sheet.zh_setting.cols[info.col];                const select = SpreadJsObj.getSelectObject(info.sheet);                if (col.field === 'quantity') {                    if (select.expr && select.expr !== '') {                        info.sheet.getCell(info.row, info.col).text(select.expr);                    }                }            },            editEnded: function (e, info) {                if (info.sheet.zh_setting) {                    const select = SpreadJsObj.getSelectObject(info.sheet);                    const col = info.sheet.zh_setting.cols[info.col];                    const validText = info.editingText ? info.editingText.replace('\n', '') : null;                    let orgValue;                    if (col.field === 'quantity') {                        orgValue = validText && validText !== ''                            ? _.toNumber(validText) ? select.quantity : select.expr                            : (select.expr && select.expr !== '') ? select.expr : select.quantity;                    } else {                        orgValue = select[col.field];                    }                    if (orgValue == validText || ((!orgValue || orgValue === '') && (validText === '' || validText === null))) {                        SpreadJsObj.reLoadRowData(info.sheet, info.row);                        return;                    }                    const exprQuantity = {                        expr: '',                        quantity: 0,                    };                    const [valid, msg] = materialSpreadObj._checkExpr(validText, exprQuantity);                    if (!valid) {                        toastr.error(msg);                        SpreadJsObj.reLoadRowData(info.sheet, info.row);                        return;                    }                    if (isNaN(exprQuantity.quantity)) {                        toastr.error('不能输入其它非数字类型字符');                        SpreadJsObj.reLoadRowData(info.sheet, info.row);                        return;                    }                    const num = parseFloat(exprQuantity.quantity);                    if (num < 0 || !/^\d+(\.\d{1,6})?$/.test(num)) {                        toastr.warning('已保留6位小数');                        exprQuantity.quantity = ZhCalc.round(num, 6);                    }                    // 更新至服务器                    const ledgerSheet = ledgerSpread.getActiveSheet();                    const ledgerSelect = SpreadJsObj.getSelectObject(ledgerSheet);                    const gclIndex = _.findIndex(gclGatherData, { b_code: ledgerSelect.b_code, name: ledgerSelect.name, unit: ledgerSelect.unit, unit_price: ledgerSelect.unit_price });                    const gcl = gclGatherData[gclIndex].leafXmjs;                    const datas = [];                    const ms_id = isStageSelf ? materialStageData[0].id : null;                    for (const xmj of gcl) {                        const data = {                            xmj_id: xmj.id,                            gcl_id: xmj.gcl_id,                            mx_id: xmj.mx_id !== undefined ? xmj.mx_id : '',                        };                        if (ms_id) data.ms_id = ms_id;                        datas.push(data);                    }                    if (isStageSelf) {                        // 取所有的gclGatherData才行,然后获取下的值                        const gclData = gclGatherData[gclIndex];                        for (const [index, ms] of materialStageData.entries()) {                            if (ms.id !== ms_id) {                                const gclOther = _.find(gclGatherListData[index], { b_code: gclData.b_code, name: gclData.name, unit: gclData.unit, unit_price: gclData.unit_price });                                if (gclOther) {                                    const leafXmjs = gclOther.leafXmjs.filter(item => {                                        return item.qc_qty || item.contract_qty || item.qc_minus_qty                                    });                                    for (const xmj of leafXmjs) {                                        const data = {                                            xmj_id: xmj.id,                                            gcl_id: xmj.gcl_id,                                            mx_id: xmj.mx_id ? xmj.mx_id : '',                                        };                                        if (_.indexOf(datas, data) === -1) {                                            datas.push(data);                                        }                                    }                                }                            }                        }                    }                    console.log(exprQuantity, datas, select.mb_id);                    postData(window.location.pathname + '/save', { type:'updates', updateData: { xmjs: datas, expr: exprQuantity.expr, quantity: exprQuantity.quantity, mb_id: select.mb_id }, ms_id: isStageSelf ? materialStageData[0].id : null }, function (result) {                        // materialListData = result;                        gclList = result;                        loadMaterialData(gclIndex, 0);                        materialSpread.getActiveSheet().setSelection(info.row + 1, info.col, 1, 1);                    }, function () {                        SpreadJsObj.reLoadRowData(info.sheet, info.row);                    });                }            },            clipboardPasted(e, info) {                const hint = {                    cellError: {type: 'error', msg: '粘贴内容超出了表格范围'},                    numberExpr: {type: 'error', msg: '不能粘贴其它非数字类型字符'},                    numberCan: {type: 'warning', msg: '已保留6位小数'},                };                const range = info.cellRange;                const sortData = info.sheet.zh_data || [];                if (range.row + range.rowCount > sortData.length) {                    toastMessageUniq(hint.cellError);                    SpreadJsObj.reLoadSheetHeader(materialSpread.getActiveSheet());                    SpreadJsObj.reLoadSheetData(materialSpread.getActiveSheet());                    return;                }                if (sortData.length > 0 && range.col + range.colCount > 5) {                    toastMessageUniq(hint.cellError);                    SpreadJsObj.reLoadSheetHeader(materialSpread.getActiveSheet());                    SpreadJsObj.reLoadSheetData(materialSpread.getActiveSheet());                    return;                }                const data = [];                for (let iRow = 0; iRow < range.rowCount; iRow++) {                    let bPaste = true;                    const curRow = range.row + iRow;                    const materialData = { id: sortData[curRow].id, mb_id: sortData[curRow].mb_id };                    const hintRow = range.rowCount > 1 ? curRow : '';                    let sameCol = 0;                    for (let iCol = 0; iCol < range.colCount; iCol++) {                        const curCol = range.col + iCol;                        const colSetting = info.sheet.zh_setting.cols[curCol];                        if (!colSetting) continue;                        const validText = info.sheet.getText(curRow, curCol).replace('\n', '');                        const orgValue = sortData[curRow][colSetting.field];                        if (orgValue == validText || ((!orgValue || orgValue === '') && (validText === ''))) {                            sameCol++;                            if (range.colCount === sameCol)  {                                bPaste = false;                            }                            continue;                        }                        const exprQuantity = {                            expr: '',                            quantity: 0,                        };                        const [valid, msg] = materialSpreadObj._checkExpr(validText, exprQuantity);                        if (!valid) {                            toastMessageUniq(getPasteHint(msg, hintRow));                            bPaste = false;                            continue;                        }                        if (isNaN(exprQuantity.quantity)) {                            toastMessageUniq(getPasteHint(hint.numberExpr, hintRow));                            bPaste = false;                            continue;                        }                        const num = parseFloat(exprQuantity.quantity);                        if (num < 0 || !/^\d+(\.\d{1,6})?$/.test(num)) {                            toastMessageUniq(getPasteHint(hint.numberCan, hintRow));                            exprQuantity.quantity = ZhCalc.round(num, 6);                        }                        materialData.expr = exprQuantity.expr;                        materialData.quantity = exprQuantity.quantity;                    }                    if (bPaste) {                        data.push(materialData);                    } else {                        SpreadJsObj.reLoadRowData(info.sheet, curRow);                    }                }                if (data.length === 0) {                    SpreadJsObj.reLoadRowData(info.sheet, info.cellRange.row, info.cellRange.rowCount);                    return;                }                const ledgerSheet = ledgerSpread.getActiveSheet();                const ledgerSelect = SpreadJsObj.getSelectObject(ledgerSheet);                const gclIndex = _.findIndex(gclGatherData, { b_code: ledgerSelect.b_code, name: ledgerSelect.name, unit: ledgerSelect.unit, unit_price: ledgerSelect.unit_price });                const gcl = gclGatherData[gclIndex].leafXmjs;                const datas = [];                const ms_id = isStageSelf ? materialStageData[0].id : null;                for (const xmj of gcl) {                    const data2 = {                        xmj_id: xmj.id,                        gcl_id: xmj.gcl_id,                        mx_id: xmj.mx_id !== undefined ? xmj.mx_id : '',                    };                    if (ms_id) data2.ms_id = ms_id;                    datas.push(data2);                }                if (isStageSelf) {                    // 取所有的gclGatherData才行,然后获取下的值                    const gclData = gclGatherData[gclIndex];                    for (const [index, ms] of materialStageData.entries()) {                        if (ms.id !== ms_id) {                            const gclOther = _.find(gclGatherListData[index], { b_code: gclData.b_code, name: gclData.name, unit: gclData.unit, unit_price: gclData.unit_price });                            if (gclOther) {                                const leafXmjs = gclOther.leafXmjs.filter(item => {                                    return item.qc_qty || item.contract_qty || item.qc_minus_qty                                });                                for (const xmj of leafXmjs) {                                    const data = {                                        xmj_id: xmj.id,                                        gcl_id: xmj.gcl_id,                                        mx_id: xmj.mx_id ? xmj.mx_id : '',                                    };                                    if (_.indexOf(datas, data) === -1) {                                        datas.push(data);                                    }                                }                            }                        }                    }                }                console.log(data, datas);                // 更新至服务器                postData(window.location.pathname + '/save', { type:'pastes', updateData: { xmjs: datas, pasteData: data }, ms_id: isStageSelf ? materialStageData[0].id : null }, function (result) {                    // materialListData = result;                    gclList = result;                    loadMaterialData(gclIndex, 0);                    materialSpread.getActiveSheet().setSelection(info.cellRange.row, info.cellRange.col, info.cellRange.rowCount, info.cellRange.colCount);                }, function () {                    SpreadJsObj.reLoadRowData(info.sheet, info.row);                });            },            _checkExprValid(expr) {                if (!expr) return [true, null];                const param = [];                let num = '', base = '';                for (let i = 0, iLen = expr.length; i < iLen; i++) {                    if (/^[\d\.%]+/.test(expr[i])) {                        if (base !== '') {                            param.push({type: 'base', value: base});                            base = '';                        }                        num = num + expr[i];                    } else if (expr[i] === '(') {                        if (num !== '') {                            param.push({type: 'num', value: num});                            num = '';                        }                        if (base !== '') {                            param.push({type: 'base', value: base});                            base = '';                        }                        param.push({type: 'left', value: '('});                    } else if (expr[i] === ')') {                        if (num !== '') {                            param.push({type: 'num', value: num});                            num = '';                        }                        if (base !== '') {                            param.push({type: 'base', value: base});                            base = '';                        }                        param.push({type: 'right', value: ')'});                    } else if (/^[\+\-*\/]/.test(expr[i])) {                        if (num !== '') {                            param.push({type: 'num', value: num});                            num = '';                        }                        if (base !== '') {                            param.push({type: 'base', value: base});                            base = '';                        }                        param.push({type: 'calc', value: expr[i]});                    } else {                        return [false, '输入的表达式含有非法字符: ' + expr[i]];                    }                }                if (num !== '') {                    param.push({type: 'num', value: num});                    num = '';                }                if (base !== '') {                    param.push({type: 'base', value: base});                    base = '';                }                if (param.length === 0) return true;                if (param.length > 1) {                    if (param[0].value === '-' && param[1].type === 'num') {                        param[1].value = '-' + param[1].value;                        param.shift();                    }                }                const iLen = param.length;                let iLeftCount = 0, iRightCount = 0;                for (const [i, p] of param.entries()) {                    if (p.type === 'calc') {                        if (i === 0 || i === iLen - 1)                            return [false, '输入的表达式非法:计算符号' + p.value + '前后应有数字'];                    }                    if (p.type === 'num') {                        num = p.value.replace('%', '');                        if (p.value.length - num.length > 1)                            return [false, '输入的表达式非法:' + p.value + '不是一个有效的数字'];                        num = _.toNumber(num);                        if (num === undefined || num === null || _.isNaN(num))                            return [false, '输入的表达式非法:' + p.value + '不是一个有效的数字'];                        if (i > 0) {                            if (param[i - 1].type !== 'calc' && param[i - 1].type !== 'left') {                                return [false, '输入的表达式非法:' + p.value + '前应有运算符'];                            } else if (param[i - 1].value === '/' && num === 0) {                                return [false, '输入的表达式非法:请勿除0'];                            }                        }                    }                    if (p.type === 'base') {                        if (i > 0 && (param[i - 1].type === 'num' || param[i - 1].type === 'right'))                            return [false, '输入的表达式非法:' + p.value + '前应有运算符'];                    }                    if (p.type === 'left') {                        iLeftCount += 1;                        if (i !== 0 && param[i-1].type !== 'calc')                            return [false, '输入的表达式非法:(前应有运算符'];                    }                    if (p.type === 'right') {                        iRightCount += 1;                        if (i !== iLen - 1 && param[i+1].type !== 'calc')                            return [false, '输入的表达式非法:)后应有运算符'];                        if (iRightCount > iLeftCount)                            return [false, '输入的表达式非法:")"前无对应的"("'];                    }                }                if (iLeftCount > iRightCount)                    return [false, '输入的表达式非法:"("后无对应的")"'];                return [true, ''];            },            _checkExpr: function (text, data) {                if (text) {                    const num = _.toNumber(text);                    if (num) {                        data.quantity = num;                        data.expr = '';                    } else {                        const expr = $.trim(text).replace('\t', '').replace('=', '').toLowerCase();                        const [valid, msg] = this._checkExprValid(expr);                        if (!valid) return [valid, msg];                        data.expr = expr;                        data.quantity = ZhCalc.calcExpr.calcExprStrRpn(expr.replace('%', '/100'));                    }                } else {                    data.quantity = 0;                    data.expr = '';                }                return [true, ''];            },        };        materialSpread.bind(spreadNS.Events.EditStarting, materialSpreadObj.editStarting);        materialSpread.bind(spreadNS.Events.EditEnded, materialSpreadObj.editEnded);        materialSpread.bind(spreadNS.Events.ClipboardPasted, materialSpreadObj.clipboardPasted);        SpreadJsObj.addDeleteBind(materialSpread, materialSpreadObj.deletePress);        $.contextMenu({            selector: '#material-spread',            build: function ($trigger, e) {                const target = SpreadJsObj.safeRightClickSelection($trigger, e, materialSpread);                return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;            },            items: {                'create': {                    name: '添加工料',                    icon: 'fa-sign-in',                    callback: function (key, opt) {                        // 获取已选清单                        changeMaterialTable();                        $('#addgl').modal('show');                    },                    disabled: function (key, opt) {                        const sheet = ledgerSpread.getActiveSheet();                        const select = SpreadJsObj.getSelectObject(sheet);                        if (!select) {                            return true;                        }                        return readOnly;                    }                },                'delete': {                    name: '删除工料',                    icon: 'fa-remove',                    callback: function (key, opt) {                        materialSpreadObj.del(materialSpread.getActiveSheet());                    },                    disabled: function (key, opt) {                        const sheet = materialSpread.getActiveSheet();                        const selection = sheet.getSelections();                        const sel = selection ? selection[0] : sheet.getSelections()[0];                        const select = SpreadJsObj.getSelectObject(sheet);                        if (!select) {                            return true;                        }                        if (!readOnly && sel.rowCount === 1 && select && materialBase.isEdit(select)) {                            return false;                        } else {                            return true;                        }                    }                },            }        });    }    // 切换清单行,读取所属项目节数据    ledgerSpread.getActiveSheet().bind(spreadNS.Events.SelectionChanged, function (e, info) {        if (info.oldSelections !== undefined) {            const iOldRow = info.oldSelections[0].row, iNewRow = info.newSelections[0].row;            if (iNewRow !== iOldRow) {                const sheet = ledgerSpread.getActiveSheet();                const select = SpreadJsObj.getSelectObject(sheet);                const index = _.findIndex(gclGatherData, { b_code: select.b_code, name: select.name, unit: select.unit, unit_price: select.unit_price });                loadMaterialData(index, 0);            }        }    });    $('#open_addtclist').click(function () {        $('#tclist_search').val('');        $('#tclist_search').siblings('a').hide();        makeChecklistData(gclGatherData, materialChecklistData);        $('#addtclist').modal('show');    });    // 回车提交    $('#tclist_search').on('keypress', function () {        if(window.event.keyCode === 13) {            $(this).blur();        }    });    $('#tclist_search').on('blur', function () {        const value = _.trim($(this).val());        let showListData = gclGatherData;        if (value !== '') {            $(this).siblings('a').show();            showListData = _.filter(gclGatherData, function (c) {                return (c.b_code && c.b_code.indexOf(value) !== -1) || (c.name && c.name.indexOf(value) !== -1);            })        } else {            $(this).siblings('a').hide();        }        remakeChecklistData(gclGatherData, showListData);    });    $('.remove-btn').on('click', function () {        $(this).hide();        $(this).siblings('input').val('');        remakeChecklistData(gclGatherData);    });    // 显示有调差工料清单    // $('#show_material_gcl').click(function () {    //     if ($(this).is(':checked')) {    //         const hadMaterialGclGatherData = [];    //         const hadGclIdList = [];    //         for (const ml of materialListData) {    //             if (hadGclIdList.indexOf(ml.gcl_id) === -1) {    //                 hadGclIdList.push(ml.gcl_id);    //             }    //         }    //         for (const gcl of gclGatherData) {    //             for (const index in gcl.leafXmjs) {    //                 const gcl_id = gcl.leafXmjs[index].gcl_id;    //                 if (hadGclIdList.indexOf(gcl_id) !== -1) {    //                     hadMaterialGclGatherData.push(gcl);    //                     break;    //                 }    //             }    //         }    //         gclGatherData = hadMaterialGclGatherData;    //     } else {    //         gclGatherModel.loadLedgerData(ledger, curLedgerData);    //         gclGatherModel.loadPosData(pos, curPosData);    //         gclGatherData = gclGatherModel.gatherGclData().filter(item => {    //             return item.qc_qty || item.contract_qty    //         });    //     }    //     SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), SpreadJsObj.DataType.Data, gclGatherData);    //     loadLeafXmjData(0);    //     loadMaterialData(0, 0);    //     SpreadJsObj.resetTopAndSelect(ledgerSpread.getActiveSheet());    //     SpreadJsObj.resetTopAndSelect(leafXmjSpread.getActiveSheet());    //     SpreadJsObj.resetTopAndSelect(materialSpread.getActiveSheet());    // });    $.subMenu({        menu: '#sub-menu', miniMenu: '#sub-mini-menu', miniMenuList: '#mini-menu-list',        toMenu: '#to-menu', toMiniMenu: '#to-mini-menu',        key: 'menu.1.0.0',        miniHint: '#sub-mini-hint', hintKey: 'menu.hint.1.0.1',        callback: function (info) {            if (info.mini) {                $('.panel-title').addClass('fluid');                $('#sub-menu').removeClass('panel-sidebar');            } else {                $('.panel-title').removeClass('fluid');                $('#sub-menu').addClass('panel-sidebar');            }            autoFlashHeight();            ledgerSpread.refresh();            materialSpread.refresh();        }    });    $.divResizer({        select: '#right-spr',        callback: function () {            ledgerSpread.refresh();            materialSpread.refresh();            const width = (($('#right-view').width()/$('#right-view').parent('div').width())*100).toFixed();            setLocalCache('material_checklist_' + materialID, width);        }    });    // 展开收起工料并浏览器记住本期展开收起    $('a', '.right-nav').bind('click', function () {        const tab = $(this), tabPanel = $(tab.attr('content'));        if (!tab.hasClass('active')) {            $('a', '.side-menu').removeClass('active');            $('.tab-content .tab-select-show').removeClass('active');            tab.addClass('active');            tabPanel.addClass('active');            showSideTools(tab.hasClass('active'));            if (tab.attr('content') === '#material-tab') {                const width = (($('#right-view').width()/$('#right-view').parent('div').width())*100).toFixed();                setLocalCache('material_checklist_' + materialID, width);            }        } else {            removeLocalCache('material_checklist_' + materialID);            tab.removeClass('active');            tabPanel.removeClass('active');            showSideTools(tab.hasClass('active'));        }        ledgerSpread.refresh();        materialSpread.refresh();    });    // 根据浏览器记录展开收起    if (getLocalCache('material_checklist_' + materialID)) {        const tab = $('.right-nav a[content="#material-tab"]'), tabPanel = $(tab.attr('content'));        $('a', '.side-menu').removeClass('active');        $('.tab-content .tab-select-show').removeClass('active');        tab.addClass('active');        tabPanel.addClass('active');        $('#right-view').width(getLocalCache('material_checklist_' + materialID) + '%');        showSideTools(tab.hasClass('active'));        ledgerSpread.refresh();        materialSpread.refresh();    }    // 导入功能    // 上传图片    let importFile = null;    $('#upload-list').click(function () {        if (materialBillsData.length === 0) {            toastr.error('请添加工料再导入。');            return        }        $("#import").modal('show');        // $(this).siblings('input').trigger('click');    });    $('#upload-list-file').change(function () {        const file = this.files[0];        importFile = file;    });    $('#import_btn').click(function() {        if (!importFile) {            toastr.error('请选择json或excel文件再确定');            return;        }        $('#import').modal('hide');        const ext = importFile.name.toLowerCase().split('.').splice(-1)[0];        const imgStr = /(xls|xlsx|json|XLS|XLSX|JSON)$/;        if (!imgStr.test(ext)) {            toastr.error('请导入正确格式的json或excel文件。');            return        }        const fileReader = new FileReader();        fileReader.onload = async function(ev) {            try{                const data = ev.target.result;                let tree = [];                const ignoreUnitPrice = $('#ignore').is(':checked');                resetExport();                $('#okedit').modal('show');                setProgress($('#export-progress'), 30);                if (/(xls|xlsx|XLS|XLSX)$/.test(ext)) {                    const workbook = XLSX.read(data, {type: 'binary'}); // 以二进制流方式读取得到整份excel表格对象                    const jsonData = transExcel(XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], { defval: null }));                    if (!(jsonData[0] && jsonData[0].b_code !== undefined && jsonData[0].b_code !== null &&                        jsonData[0].gljcode !== undefined && jsonData[0].name !== undefined && jsonData[0].name !== undefined &&                        jsonData[0].unit !== undefined && jsonData[0].unit_price !== undefined)) {                        throw 'excel必须按指定格式内容上传';                    }                    tree = _.filter(jsonData, function (item) {                        return item.b_code !== null;                    });                    let lastIndex = 0;// 防止导入相同的清单导致导入的含量数量增多                    for (const [i,t] of tree.entries()) {                        const jIndex1 = _.findIndex(jsonData, { b_code: t.b_code, name: t.name, unit: t.unit, unit_price: t.unit_price }, lastIndex);                        lastIndex = jIndex1;                        if (i + 1 < tree.length) {                            const jIndex2 = _.findIndex(jsonData, { b_code: tree[i+1].b_code, name: tree[i+1].name, unit: tree[i+1].unit, unit_price: tree[i+1].unit_price }, lastIndex);                            t.children = jsonData.slice(jIndex1 + 1, jIndex2);                            lastIndex = jIndex2;                        } else {                            t.children = jsonData.slice(jIndex1 + 1);                        }                    }                } else {                    const ascii = jschardet.detect(data.substring(0, 10000));                    iconv.skipDecodeWarning = true                    tree = JSON.parse(iconv.decode(data, ascii.encoding));// 需要转码,否则前端处理中文会出现乱码                    if (!(tree[0] && tree[0].b_code !== undefined && tree[0].b_code !== null &&                        tree[0].gljcode !== undefined && tree[0].name !== undefined && tree[0].name !== undefined &&                        tree[0].unit !== undefined && tree[0].unit_price !== undefined)) {                        throw 'json必须按指定格式内容上传';                    }                }                stopProgress($('#export-progress'));                $('#bill-detail').show();                setProgress($('#bill-progress'), 30);                // 导入先生成materialCheckList,再生成materialBillsData,最后生成materialListData                console.log(tree, gclGatherData, materialChecklistData, materialBillsData);                const pushChecklist = [];                const pushBillsData = [];                const needPushTree = [];                // 分析materialCheckList和tree,找出相同的清单并插入对应不存在的工料                for (const t of tree) {                    if(t.children.length === 0) continue;                    const findObject = {                        b_code: t.b_code ? t.b_code.toString() : t.b_code,                        name: t.name ? t.name.toString() : t.name,                        unit: t.unit ? t.unit.toString() : t.unit,                    };                    if (!ignoreUnitPrice) findObject.unit_price = t.unit_price ? parseFloat(t.unit_price) : null;                    const order = _.findIndex(gclGatherData, findObject);                    const mlOrder = _.findIndex(materialChecklistData, findObject);                    const haveQuantity = _.find(t.children, function (item) { return item.quantity && item.quantity !== 0 }) ? 1 : 0;                    if (mlOrder === -1 && order !== -1 && haveQuantity && _.findIndex(pushChecklist, findObject) === -1) {                        pushChecklist.push({                            b_code: gclGatherData[order].b_code,                            name: gclGatherData[order].name,                            unit: gclGatherData[order].unit,                            unit_price: gclGatherData[order].unit_price,                            quantity: gclGatherData[order].quantity ? gclGatherData[order].quantity : null,                            total_price: gclGatherData[order].total_price ? gclGatherData[order].total_price : null,                            had_bills: 0,                        });                    } else if (mlOrder === -1 && order === -1) {                        continue;                    } else if (!haveQuantity) {                        continue;                    }                    needPushTree.push(t);                    // for (const c of t.children) {                    //     const mbOrder = _.findIndex(materialBillsData, { code: c.gljcode, name: c.name, unit: c.unit });                    //     if (c.b_code !== null && mbOrder === -1 && _.findIndex(pushBillsData, { code: c.gljcode, name: c.name, unit: c.unit }) === -1) {                    //         pushBillsData.push({                    //             code: c.gljcode,                    //             name: c.name,                    //             unit: c.unit,                    //             spec: c.specs,                    //         })                    //     }                    // }                }                if (needPushTree.length === 0) {                    throw '不存在需要导入的工料清单含量';                }                // 先上传需要生成的清单及工料                if (pushChecklist.length > 0 || pushBillsData.length > 0) {                    postData(window.location.pathname + '/save', { type:'exportCB', addChecklist: pushChecklist, addBillsList: pushBillsData }, async function (result) {                        // materialListData = result;                        materialChecklistData = result.materialChecklistData;                        materialBillsData = result.materialBillsData;                        materialStageBillsData = result.materialStageBillsData;                        stopProgress($('#bill-progress'));                        await pushListData(needPushTree);                    }, function () {                        stop = true;                        clearInterval(interval);                        setTimeout(function () {                            $('#okedit').modal('hide');                        }, 1000);                    });                } else {                    stopProgress($('#bill-progress'));                    await pushListData(needPushTree);                }            } catch (error) {                console.log(error);                toastr.error(error);                stop = true;                clearInterval(interval);                setTimeout(function () {                    $('#okedit').modal('hide');                    $('#import').modal('show');                }, 1000);                return            }            // 分析jsondata,得出每个清单间工料数量,生成新的树结构数组            // let persons = []; // 存储获取到的数据            // // 表格的表格范围,可用于判断表头是否数量是否正确            // let fromTo = '';            // // 遍历每张表读取            // for (const sheet in workbook.Sheets) {            //     if (workbook.Sheets.hasOwnProperty(sheet)) {            //         fromTo = workbook.Sheets[sheet]['!ref'];            //         console.log(fromTo);            //         persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));            //         // break; // 如果只取第一张表,就取消注释这行            //     }            // }            // console.log(persons);        };        // 以二进制方式打开文件        fileReader.readAsBinaryString(importFile);        $('#upload-list-file').val('');        importFile = null;    });    function sleep(millisecond) {        return new Promise(resolve => {            setTimeout(() => {                resolve()            }, millisecond)        })    }    let value = 0;    let interval;    let stop = false;    function setProgress(_this, time = 50) {        interval = setInterval(function () {            if (value < 100) {                value = parseInt(value) + 1;                _this.css("width", value + "%").text(value + "%");            } else if (value === 100) {                value = parseInt(value) + 1;                value = 30;            }        }, time);    }    function resetExport() {        resetProgress($('#export-progress'));        $('#bill-detail').hide();        resetProgress($('#bill-progress'));        $('#list-detail').hide();        resetProgress($('#list-progress'));    }    function resetProgress(_this) {        _this.removeClass('bg-success');        _this.css("width", "0%").text("0%").attr('aria-valuenow', '0');    }    function stopProgress(_this) {        if (interval) {            _this.addClass('bg-success');            _this.css("width", "100%").text("100%");            value = 0;            stop = true;            clearInterval(interval);            interval = 0;        }    }    async function pushListData(tree = []) {        if (tree.length > 0) {            const ignoreUnitPrice = $('#ignore').is(':checked');            for (const [i,t] of tree.entries()) {                $('#list-detail').find('b').text(t.b_code);                resetProgress($('#list-progress'));                if (!interval) {                    $('#list-detail').show();                    setProgress($('#list-progress'), 30);                }                const mbList = [];                for (const mb of t.children) {                    if (mb.quantity) {                        const mbInfo = _.find(materialBillsData, { code: mb.gljcode+'', name: mb.name+'', unit: mb.unit+'' });                        if (mbInfo) {                            const num = parseFloat(mb.quantity);                            if (num < 0 || !/^\d+(\.\d{1,6})?$/.test(num)) {                                // toastr.warning('已保留6位小数');                                mb.quantity = ZhCalc.round(num, 6);                            }                            mbList.push({ id: mbInfo.id, quantity: mb.quantity });                        }                    }                }                if (mbList.length === 0 && i+1 === tree.length) {                    stopProgress($('#list-progress'));                    toastr.success('导入成功');                    setTimeout(function () { $('#okedit').modal('hide') }, 2000);                    showSjsData();                    return;                }                if (mbList.length === 0) {                    continue;                }                const findObject = { b_code: t.b_code ? t.b_code.toString() : t.b_code,                    name: t.name ? t.name.toString() : t.name,                    unit: t.unit ? t.unit.toString() : t.unit,                };                if (!ignoreUnitPrice) findObject.unit_price = t.unit_price ? parseFloat(t.unit_price) : null;                const gclIndex = _.findIndex(gclGatherData, findObject);                const gcl = gclGatherData[gclIndex].leafXmjs;                const ms_id = isStageSelf ? materialStageData[0].id : null;                // const index = materialChecklistData.indexOf(select);                const datas = [];                for (const xmj of gcl) {                    const notx = findNotJoinLeafXmj(xmj);                    const notx2 = findNotChangeLeafXmj(xmj);                    const data = {                        xmj_id: xmj.id,                        gcl_id: xmj.gcl_id,                        mx_id: xmj.mx_id !== undefined ? xmj.mx_id : '',                        contract_qty: xmj.contract_qty,                        qc_qty: xmj.qc_qty,                        qc_minus_qty: xmj.qc_minus_qty,                        gather_qty: xmj.gather_qty,                        is_join: notx !== undefined ? 0 : notx2 !== undefined ? 2 : 1,                    };                    if (ms_id) data.ms_id = ms_id;                    datas.push(data);                }                if (isStageSelf) {                    // 取所有的gclGatherData才行,然后获取下的值                    const gclData = gclGatherData[gclIndex];                    for (const [index, ms] of materialStageData.entries()) {                        if (ms.id !== ms_id) {                            const gclFindObject = { b_code: gclData.b_code ? gclData.b_code.toString() : gclData.b_code,                                name: gclData.name ? gclData.name.toString() : gclData.name, unit: gclData.unit ? gclData.unit.toString() : gclData.unit };                            if (!ignoreUnitPrice) gclFindObject.unit_price = gclData.unit_price;                            const gclOther = _.find(gclGatherListData[index], gclFindObject);                            if (gclOther) {                                const leafXmjs = gclOther.leafXmjs.filter(item => {                                    return item.qc_qty || item.contract_qty || item.qc_minus_qty                                });                                for (const xmj of leafXmjs) {                                    const notx = findNotJoinLeafXmj(xmj);                                    const notx2 = findNotChangeLeafXmj(xmj);                                    const data = {                                        xmj_id: xmj.id,                                        gcl_id: xmj.gcl_id,                                        mx_id: xmj.mx_id ? xmj.mx_id : '',                                        contract_qty: xmj.contract_qty,                                        qc_qty: xmj.qc_qty,                                        qc_minus_qty: xmj.qc_minus_qty,                                        gather_qty: xmj.gather_qty,                                        is_join: notx !== undefined ? 0 : notx2 !== undefined ? 2 : 1,                                        ms_id: ms.id,                                    };                                    datas.push(data);                                }                            }                        }                    }                }                // 上传到数据库                const select = _.find(materialChecklistData, findObject);                console.log(select, datas, mbList);                if (select) {                    const result = await postDataAsync(window.location.pathname + '/save', {type: 'adds', checklist: { id: select.id, had_bills: 1 }, postData: {xmjs: datas, mbIds: mbList, export: true}});                    // materialListData = result;                    select.had_bills = 1;                    gclList = result;                    stopProgress($('#list-progress'));                    if (i+1 === tree.length) {                        toastr.success('导入成功');                        setTimeout(function () { $('#okedit').modal('hide') }, 2000);                        showSjsData();                    }                    // }, function () {                    //     stop = true;                    //     clearInterval(interval);                    //     setTimeout(function () { $('#okedit').modal('hide') }, 1000);                    // });                } else {                    stopProgress($('#list-progress'));                }            }        }    }    function transExcel(results) {        const mapInfo = {            '清单编号': 'b_code',            '工料编号': 'gljcode',            '名称': 'name',            '单位': 'unit',            '规格': 'specs',            '单价': 'unit_price',            '单位耗量': 'quantity',        };        return results.map(zhObj => {            const enObj = {}            const zhKeys = Object.keys(zhObj);            zhKeys.forEach(zhKey => {                const enKey = mapInfo[zhKey];                enObj[enKey] = zhObj[zhKey] && _.isString(zhObj[zhKey]) ? _.trim(zhObj[zhKey]) : zhObj[zhKey];            });            return enObj        })    }});
 |