## 拦截复写列表顶部按钮接：

## 1、列表

```typescript
import { request } from '@weapp/utils'; // 拦截eb列表按钮接口请求后

// 拦截eb列表按钮接口请求后
axios.interceptors.response.use(
  function (response) {
    if (
      response.status === 200 &&
      response.config.url.includes('/api/ebuilder/form/list/getListButtons/')
    ) {
      console.log('拦截eb列表按钮接口请求后：', response);
      // 获取表格视图id
      const listId = response.config.url.split('/getListButtons/')?.[1]?.split('?')?.[0];
      console.log('listId', listId);
      return new Promise(function (resolve, reject) {
        request({
          url: 'XXXX', // 请求自定义接口
          method: 'get',
          params: { listId: listId },
          headers: { ebBusinessId: listId },
        }).then((res) => {
          console.log('==11=', res);
          // demo  过滤按钮id不等于932056135746060297 的
          let _btns = response.data.data.buttons.filter((b) => b.id !== '932056135746060297');
          _btns = _btns.map((b) => {
            console.log(b);
            if (b.id === '923125700635418651') {
              return { ...b, name: '自定义名称' }; //复写按钮名称
            }
            return b;
          });
          resolve({
            ...response,
            data: {
              ...response.data,
              data: {
                ...response.data.data,
                buttons: _btns, // 返回复写后的按钮数据
              },
            },
          });
        });
      });
    } else {
      return response;
    }
  },
  function (error) {
    return Promise.reject(error);
  },
);
```

[图片附件未整合: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB0sAAALACAYAAADynZpbAAAgAElEQVR4Aey9CbhcVZnv7fN995vv7f6wJ+1W4wgOAQQHYut...]

## 2、布局

```typescript
axios.interceptors.response.use(
    function (response) {
        // 响应状态码为 2xx 时触发成功的回调，形参中的 response 是“成功的结果”
        let buttonData = {};
        if (
            response.status === 200 &&
            response.config.url.includes('/api/ebuilder/form/data/getFormButtons') 
        ) {
            let formId = window.ebdFormSdk && window.ebdFormSdk.getObjId();
            let dataId = window.sessionStorage.getItem('governTaskDataId');
            if (!formId || !dataId) return response;
            // 无按钮
            var oldButtonMap = new Map();
            let newButtonArray = new Array();
            response?.data?.data?.forEach((item,index) => {
                oldButtonMap.set(item.id,item);
            });
            return new Promise(function (resolve, reject) {
                weappUtils.request({
                        url: `XXX`,//自定义接口
                        method: 'post',
                }).then((res) => {
                    if (res.status && Object.keys(res.data).length > 0) {
                        res.buttonIdSet = res.data?.buttonIdSet.map((item) => {
                            if(oldButtonMap.has(item) > 0) {
                                oldButtonMap.delete(item);
                            }
                        });
                    
                        for(let item of oldButtonMap.entries()){
                            newButtonArray.push(item[1]);
                        }
                        response.data.data = newButtonArray;
                        console.log(response);
                        resolve({
                            ...response,
                        });
                    } else {
                        resolve({
                            ...response,
                        });
                    }
                });
            });
            // return response;
        }else {
            return response;
        }
    },
    function (error) {
        // console.log(error)
        // 响应状态码不是 2xx 时触发失败的回调，形参中的 error 是“失败的结果”

        return Promise.reject(error);
    },
);
```

## 案例

### 1、拦截指定的请求url复写

```typescript
//拦截设计器组件请求接口，改下参数
axios.interceptors.request.use(function (config) {
  if(config.url.indexOf("/api/ebuilder/coms/component/list") >-1 
    && window.location.pathname.indexOf('/sp/workflow/formdesigner')>-1 
    && config.params.module  === "EBUILDERFORM"){
    console.log("卡片挂载",config)
    config.params.module = "EBUILDERCARD";
  }
  
  return config
}, function (error) {
  return Promise.reject(error);
});
```

### 2、拦截列表获取默认值接口，更新值

```typescript
// 拦截接口请求后
axios.interceptors.response.use(function (response) {
  if (response.status === 200 && response.config.url.includes('/api/ebuilder/form/listFilter/getFilterDefault')) {
    console.log('拦截eb列表按钮接口请求后：', response,response.config.data);
   
     const tempdata = response.config.data ? JSON.parse(response.config.data):{}
     console.log("tempdata",tempdata)
     if(tempdata.id === "947652635398012929"){
      response.data.data = {
        ...response.data.data,
        searchParamData:{
          ...response.data.data.searchParamData,
          groupFields:{
            ...response.data.data.searchParamData.groupFields,
            field_943875795724861442:['943875817134186501']
          }
        }
      };
       return response
     }
       return response;
  }else {
    return response;
  }
}, function (error) {
  return Promise.reject(error);
});
```

### 3、拦截分组列表请求接口，添加参数

```typescript
/**
* 支持分组列表中关联eb字段分组排序
*/
//拦截请求接口，改下参数
axios.interceptors.request.use(function (config) {
  //947648104171053057  表格视图id，用来判断接口
  if(config.url.indexOf("/api/ebuilder/form/list/getListDatas") >-1&& config.data.listId==="947648104171053057"){
    console.log("卡片挂载",config,config.data);
    //sz_2bk0wu  为关联eb对应表单的字datakey       orderType:asc |  desc | ""
    config.data.groupSortParams = [{orderKey: "sz_2bk0wu", orderType: "asc"}];
  }
  
  return config
}, function (error) {
  return Promise.reject(error);
});
```

### 4、拦截搜索接口，处理接口返回数据

```javascript
/**
* 场景：拦截列表id是1008782724358430720的搜索showFilters接口，屏蔽【创建者】和【最后更新时间】字段
*/
axios.interceptors.response.use(function (response) {
  // 1.拦截列表id是1008782724358430720的showFilters接口
  if (response.status === 200 && response.config.url.includes('api/ebuilder/form/listFilter/showFilters/1008782724358430720')) {
    
    // 2.屏蔽【创建者】和【最后更新时间】字段
    const hideFields = ["creator","update_time"];
    response.data.data = (response.data.data||[]).filter((item)=>!hideFields.includes(item.fieldName));
    console.log('拦截eb列表按钮接口请求后,其他条件中屏蔽创建者和最后更新时间：',response.data.data);

    return response;
  }else {
    return response;
  }
}, function (error) {
  return Promise.reject(error);
});
```

[图片附件未整合: ../../../../_assets/933185733679644672/002-8646e5cddd.png]

### 5、拦截初始化接口，设置拦截第一次获取数据，点击搜索后才进行获取数据

说明：拦截参数为interceptInitGetData，true则拦截第一次请求。

支持基线：weapp-ebdfpage-1.20.0      20240701基线

```javascript
// 拦截接口请求后
axios.interceptors.response.use(function (response) {
  // 拦截列表listId是1017302084124762154的listInit接口
  // 默认拦截第一次请求
  if (
    response.status === 200 
    && response.config.url.includes('api/ebuilder/form/list/listInit')
    && JSON.parse(response.config.data)?.listId === '1017302084124762154'
  ) {
    response.data.data.listBaseInfo = {
      ...response.data.data.listBaseInfo,
      interceptInitGetData:true
    }
    return response;
  }else {
    return response;
  }
}, function (error) {
  return Promise.reject(error);
});
```

### [图片附件未整合: ../../../../_assets/933185733679644672/003-33fcc55ffc.png]

6、虚拟表单统计里面的过滤条件放开sql条件—临时不建议使用

> 有需求联系栾俊超

```javascript
// 拦截接口请求后
axios.interceptors.response.use(function (response) {
  if (response.status === 200 && response.config.url.includes('/api/ebuilder/form/obj/getInfo/928613856982884353')) {
    response.data.data.isPhysical=true;
   
          return response;
     }
       return response;
  
}, function (error) {
  return Promise.reject(error);
});
```

### 7、表格视图明细表列中多行文本支持标签解析复写

```
// 拦截接口请求后
/****
*1127967409682161665   ：表格视图id
*/
axios.interceptors.response.use(function (response) {
  if (
    response.status === 200 
    && response.config.url.includes('/api/ebuilder/form/list/getListDatas')
    && JSON.parse(response.config.data)?.listId === '1127967409682161665'
  ) {
      console.log("response",response);
      let tempColumns = response.data.data.columns ||[];
    tempColumns = tempColumns.map(col=>{
      if(col.detailColumn && col.children && col.children.length){
        return {...col,children:col.children.map(childCol=>{
          if(childCol.dataIndex==="XXX字段的dataindex"){
            return {...childCol,fieldConfig:{supportHtml:true}}
          }
          return childCol
        })}
      }
      return col
    });
    response.data.data.columns  = tempColumns;
    return response;
  }else {
    return response;
  }
}, function (error) {
  return Promise.reject(error);
});
```

### 8、表单隐藏申请按钮

```
axios.interceptors.response.use(function (response) {
  if (response.status === 200 && response.config.url.includes('/api/ebuilder/form/data/getDetail')) {
     const tempdata = response.config.data ? JSON.parse(response.config.data):{}
     if(tempdata.objId === "1120527963720417281"){
      response.data.data = {
        ...response.data.data,
        applyUser:''
      };
       return response
     }
       return response;
  }else {
    return response;
  }
}, function (error) {
  return Promise.reject(error);
});
```

### 9、复写页面列表数据中附件鉴权参数

```
const JSONSafeParse = (_value, defaultValue) => {
  let parsedData;
  const value = _value;
  try {
    if (typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) {
      parsedData = JSON.parse(value);
    } else {
      parsedData = value;
    }
  } catch (error) {
    parsedData = defaultValue || value; // 其他默认值或数据本身
  }
  return parsedData;
};

// 拦截接口请求后
axios.interceptors.response.use(function (response) {
  if (response.status === 200 && response.config.url.includes('/api/ebuilder/coms/nlist/getData')
 ) {
   const { config ,data} = response;
   const pageId =  config.data.get("pageId");
   /**
    * 1、页面id ： 需要修改
    */
     if(pageId=== "1178070668565512192"){
       const tempListdata = data.data.list ||[];
    //  console.log("tempdata",tempListdata)
       /**
        * 2、附件字段id ： 需要修改
        */
        const targetFieldId = '10198553679217827847371450108967129090';
     response.data.data.list =  tempListdata.map(d=>{
      
       let fjDatas =d[targetFieldId] || [];

       fjDatas = fjDatas.map(fd=>{
         console.log("fd",fd)
        let fjSrc = JSONSafeParse(fd.src,{});
          console.log("fjSrc",fjSrc)
            const customParamSuffix = weappUtils.qs.stringify({
               /**
                * 3、目标表单id ： 需要修改， data里面会返回
                */
            customParam: JSON.stringify({ dataId:d["id"] , objId:"1178067997000523776"  }),
          });
        const _src = fjSrc.src.replace("&module=datasource",'')
        fjSrc ={...fjSrc,src: `${_src}&module=ebuilderform&authModule=ebuilderform&appId=1&${customParamSuffix}`};
         return {...fd,src:JSON.stringify(fjSrc)}
       })
       return {...d,[targetFieldId]:fjDatas}
     });

       return response
     }
       return response;
  }else {
    return response;
  }
}, function (error) {
  return Promise.reject(error);
});
```

//页面中多个列表

```
const JSONSafeParse = (_value, defaultValue) => {
  let parsedData;
  const value = _value;
  try {
    if (typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) {
      parsedData = JSON.parse(value);
    } else {
      parsedData = value;
    }
  } catch (error) {
    parsedData = defaultValue || value; // 其他默认值或数据本身
  }
  return parsedData;
};

// 拦截接口请求后
axios.interceptors.response.use(function (response) {
  if (response.status === 200 && response.config.url.includes('/api/ebuilder/coms/nlist/getData')
 ) {
   const { config ,data} = response;
   const pageId =  config.data.get("pageId");
   const compId =  config.data.get("compId");
   /**
    * 1、页面id ： 需要修改
    */
     if(pageId=== "1175853086712750081"){
       const tempListdata = data.data.list ||[];
    //  console.log("tempdata",tempListdata)
       /**
        * 2、附件字段id ： 需要修改
        * 3、目标表单id ： 需要修改， data里面会返回
        */
  
         const listMap ={
          //组件id
          'a0f5e43fca7a40259cd4ead9798b36b7':{
        //附件字段id
            targetFieldId: '10176885738582548482175705842138508171',
            //视图目标objid字段
            objId:"10176885738582548482175749379938846174"
          },
          "a4ca31f46a234e4794c40acd2cb94d40":{
            targetFieldId: '10177034028955443202175705844585908172',
            objId:"",
            //目标表单id
            orgObjId:"1172889069677404160"
          }
        }
     response.data.data.list =  tempListdata.map(d=>{
       const _targetFieldId = listMap[compId]["targetFieldId"];
       let fjDatas =d[_targetFieldId] || [];

       fjDatas = fjDatas.map(fd=>{
        // console.log("fd",fd)
        let fjSrc = JSONSafeParse(fd.src,{});
          //console.log("fjSrc",fjSrc)
          const tarObjId = listMap[compId]["objId"]|| "";
          const orgObjId =  listMap[compId]["orgObjId"]||"";
            const customParamSuffix = weappUtils.qs.stringify({
            customParam: JSON.stringify({ dataId:d["id"] , objId:d[tarObjId]||orgObjId }),
          });
        const _src = fjSrc.src.replace("&module=datasource",'')
        fjSrc ={...fjSrc,src: `${_src}&module=ebuilderform&authModule=ebuilderform&appId=1&${customParamSuffix}`};
         return {...fd,src:JSON.stringify(fjSrc)}
       })
       return {...d,[_targetFieldId]:fjDatas}
     });

       return response
     }
       return response;
  }else {
    return response;
  }
}, function (error) {
  return Promise.reject(error);
});
```

## 10、拦截布局按钮复写自定义判断渲染自定义按钮

```
axios.interceptors.response.use(
    function (response) {
        // 响应状态码为 2xx 时触发成功的回调，形参中的 response 是“成功的结果”
        if (
            response.status === 200 &&
            response.config.url.includes('/api/ebuilder/form/data/getFormButtons') 
        ) {
            const requestData = JSON.parse(response.config?.data||"{}") ;
            let dataId = requestData.dataId;
            if (response.config?.data?.indexOf('1174652042036477952')<0  ) return response;
            // 无按钮
            return new Promise(function (resolve, reject) {
                weappUtils.request({
                        url: `/api/bpm/plateForm/isApproving`,//自定义接口
                        method: 'post',
                        data:{
                             flowBpmId: dataId,
                        }
                }).then((res) => {
                    if (res.status && (res.data.hasApprovingData ||1)) {
                         response.data.data =[{
                            "id": "1",
                              "buttonKey": "",
                              "name": "js按钮",
                              "showPosition": [
                                  "rightTop"
                              ],
                              "hidden": false,     
                              "actions": [
                                  {
                                      "id": "1",
                                      "actionType": "jsCode",
                                      "enable": 1,
                                      "buttonId": "2",
                                      "ecode": `console.log('${requestData.dataId}')`
                                  }
                              ]
                          }];
                        console.log(response);
                        resolve({
                            ...response,
                        });
                    } else {
                        resolve({
                            ...response,
                        });
                    }
                });
            });
            // return response;
        }else {
            return response;
        }
    },
    function (error) {
        // console.log(error)
        // 响应状态码不是 2xx 时触发失败的回调，形参中的 error 是“失败的结果”

        return Promise.reject(error);
    },
);
```

## 11、关联eb字段作为分类搜索值排序

```

//拦截请求接口，改下参数
axios.interceptors.request.use(function (config) {
  //947648104171053057  表格视图id，用来判断接口
  if(config.url.indexOf("/api/ebuilder/form/browser/groupWithCount") >-1&& 其他判断条件){
 
    //sz_2bk0wu  为关联eb对应表单的字datakey       orderType:asc |  desc | ""
    config.data.groupSortParams = [{orderKey: "sz_2bk0wu", orderType: "asc"}];
  }
  
  return config
}, function (error) {
  return Promise.reject(error);
});
```

## 12、自定义屏蔽 【批量更改字段值】中的表单字段

```javascript
/**
 * @function filterObjField
 * @param objId {string} 
 * @param ignoreFieldIds {string[]}
 * @description 传入表单id和需要屏蔽的字段id数组，可实现屏蔽批量更改字段值中的显示字段
 * */
const filterObjField = (objId,ignoreFieldIds)=>{
  axios.interceptors.response.use(
    function (response) {
      let buttonData = {};
      if (
        response.status === 200 &&
        response.config.url.includes(`/api/ebuilder/form/list/getBatchEditValueConfig/${objId}`)
      ) {
        return new Promise(function (resolve, reject) {
          const _fields = response?.data?.data?.fields || [];
          if(_fields?.length > 0){
            const fields = _fields.filter((field)=>{
              return !ignoreFieldIds.includes(field.fieldId);
            })
            response.data.data.fields = fields;
          }
          resolve(response);
        });
      }else {
        return response;
      }
    },
    function (error) {
      return Promise.reject(error);
    },
  );
}
filterObjField('1170209723078869030',["1170209723078869044"])
```

[图片附件未整合: ../../../../_assets/933185733679644672/004-afd7b246dc.png]

## 13、去除列表某个接口的参数

```javascript
axios.interceptors.request.use(function (config) {
  if(config.url.indexOf("/api/ebuilder/form/batch/getImpTemplateByObjId") >-1){
      if('layoutId' in config.data){
          delete config.data.layoutId
      }
  }
  return config
}, function (error) {
  return Promise.reject(error);
});
```

## 14、post请求的data参数是formData结构

```
/*****
*  参数是new FormData();
**/
axios.interceptors.request.use(function (config) {
  if(config.url.indexOf("/api/bs/ebuilder/form/association/save") >-1){
     config.data.set('dddd','1');
  }
  return config
}, function (error) {
  return Promise.reject(error);
});
```
