// 浙江-象山（从宁海复制）
INTERFACE_EXPORT = (() => {
    'use strict';
  
    /**
     * 
     * @param {String} areaKey - 地区标识，如：'安徽@马鞍山'，有些地区的接口只是取值上有不同，共有一个接口脚本， 需要通过地区标识确定一些特殊处理
     * @param {Number} exportKind - 导出类型，招标、投标、控制价
     * @param {Object} projectData - 项目表数据：{ 建设项目Data, children: [单位工程...] }
     * @param {Object} tenderDetailMap - 单位工程ID与getData接口数据(projectObj.project的结构)的映射。
     * @return {Promise<Array>} - 返回的数据结构必须按照规定：[{ data, exportKind, fileName }]，参考web\building_saas\standard_interface\index.js中的注释说明
     */
    async function entry(areaKey, exportKind, projectData, tenderDetailMap) {
      const {
        CONFIG: {
          TYPE,
          WHITE_SPACE
        },
        UTIL: {
          getValueByKey,
          getHan,
          getFee,
          getUnitFee,
          getNodeByFlag,
          generateHardwareId,
        },
        Element,
      } = INTERFACE_EXPORT_BASE;
  
      const {
        EXPORT_KIND: { BID_INVITATION, BID_SUBMISSION, CONTROL },
        fixedFlag,
        RationType,
      } = window.commonConstants
  
      const GljType = gljUtil.gljType;
  
      const { isEmptyVal, isDef } = window.commonUtil;
  
      const isBidInvitation = exportKind === BID_INVITATION; // 是否是招标
      const isBidSubmission = exportKind === BID_SUBMISSION; // 是否是投标
      const isControl = exportKind === CONTROL; // 是否是控制价
  
      
      const subArea = areaKey.split('@')[1];
      const info = projectData.property && projectData.property.basicInformation || [];
      const { summaryInfo } = projectData;
      const constructionSummary = summaryInfo[projectData.ID];
      let curTender;
  
      // 小数位数（按照需求固定）
      const qD = 4; // 消耗量
      const fD = 2; // 费用
      const pD = 6; // 中间过程
      
      // 值映射表
      const valueMap = {
        '新建': '1',
        '改扩建': '2',
        '养护': '3',
        '养护（年度经费）': '4',
        '养护(年度经费)': '4',
  
        '高速公路': '1',
        '一级公路': '2',
        '二级公路': '3',
        '三级公路': '4',
        '四级公路': '5',
        '桥梁工程': '6',
        '独立桥梁': '6',
        '隧道工程': '7',
        '独立隧道': '7',
        '其他工程': '8',
        '等外工程': '8',
  
        '一般计税': '1',
        '简易计税': '2',
      }
  
      // 是否是材料
      const isMaterial = (type) => {
        return /^2/.test(type);
      }
      
      // 是否是机械
      const isMachine = (type) => {
        return /^3/.test(type);
      }
      
      // 获取预算价
      const getMarketPrice = (glj) => {
        const tenderCoe = gljUtil.getTenderPriceCoe(glj, curTender.property);
        return gljUtil.getMarketPrice(glj, curTender.projectGLJ.datas, curTender.property.calcOptions, curTender.labourCoe.datas, curTender.property.decimal, false, _, scMathUtil, tenderCoe); 
      }
  
      // 获取人工单价
      const getLabourPrice = () => {
        if (isBidInvitation) {
          return 0;
        }
        const glj = curTender.projectGLJ.datas.gljList.find(glj => glj.type === 1);
        if (!glj) {
          return 0;
        }
        return getMarketPrice(glj);
      }
  
      const subTypeKeyArr = ['code', 'name', 'specs', 'unit', 'subType']
  
      function _getSum(orgSum) {
        let rst = orgSum;
        // const isBidInvitation = exportKind === BID_INVITATION; // 是否是招标
        // const isBidSubmission = exportKind === BID_SUBMISSION; // 是否是投标
        // const isControl = exportKind === CONTROL; // 是否是控制价
        //根据导出类型（上面3个），输出实际合计或price
        if (isBidInvitation) {
          rst = 0;
        }
        return rst;
      }

      // 获取人工消耗量
      const getLabourQuantity = (node) => {
        if (isBidInvitation) {
          return 0;
        }
        const quantity = +node.data.quantity || 1;
        let total = 0;
        const posterity = node.getPosterity();
        const rations = posterity.filter(item => calcTools.isRationItem(item));
        rations.forEach(ration => {
          const labours = curTender.ration_glj.datas.filter(glj => glj.rationID === ration.data.ID && glj.type === 1);
          labours.forEach(labour => {
            total = scMathUtil.roundForObj(total + labour.tenderQuantity * ration.data.tenderQuantity, qD);
          });
        });
        const labourRations = posterity.filter(item => (calcTools.isVolumePrice(item) || calcTools.isGljRation(item)) && item.data.subType === 1);
        labourRations.forEach(labour => {
          total = scMathUtil.roundForObj(total + +labour.data.tenderQuantity, qD);
        });
        return total / quantity;
      }
  
      // 获取主材费、辅材费
      const getMaterialFee = (node) => {
        const rst = {
          mainFee: 0,
          assFee: 0,
        };
        if (isBidInvitation) {
          return rst;
        }
        let quantity = calcTools.isBill(node) ? node.data.quantity : node.data.tenderQuantity;
        quantity = +quantity || 1;
        const posterity = calcTools.isBill(node) ? node.getPosterity() : [node];
        // 计算定额下的费用（限定材料）
        const rations = posterity.filter(item => calcTools.isRationItem(item));
        rations.forEach(ration => {
          const rationGljData = curTender.ration_glj.datas.filter(glj => glj.rationID === ration.data.ID && isMaterial(glj.type));
          rationGljData.forEach(rGlj => {
            const key = gljUtil.getIndex(rGlj);
            const projectGlj = curTender.projectGLJ.datas.gljMap[key];
            if (projectGlj) {
              const gljUnitFee = scMathUtil.roundForObj(rGlj.tenderQuantity * getMarketPrice(projectGlj), pD);
              const gljTotalFee = scMathUtil.roundForObj(gljUnitFee * ration.data.tenderQuantity, fD);
              if (projectGlj.is_main_material) {
                rst.mainFee = scMathUtil.roundForObj(rst.mainFee + gljTotalFee, fD);
              } else {
                rst.assFee = scMathUtil.roundForObj( rst.assFee + gljTotalFee, fD);
              }
            }
          });
        });
  
        // 计算工料机类型定额、量价（限定材料）
        const materialRations = posterity.filter(item => calcTools.isGljRation(item) && isMaterial(item.data.subType));
        materialRations.forEach(ration => {
          const key = gljUtil.getIndex(ration.data, subTypeKeyArr);
          const projectGlj = curTender.projectGLJ.datas.gljMap[key];
          if (projectGlj) {
            if (projectGlj.is_main_material) {
              rst.mainFee = scMathUtil.roundForObj(rst.mainFee + getFee(ration.data.fees, 'common.tenderTotalFee'), fD);
            } else {
              rst.assFee = scMathUtil.roundForObj(rst.assFee + getFee(ration.data.fees, 'common.tenderTotalFee'), fD);
            }
          }
        });
  
        const volumes = posterity.filter(item => calcTools.isVolumePrice(item) && isMaterial(item.data.subType));
        volumes.forEach(vol => {
          rst.mainFee = scMathUtil.roundForObj(rst.mainFee + getFee(vol.data.fees, 'common.tenderTotalFee'), fD);
        });
        rst.mainFee = scMathUtil.roundForObj(rst.mainFee / quantity, fD);
        rst.assFee = scMathUtil.roundForObj(rst.assFee / quantity, fD);
        return rst;
      }
      
      // 节点定义--------------------------------
  
      /* 工程信息 */
      function GongCXX() {
        const attrs = [
            { name: '项目编号', value: getValueByKey(info, 'projNum'), minLen: 1 },
            { name: '项目名称', value: projectData.name, minLen: 1 },
            { name: '建设单位', value: getValueByKey(info, 'constructingUnits'), minLen: 1 },
            { name: '起始桩号', value: getValueByKey(info, 'startChainages') },
            { name: '终点桩号', value: getValueByKey(info, 'endChainages') },
            { name: '建设地址', value: getValueByKey(info, 'constructionAddress') },
            { name: '项目概况', value: getValueByKey(info, 'projOverview') },
            { name: '项目类型', value: valueMap[getValueByKey(info, 'natureConstruction')] },
            { name: '专业划分', value: valueMap[getValueByKey(info, 'roadGrade')] },
            { name: '道路里程-公里', value: getValueByKey(info, 'roadDistance') },
            { name: '设计单位', value: getValueByKey(info, 'designUnit') },
            { name: '计税方式', value: valueMap[getValueByKey(info, 'taxMode')] },
            {name: '文件类型', value: isBidInvitation ? 1 : (isControl ? 2 : 3)},    // 1=工程量清单；2=招标控制价；3=投标报价；
            { name: '标准版本号', value: '1.0' },
            { name: 'GUID', value: projectData.GUID }
        ];
        Element.call(this, '工程信息', attrs);
      }
  
      /* 招标信息 */
      function ZhaoBiaoXX() {
        const attrs = [
            { name: '招标人', value: getValueByKey(info, 'tendereeName'), minLen: 1 },
            { name: '招标法定代表人或其授权人', value: getValueByKey(info, 'tenderAuthorizer') },
            { name: '编制人', value: getValueByKey(info, 'compileApprover') },
            { name: '编制人资格证号', value: getValueByKey(info, 'compileCertNo') },
            { name: '编制日期', value: getValueByKey(info, 'compileDate'), type: TYPE.DATE},
            { name: '招标代理机构', value: getValueByKey(info, 'proxy'), minLen: 1},
            { name: '招标范围', value: getValueByKey(info, 'scopeofBidding')},
            { name: '总工期日历天', value: getValueByKey(info, 'timeLimit'), minLen: 1},
        ];
        Element.call(this, '招标信息', attrs);
      }
  
      /* 招标控制价 */
      function ZhaoBiaoKZJ() {
        const attrs = [
            { name: '招标人', value: getValueByKey(info, 'tendereeName'), minLen: 1 },
            { name: '招标法定代表人或其授权人', value: getValueByKey(info, 'tenderAuthorizer') },
            { name: '编制人', value: getValueByKey(info, 'compileApprover') },
            { name: '编制人资格证号', value: getValueByKey(info, 'compileCertNo') },
            { name: '编制日期', value: getValueByKey(info, 'compileDate'), type: TYPE.DATE},
            { name: '编制说明', value: getValueByKey(info, 'preparationDescription') },
            { name: '复核人', value: getValueByKey(info, 'reviewApprover') },
            { name: '复核人资格证号', value: getValueByKey(info, 'reviewCertNo') },
            { name: '复核日期', value: getValueByKey(info, 'reviewDate'), type: TYPE.DATE },
            { name: '审核人', value: getValueByKey(info, 'examineApprover') },
            { name: '审核人资格证号', value: getValueByKey(info, 'examineCertNo') },
            { name: '审核日期', value: getValueByKey(info, 'examineDate'), type: TYPE.DATE },
            { name: '控制价总价', value: constructionSummary.totalCost, type: TYPE.DECIMAL },
            { name: '备注', value: getValueByKey(info, '') },
        ];
        Element.call(this, '招标控制价', attrs);
      }
  
      /* 投标信息 */
      function TouBiaoXX() {
        let hardID = generateHardwareId();
        let [cpuId, diskId, macId] = hardID.split(";");
  
        const attrs = [
            { name: '投标人', value: getValueByKey(info, 'bidderName'), minLen: 1 },
            { name: '投标人法人或其授权人', value: getValueByKey(info, 'bidderAuthorizer') },
            { name: '投标人资质证号', value: getValueByKey(info, 'bidderCertNo') },
            { name: '总工期日历天', value: getValueByKey(info, 'timeLimit')},
            // { name: '投标总价', value: constructionSummary.totalCost, type: TYPE.DECIMAL },
            { name: '投标总价', value: (constructionSummary.totalCost).toFixed(2) }, // 根据需求，固定写死2位小数，所以不设定Decimal，当string来看
            { name: '投标下浮率', value: getValueByKey(info, 'downwardFloatingRateOfBid') },
            { name: '投标报价说明', value: getValueByKey(info, 'descriptionOfTenderOffer') },
            { name: '质量承诺', value: getValueByKey(info, 'qualityCommitment') },
            { name: '投标保证金', value: getValueByKey(info, 'bidBond') },
            { name: '项目经理或项目负责人', value: getValueByKey(info, 'projectManagers') },
            { name: '项目经理或项目负责人资格证号', value: getValueByKey(info, 'projectmanagersCertNo') },
            { name: '造价软件品牌', value: '纵横公路云造价', minLen: 1 },
            { name: '造价软件版本', value: 'Ver' + VERSION, minLen: 1 },
            { name: '造价软件加密锁编号', value: userID, minLen: 1 },
            { name: '计算机硬件信息', value: cpuId + diskId + macId, minLen: 1 },
            { name: '备注', value: getValueByKey(info, '') },
        ];
        Element.call(this, '投标信息', attrs);
      }
      
      /* 工程量清单明细 */
      let billSeq = 1;
      // 获取数据类型
      function getBillDataType(node) {
        // 目录
        if (!calcTools.isLeafBill(node)) {
          return '1';
        }
        // 备注：增加判断，有些目录下无子项，原则上属于叶子，但应该还是要设置成目录
        if ( (node.data.name.indexOf('第') >= 0) && (node.data.name.indexOf('00章') >= 0) ) {
          return '1';
        }
        // 专项暂定
        if (node.data.specialProvisional == '专业工程') {
          return '21';
        }
        // 安全生产费
        const safeCode = projectObj.getSaveProductionCostCode();
        if (node.data.code == safeCode) {
          return '22'
        }
        // 工程一切险
        if ((node.data.code == '-a') && (node.parent && (node.parent.data.code == '101-1'))) {
          return '23'
        }
        // 第三者责任险
        if ((node.data.code == '-b') && (node.parent && (node.parent.data.code == '101-1'))) {
          return '24'
        }
        return '20';
      }
  
      // 获取清单章节
      const getBillSection = (node) => {
        const parentFlag = node.parent ? node.parent.getFlag() : null;
        if (parentFlag !== fixedFlag.ONE_SEVEN_BILLS) {
          let cur = node;
          while (cur) {
            if (cur.data.sectionCode) {
              return cur.data.sectionCode;
            }
            cur = cur.parent;
          }
          return (cur.data.name || '').replace(/[^0-9]/g, '');
        } else {
          const sectionCode = (node.data.name || '').replace(/[^0-9]/g, '');
          node.data.sectionCode = sectionCode;
          return sectionCode
        }
      }
  
      // 获取子目号
      const getBillCode = (node) => {
        if (node.data.code) {
          return node.data.code;
        }
        const parentFlag = node.parent ? node.parent.getFlag() : null;
        if (parentFlag === fixedFlag.ONE_SEVEN_BILLS) {
          return getBillSection(node);
        }
        return node.data.code;
      }
      function GongCLQDMX(node) {
        const { mainFee, assFee } = getMaterialFee(node);
        const billDataType = getBillDataType(node);
        let unitFee = 0;
        let totalFee = 0;
        if (!isBidInvitation || billDataType === '21') {
          unitFee = getFee(node.data.fees, 'common.tenderUnitFee');
          totalFee = getFee(node.data.fees, 'common.tenderTotalFee');
        }
        const attrs = [
          {name: '序号', value: billSeq ++ },
          {name: 'GUID', value: node.data.GUID || node.data.ID },
          {name: '清单章节', value: getBillSection(node), minLen: 1, enumeration: [
            '100', '200', '300', '400', '500', '600', '700', '800', '900', '1000', '1100', 
            '1200', '1300', '1400', '1500', '1600', '1700', '1800', '1900', '2000', 
          ]},
          {name: '子目长编号', value: divideObj.getExeBillCode(node.data.ID, node. tree)},
          {name: '子目号', value: getBillCode(node), minLen: 1},
          {name: '子目名称', value: node.data.name, minLen: 1},
          {name: '单位', value: node.data.unit},
          {name: '数量', value: node.data.quantity, type: TYPE.DECIMAL},
          {name: '单价', value: unitFee, type: TYPE.DECIMAL},
          {name: '合价', value: totalFee, type: TYPE.DECIMAL},
          {name: '备注', value: node.data.remark },
          {name: '数据类型', value: billDataType },
          {name: '人工费', value: getUnitFee(getFee(node.data.fees, 'marketLabour.tenderTotalFee', exportKind), node.data.quantity, 2), type: TYPE.DECIMAL},
          {name: '人工单价', value: getLabourPrice(), type: TYPE.DECIMAL},
          {name: '人工消耗量', value: getLabourQuantity(node), type: TYPE.DECIMAL},
          {name: '主材费', value: mainFee, type: TYPE.DECIMAL},
          {name: '辅材费', value: assFee, type: TYPE.DECIMAL},
          {name: '设备费', value: getUnitFee(getFee(node.data.fees, 'equipment.tenderTotalFee', exportKind), node.data.quantity, fD), type: TYPE.DECIMAL},
          {name: '机械使用费', value:  getUnitFee(getFee(node.data.fees, 'machine.tenderTotalFee', exportKind), node.data.quantity, fD), type: TYPE.DECIMAL},
          {name: '措施费1', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'measure1.tenderTotalFee', exportKind) : getFee(node.data.fees, 'otherDirect.tenderTotalFee', exportKind), node.data.quantity, fD), type: TYPE.DECIMAL},
          {name: '措施费2', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'measure2.tenderTotalFee', exportKind) : getFee(node.data.fees, 'composite.tenderTotalFee', exportKind), node.data.quantity, fD), type: TYPE.DECIMAL},
          {name: '企业管理费', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'manage.tenderTotalFee', exportKind) : getFee(node.data.fees, 'local.tenderTotalFee', exportKind), node.data.quantity, fD), type: TYPE.DECIMAL},
          {name: '规费', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'force.tenderTotalFee', exportKind) : getFee(node.data.fees, 'indirect.tenderTotalFee', exportKind), node.data.quantity, fD), type: TYPE.DECIMAL},
          {name: '利润', value: getUnitFee(getFee(node.data.fees, 'profit.tenderTotalFee', exportKind), node.data.quantity, fD), type: TYPE.DECIMAL},
          {name: '税金', value: getUnitFee(getFee(node.data.fees, 'tax.tenderTotalFee', exportKind), node.data.quantity, fD), type: TYPE.DECIMAL},
          {name: '评审清单', value: isNaN(+node.data.appraisalBills) ? 0 : +node.data.appraisalBills},
        ];
        Element.call(this, '工程量清单明细', attrs);
      }
  
      /* 清单主材表明细 */
      let mainMaterialSeq = 1;
      function QDZCBMX(material) {
        const attrs = [
          { name: '序号', value: mainMaterialSeq++, minLen: 1 },
          { name: '材料编码', value: material.code, minLen: 1 },
          { name: '主材名称', value: material.name, minLen: 1 },
          { name: '单位', value: material.unit, minLen: 1 },
          { name: '主材消耗量', value: material.quantity, type: TYPE.DECIMAL },
          { name: '单价', value: material.unitPrice, type: TYPE.DECIMAL },
          { name: '合价', value: material.totalPrice , type: TYPE.DECIMAL},
          { name: '备注', value: material.remark },
        ];
        Element.call(this, '清单主材明细', attrs);
      }
  
      /* 定额信息表 */
      let rationSeq = 1;
      // 获取数据类型
      const getRationDataType = (node) => {
        const programText = curTender.calcProgram.compiledTemplateMaps[node.data.programID];
        return programText === '费率为0' ? '4' : '3';
      }

      function billDEXXB(node) {
        // 叶子清单生成定额信息表用
        const { mainFee, assFee } = getMaterialFee(node);
        const attrs = [
          {name: '序号', value: '' },
          {name: 'GUID', value: node.data.GUID},
          {name: '定额编号', value: ''},
          {name: '定额名称', value: node.data.name, minLen: 1 },
          {name: '单位', value: node.data.unit, minLen: 1 },
          // {name: '数量', value: node.data.tenderQuantity, type: TYPE.DECIMAL},
          {name: '数量', value: (node.data.tenderQuantity)?node.data.tenderQuantity:node.data.quantity, type: TYPE.DECIMAL},
          {name: '单价', value: getFee(node.data.fees, 'common.tenderUnitFee', exportKind), type: TYPE.DECIMAL},
          {name: '合价', value: getFee(node.data.fees, 'common.tenderTotalFee', exportKind), type: TYPE.DECIMAL},
          {name: '备注', value: node.data.remark },
          {name: '数据类型', value: (node.data.specialProvisional === '材料暂估') ? '1' : '2' },
          {name: '人工费', value: getUnitFee(getFee(node.data.fees, 'marketLabour.tenderTotalFee', exportKind), node.data.tenderQuantity, 2), type: TYPE.DECIMAL},
          {name: '主材费', value: mainFee, type: TYPE.DECIMAL},
          {name: '辅材费', value: assFee, type: TYPE.DECIMAL},
          {name: '设备费', value: getUnitFee(getFee(node.data.fees, 'equipment.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '机械使用费', value:  getUnitFee(getFee(node.data.fees, 'machine.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '措施费1', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'measure1.tenderTotalFee', exportKind) : getFee(node.data.fees, 'otherDirect.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '措施费2', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'measure2.tenderTotalFee', exportKind) : getFee(node.data.fees, 'composite.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '企业管理费', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'manage.tenderTotalFee', exportKind) : getFee(node.data.fees, 'local.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '规费', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'force.tenderTotalFee', exportKind) : getFee(node.data.fees, 'indirect.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '利润', value: getUnitFee(getFee(node.data.fees, 'profit.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '税金', value: getUnitFee(getFee(node.data.fees, 'tax.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
        ];
        Element.call(this, '定额信息表', attrs);
      }

      function DEXXB(node) {
        // if (node.data.code == '1-2-14-1') debugger;
        const { mainFee, assFee } = getMaterialFee(node);
        const attrs = [
          {name: '序号', value: rationSeq ++ },
          {name: 'GUID', value: node.data.GUID || node.data.ID },
          {name: '定额编号', value: node.data.code},
          {name: '定额名称', value: node.data.name, minLen: 1 },
          {name: '单位', value: node.data.unit, minLen: 1 },
          // {name: '数量', value: node.data.tenderQuantity, type: TYPE.DECIMAL},
          {name: '数量', value: (node.data.tenderQuantity)?node.data.tenderQuantity:node.data.quantity, type: TYPE.DECIMAL},
          {name: '单价', value: getFee(node.data.fees, 'common.tenderUnitFee', exportKind), type: TYPE.DECIMAL},
          {name: '合价', value: getFee(node.data.fees, 'common.tenderTotalFee', exportKind), type: TYPE.DECIMAL},
          {name: '备注', value: node.data.remark },
          {name: '数据类型', value: getRationDataType(node) },
          {name: '人工费', value: getUnitFee(getFee(node.data.fees, 'marketLabour.tenderTotalFee', exportKind), node.data.tenderQuantity, 2), type: TYPE.DECIMAL},
          {name: '主材费', value: mainFee, type: TYPE.DECIMAL},
          {name: '辅材费', value: assFee, type: TYPE.DECIMAL},
          {name: '设备费', value: getUnitFee(getFee(node.data.fees, 'equipment.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '机械使用费', value:  getUnitFee(getFee(node.data.fees, 'machine.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '措施费1', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'measure1.tenderTotalFee', exportKind) : getFee(node.data.fees, 'otherDirect.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '措施费2', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'measure2.tenderTotalFee', exportKind) : getFee(node.data.fees, 'composite.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '企业管理费', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'manage.tenderTotalFee', exportKind) : getFee(node.data.fees, 'local.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '规费', value: getUnitFee(COMPILATION_NAME.includes('公路造价') ? getFee(node.data.fees, 'force.tenderTotalFee', exportKind) : getFee(node.data.fees, 'indirect.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '利润', value: getUnitFee(getFee(node.data.fees, 'profit.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
          {name: '税金', value: getUnitFee(getFee(node.data.fees, 'tax.tenderTotalFee', exportKind), node.data.tenderQuantity, fD), type: TYPE.DECIMAL},
        ];
        Element.call(this, '定额信息表', attrs);
      }
  
      /* 造价汇总明细 */
      let hzSeq = 1;
      // 获取章次
      const getSection = (node) => {
        const parentFlag = node.parent ? node.parent.getFlag() : null;
        if (parentFlag !== fixedFlag.ONE_SEVEN_BILLS) {
          return '';
        }
        return (node.data.name || '').replace(/[^0-9]/g, '')
      }
      let curLB = 7;
      // 获取类别
      const getLB = (node) => {
        const flag = node.getFlag();
        const parentFlag = node.parent ? node.parent.getFlag() : null;
        if (parentFlag === fixedFlag.ONE_SEVEN_BILLS) {
          return getSection(node);
        }
        switch (flag) {
          case fixedFlag.ONE_SEVEN_BILLS:
            return '1';
          case fixedFlag.PROVISIONAL_TOTAL:
            return '2';
          case fixedFlag.BILLS_TOTAL_WT_PROV:
            return '3';
          case fixedFlag.DAYWORK_LABOR:
            return '4';
          case fixedFlag.PROVISIONAL:
            return '5';
          case fixedFlag.TOTAL_COST:
            return '6';
          default:
            return curLB++;
        }
  
      }
      function ZJHZMX(node) {
        const attrs = [
          {name: '序号', value: hzSeq++ },
          {name: '章次', value: getSection(node) },
          {name: '名称', value: node.data.name, minLen: 1 },
          {name: '金额', value: _getSum(getFee(node.data.fees, 'common.tenderTotalFee')), type: TYPE.DECIMAL },
          {name: '类别', value: getLB(node) },
          {name: '备注', value: node.data.remark },
  
        ];
        Element.call(this, '造价汇总明细', attrs);
      }
      
      /* 人材机汇总明细表 */
      // 获取人材机类别
      const getGljLB = (glj) => {
        if (glj.type === 1) {
          return '1';
        }
        if (!glj.is_main_material && isMaterial(glj.type) && ![202, 203, 204 ].includes(glj.type)) {
          return '2';
        }
        if (isMachine(glj.type) && glj.type !== 301) {
          return '3';
        }
        if (glj.type === 5) {
          return '4';
        }
        if ([202, 203, 204].includes(glj.type)) {
          return '5';
        }
        if (glj.type === 301) {
          return '6';
        }
        if (glj.is_main_material && isMaterial(glj.type) && ![202, 203, 204 ].includes(glj.type)) {
          return '7';
        }
        return '2';
      }
      function RCJHZMXB(glj) {
        const attrs = [
          {name: '人材机编号', value: glj.code, minLen: 1  },
          {name: '人材机名称', value: glj.name, minLen: 1 },
          {name: '规格型号', value: glj.specs },
          {name: '单位', value: glj.unit, minLen: 1 },
          {name: '数量', value: glj.tenderQuantity },
          {name: '单价', value: glj.priceInfo.tenderPrice, type: TYPE.DECIMAL },
          {name: '人材机类别', value: getGljLB(glj) },
          {name: '是否主要材料', value: +glj.is_main_material },
          {name: '是否甲供', value: 0 },
          {name: '备注', value: glj.remark },
    
        ];
        Element.call(this, '人材机汇总明细表', attrs);
        
      }
  
      // 组装数据 ------------------------------------------------------------
  
      /* 生成清单主材表 */
      function createQDZCB(node) {
        const qdzcb = new Element('清单主材表');
  
        // 获取主材
        const mainMaterials = [];
        const materialMap = {};
        node.children.forEach(ration => {
          const materials = curTender.ration_glj.datas.filter(glj => glj.rationID === ration.data.ID && isMaterial(glj.type));
          materials.forEach(material => {
            const key = gljUtil.getIndex(material);
            const projectGlj = curTender.projectGLJ.datas.gljMap[key];
            if (projectGlj && projectGlj.is_main_material) {
              if (!materialMap[key]) {
                materialMap[key] = {
                  code: projectGlj.code,
                  name: projectGlj.name,
                  unit: projectGlj.unit,
                  quantity: +material.tenderQuantity,
                  unitPrice: getMarketPrice(projectGlj),
                  totalPrice: 0,
                  remark: projectGlj.remark,
                };
                mainMaterials.push(materialMap[key]);
              } else {
                materialMap[key].quantity = scMathUtil.roundForObj(materialMap[key].quantity + +material.tenderQuantity, qD);
              }
            }
          });
        });
        mainMaterials.forEach(material => {
          material.totalPrice = scMathUtil.roundForObj(material.quantity * material.unitPrice, fD);
          qdzcb.children.push(new QDZCBMX(material));
        });
        return qdzcb.children.length ? qdzcb : null;
      }

      /* 生成定额信息表 */
      function createDEXXB(node) {
        const rst = [];
        if(isBidInvitation) return rst; //招标工程量清单不导出定额数据
        node.children.forEach(ration => {
          const dexxb = new DEXXB(ration);
          rst.push(dexxb);
  
          // 生成定额人材机含量明细
          const rGljData = curTender.ration_glj.datas.filter(glj => glj.rationID === ration.data.ID);
          rGljData.forEach(rGlj => {
            const projectGlj = curTender.projectGLJ.datas.gljMap[gljUtil.getIndex(rGlj)];
            if (!projectGlj) {
              return;
            }
            const attrs = [
              { name: '人材机编号', value: projectGlj.code },
              { name: '人材机含量', value: rGlj.tenderQuantity, type: TYPE.DECIMAL },
            ]
            const dercjhlmx = new Element('定额人材机含量明细', attrs);
            dexxb.children.push(dercjhlmx);
          })
        });
        return rst;
      }
  
      /* 生成工程量清单表 */
      function createGCLQD() {
        function _checkIfNeedTransfer(node) {
          let rst = false;
          if (node.data.specialProvisional !== undefined && node.data.specialProvisional !== null && node.data.specialProvisional !== '' && node.children.length === 0) {
            rst = (node.data.specialProvisional === '材料暂估' && node.data.specialProvisional === '工程设备');
          }
          return rst;
        }
          // 设置工程量清单明细
        function setupGCLQDMX(nodes) {
          const rst = [];
          nodes.forEach(node => {
            // if (node.data.name === '利用石方') debugger;
            if (_checkIfNeedTransfer(node)) {
              //象山的坑，叶子清单(专项暂定)要转成定额信息表
              const dexxb = new billDEXXB(node);
              rst.push(dexxb);              
            } else {
              // 原逻辑：
              const glcqdmx = new GongCLQDMX(node);
              rst.push(glcqdmx);
              if (!node.source.children.length && node.children.length) {
                // 清单主材表
                const qdzcb = createQDZCB(node);
                if (qdzcb) {
                  glcqdmx.children.push(qdzcb);
                }
                // 定额
                glcqdmx.children.push(...createDEXXB(node));
              } else {
                // 子清单
                glcqdmx.children.push(...setupGCLQDMX(node.children));
              }
            }
          });
          return rst;
        }
  
        const gclqd = new Element('工程量清单表');
        // 工程量清单明细为固定清单（第100章至700章清单）下所有清单
        const fixedNode = getNodeByFlag(curTender.mainTree, fixedFlag.ONE_SEVEN_BILLS)
        gclqd.children.push(...setupGCLQDMX(fixedNode.children));
  
  
        return gclqd;
      }
  
      /* 生成计日工信息表 */
      let jrgSeq = 1;
      // 获取数据类型
      const getJRGDataType = (node) => {
        const flag = node.getFlag();
        const parentFlag = node.parent ? node.parent.getFlag() : null;
        if (flag === fixedFlag.DAYWORK_LABOR) {
          return '0';
        }
        if (flag === fixedFlag.LABOUR_SERVICE) {
          return '1';
        }
        if (flag === fixedFlag.MATERIAL) {
          return '2';
        }
        if (flag === fixedFlag.CONSTRUCTION_MACHINE) {
          return '3';
        }
        if (parentFlag === fixedFlag.LABOUR_SERVICE) {
          return '4';
        }
        if (parentFlag === fixedFlag.MATERIAL) {
          return '5';
        }
        if (parentFlag === fixedFlag.CONSTRUCTION_MACHINE) {
          return '6';
        }
      }
      function createJRGXXB() {
        const jrgxxb = new Element('计日工信息表');
        const fixedNode = getNodeByFlag(curTender.mainTree, fixedFlag.DAYWORK_LABOR);
        function createJRG(node) {
          // 计日工信息标题
          const jrgxxbt = new Element('计日工信息标题', [
            { name: '序号', value: jrgSeq++ },
            { name: '名称', value: node.data.name },
            { name: '数据类型', value: getJRGDataType(node) },
            { name: '合价', value: _getSum(getFee(node.data.fees, 'common.tenderTotalFee')), type: TYPE.DECIMAL},
          ]);
          if (node === fixedNode) {
            return jrgxxbt;
          }
          jrgxxbt.children = node.children.map(child => new Element('计日工信息明细', [
              { name: '编号', value: child.data.code, minLen: 1 },
              { name: '名称', value: child.data.name, minLen: 1 },
              { name: '数据类型', value: getJRGDataType(child) },
              { name: '单位', value: child.data.unit, minLen: 1 },
              { name: '暂定数量', value: child.data.quantity, type: TYPE.DECIMAL },
              { name: '单价', value: _getSum(getFee(child.data.fees, 'common.tenderUnitFee')), type: TYPE.DECIMAL },
              { name: '合价', value: _getSum(getFee(child.data.fees, 'common.tenderTotalFee')), type: TYPE.DECIMAL },
            ]));
          return jrgxxbt;
        }
        jrgxxb.children = [fixedNode, ...fixedNode.children].map(node => createJRG(node));
        return jrgxxb;
      }
  
      /* 生成造价汇总表 */
      function createZJHZB() {
        const zjhzb = new Element('造价汇总表');
        // 提取需要显示的数据
        const nodes = [];
        curTender.mainTree.roots.forEach(node => {
          nodes.push(node);
          if (node.getFlag() === fixedFlag.ONE_SEVEN_BILLS) {
            nodes.push(...node.children);
          }
        });
        zjhzb.children = nodes.map(node => new ZJHZMX(node));
        return zjhzb;
      }
  
      /* 生成人材机汇总 */
      function createRCJHZ() {
        const rcjhz = new Element('人材机汇总');
        rcjhz.children = curTender.projectGLJ.datas.gljList.map(glj => new RCJHZMXB(glj));
        return rcjhz;
      }
  
      /* 生成标段工程 */
      function createGLBDGC(rawTender, seq){
        // 标段属性
        const tenderAttrs = [
            { name: '序号', value: seq, minLen: 1 },
            { name: '标段名称', value: rawTender.name, minLen: 1 },
            { name: '金额', value: isBidInvitation ? 0 : projectData.summaryInfo[rawTender.ID].totalCost },
            { name: '唯一标识-Guid', value: rawTender.GUID }
        ];
        const gongLBDGC = new Element('公路标段工程', tenderAttrs)
        // 工程量清单表
        const gclqd = createGCLQD();
        // 计日工信息表
        const jrgxxb = createJRGXXB();
        // 造价汇总表
        const zjhzb = createZJHZB();
        // 人材机汇总
        const rcjhz = createRCJHZ();
        gongLBDGC.children = [gclqd, jrgxxb, zjhzb, rcjhz];
  
  
        // 公路工程汇总明细属性
        const hzAttrs = [
          ...tenderAttrs,
          { name: '备注', value: '' }
        ];
  
        return {
          gongLBDGC,
          hzAttrs,
        }
      }
  
      /* 组装建设项目数据 */
      function setupConstruction() {
        const rootNode = new Element('浙江公路工程');
        const gongCXX = new GongCXX();
        const zhaoTBXX = new Element('招投标信息');
        const gongLGCSJ = new Element('公路工程数据');
        rootNode.children = [gongCXX, zhaoTBXX, gongLGCSJ];
  
        if (isBidInvitation) {
          zhaoTBXX.children.push(new ZhaoBiaoXX());
        } else if (isControl) {
          zhaoTBXX.children.push(new ZhaoBiaoKZJ());
        } else {
          zhaoTBXX.children.push(new TouBiaoXX());
        }
  
        const gongLGCHZ = new Element('公路工程汇总');
        const gongLGCHZBT = new Element('公路工程汇总标题');
        gongLGCHZ.children.push(gongLGCHZBT);
  
        // 组装标段数据
        projectData.children.forEach((tender, index) => {
          billSeq = 1;
          mainMaterialSeq = 1;
          rationSeq = 1;
          jrgSeq = 1;
          hzSeq = 1;
          curTender = tenderDetailMap[tender.ID];
          const {
            gongLBDGC,
            hzAttrs,
          } = createGLBDGC(tender, index + 1);
          gongLGCSJ.children.push(gongLBDGC);
          const gongLGCHZMX = new Element('公路工程汇总明细', hzAttrs);
          gongLGCHZBT.children.push(gongLGCHZMX);
        });
        gongLGCSJ.children.push(gongLGCHZ);
  
  
        const suffix = INTERFACE_CONFIG[areaKey]['fileSuffix'][exportKind];
        return [{
          data: rootNode,
          exportKind,
          fileName: `${projectData.name}${suffix}`
      }];
      }
  
      return setupConstruction(projectData);
    
    }
  
    return {
      entry,
    };
  })();
  