liqiuying 2 місяців тому
батько
коміт
cd1c41ce33
2 змінених файлів з 202 додано та 284 видалено
  1. 107 263
      entrypoints/popup/pages/DesignPic.tsx
  2. 95 21
      entrypoints/popup/pages/utils.ts

+ 107 - 263
entrypoints/popup/pages/DesignPic.tsx

@@ -365,21 +365,21 @@ export default function DesignPic() {
             // 筛选备货单号存在的值
             let pic_text_arr1 = pic_text_arr.filter(item => item.order_no && item.order_no != "-")
             // 为存在图片的对象添加宽高
-            pic_text_arr1.map(item => {
-              item.data_params.map((items: any) => {
-                if (items.design_pic) {
-                  if (img_values[items.design_pic]) {
-                    items['width'] = img_values[items.design_pic].width
-                    items['height'] = img_values[items.design_pic].height
-                    items['file'] = img_values[items.design_pic].file
-                  }
-                }
-              })
-              if (item.pre_info && item.pre_info.pre_pic) {
-                item.pre_info.width = img_values[item.pre_info.pre_pic].width
-                item.pre_info.height = img_values[item.pre_info.pre_pic].height
-              }
-            })
+            // pic_text_arr1.map(item => {
+            //   item.data_params.map((items: any) => {
+            //     if (items.design_pic) {
+            //       if (img_values[items.design_pic]) {
+            //         items['width'] = img_values[items.design_pic].width
+            //         items['height'] = img_values[items.design_pic].height
+            //         items['file'] = img_values[items.design_pic].file
+            //       }
+            //     }
+            //   })
+            //   if (item.pre_info && item.pre_info.pre_pic) {
+            //     item.pre_info.width = img_values[item.pre_info.pre_pic].width
+            //     item.pre_info.height = img_values[item.pre_info.pre_pic].height
+            //   }
+            // })
             // 数据显示
             let table_data: any[] = []
             pic_text_arr1.forEach(item => {
@@ -420,6 +420,7 @@ export default function DesignPic() {
   interface imgValuesProps {
     [key: string]: {
       design_pic: string,
+      design_sku: string
       url: string
       width: string | number
       height: string | number
@@ -435,6 +436,7 @@ export default function DesignPic() {
         if (item.design_pic && !img_values[item.design_pic]) {
           img_values[item.design_pic] = {
             design_pic: item.design_pic,
+            design_sku: item.design_sku,
             url: '',
             width: '',
             height: ''
@@ -477,26 +479,39 @@ export default function DesignPic() {
       } else {
         fetch_url = `https:${uploadUrl}photo/temuUploadStepTwo`
       }
+      if (!uploadUrl) {
+        CustomMessage.warning("上传地址丢失,请再次点击获取定制数据!")
+        return
+      }
       if (Object.values(img_values) && Object.values(img_values).length) {
-        let queImgs: any = {}, queImgsCindex = 0;
+        let queImgs: any = {}, queImgsCindex = 0, imgall_values: any = {};
         Object.values(img_values).forEach((v, cindex) => {
           if (!queImgs[cindex]) {
             queImgs[cindex] = {
-              design_pic: v.design_pic
+              design_pic: v.design_pic,
+              design_sku: v.design_sku,
             }
           }
         })
+
         const imgUpdate = () => {
           if (queImgs[queImgsCindex]) {
+            setLoading(true)
             urlToFile(queImgs[queImgsCindex]?.design_pic, `${new Date().getTime()}.png`).then(file => {
+              if (!file) {
+                queImgsCindex++
+                imgUpdate()
+                return
+              }
               // photo/temuUploadStepTwo
               let form_data = new FormData()
               form_data.append('api_token', token as string)
               form_data.append('file', file)
-              fetch(fetch_url, {
+
+              fetch(`https:${uploadUrl}photo/temuUploadStepOne`, {
                 method: 'POST',
                 headers: {
-                  'Content-Type': 'multipart/form-data',
+                  // 'Content-Type': 'multipart/form-data',
                   'access-control-allow-credentials': 'true',
                   'X-CSRF-TOKEN': 'Bearer ' + token,
                   'Authorization': 'Bearer ' + token,
@@ -505,215 +520,79 @@ export default function DesignPic() {
               }).then(resjson => {
                 return resjson.json();
               }).then(res => {
-                console.log(res, '-resres')
+                const { data } = res;
+                if (!imgall_values[queImgs[queImgsCindex].design_sku]) {
+                  imgall_values[queImgs[queImgsCindex].design_sku] = {
+                  }
+                }
+                if (!imgall_values[queImgs[queImgsCindex].design_sku][queImgs[queImgsCindex].design_pic]) {
+                  imgall_values[queImgs[queImgsCindex].design_sku][queImgs[queImgsCindex].design_pic] = {
+                    ...data
+                  }
+                }
+                if (imgall_values[queImgs[queImgsCindex].design_sku][queImgs[queImgsCindex].design_pic]) {
+                  imgall_values[queImgs[queImgsCindex].design_sku][queImgs[queImgsCindex].design_pic] = {
+                    ...data
+                  }
+                }
                 queImgsCindex++
                 imgUpdate()
 
+              }).catch(error => {
+                queImgsCindex++
+                imgUpdate()
               })
             })
-          }
-        }
-        imgUpdate()
-
-        return
-
-      }
-      return
-      console.log(table_obj, "table_obj", Object.values(table_obj))
-      const table_params = Object.values(table_obj)
-      let arr_index = 0
-      if (!uploadUrl) {
-        CustomMessage.warning("上传地址丢失,请再次点击获取定制数据!")
-        return
-      }
-
-      console.log(table_params[arr_index], '-paramsparams')
-      const FetchFun = (params: any) => {
-        // console.log(params, "params")
-        params['api_token'] = token
-        let data_params = [], form_data = new FormData();
-        // form_data.append('api_token', token)
-        // form_data.append('order_no', table_params[arr_index].order_no)
-        // form_data.append('design_sku', table_params[arr_index].design_sku)
-        // table_params[arr_index].data_params.forEach((v:any, index:number) => {
-        //   form_data.append(`data_params[${index}]['design_pic']`, v.design_pic || '')
-        //   form_data.append(`data_params[${index}]['height']`, v.height || '')
-        //   form_data.append(`data_params[${index}]['width']`, v.width || '')
-        //   form_data.append(`data_params[${index}]['text']`, v.text || '')
-        //   form_data.append(`data_params[${index}]['region']`, v.region || '')
-        //   form_data.append(`data_params[${index}]['file']`, v.file || '')
-        // })
-        fetch(fetch_url, {
-          method: 'POST',
-          headers: {
-            'Content-Type': 'application/json',
-          },
-          body: JSON.stringify(params),
-        }).then(resjson => {
-          return resjson.json();
-        }).then(res => {
-          if (res.data.error && res.data.error.length) {
-            // 未上传成功的 图片
-            console.log(res.data.error, "arr_index", arr_index)
-            res.data.error.forEach((item: any) => {
-              CustomMessage.error(item.design_pic)
-            })
-          }
-          arr_index++
-          if (arr_index < table_params.length) {
-            // tableData循环出备货单相同的数据,修改表格操作数据 is_upload
-            let tableData1 = tableData.map(item => {
-              if (item.order_no == params.order_no) {
-                console.log(item.order_no, "item.order_no", params)
-                item.is_upload = true
-              }
-              return item
-            })
-            // console.log(tableData1,"tableData111")
-            setTableData(tableData1)
-            FetchFun(table_params[arr_index])
-          } else {
-            setLoading(false)
-            setTableData([])
-            CustomMessage.success("图片上传结束")
-          }
-        }).catch(err => {
-          console.log(err, "err")
-          arr_index++
-          if (arr_index < table_params.length) {
-            FetchFun(table_params[arr_index])
           } else {
-            setLoading(false)
-            setTableData([])
-            CustomMessage.success("图片上传结束")
-          }
-        })
-      }
-      setLoading(true)
-      FetchFun(table_params[arr_index])
-    } catch (error) {
-      console.error(error, "报错")
-    }
-  }
-
-
 
-  const uploadPic1 = () => {
-    try {
-      const token = localStorage.getItem("access_token");
-      console.log(tableData, "tableData")
-      let table_obj: { [key: string]: any } = {};
-      tableData.forEach(item => {
-        if (!table_obj[item.design_sku]) {
-          table_obj[item.design_sku] = ""
-        }
-        if (table_obj[item.design_sku]) {
-          const data_params = table_obj[item.design_sku].data_params
-          data_params.push({
-            design_pic: item.file,
-            region: item.region,
-            text: item.text,
-            width: item.width,
-            height: item.height,
-          })
-          table_obj[item.design_sku] = {
-            ...table_obj[item.design_sku],
-            data_params,
-          }
-        } else {
-          table_obj[item.design_sku] = {
-            order_no: item.order_no,
-            design_sku: item.design_sku,
-            data_params: [{
-              design_pic: item.file,
-              region: item.region,
-              text: item.text,
-              width: item.width,
-              height: item.height,
-            }]
-          }
-        }
-      })
-      console.log(table_obj, "table_obj", Object.values(table_obj))
-      const table_params = Object.values(table_obj)
-      let fetch_url = "", arr_index = 0, pic_index = 0;
-      if (!uploadUrl) {
-        CustomMessage.warning("上传地址丢失,请再次点击获取定制数据!")
-        return
-      }
-      if (uploadUrl.includes('http')) {
-        fetch_url = `${uploadUrl}photo/temuUpload`
-      } else {
-        fetch_url = `http:${uploadUrl}photo/temuUpload`
-      }
-
-      // 定制图片转为二进制
-      const picFun = (item: any) => {
-        let design_arr = item.data_params;
-        console.log(design_arr, "design_arr")
-        if (Array.isArray(design_arr) && design_arr.length) {
-          const desFun = (items: any) => {
-            if (items.design_pic && items.design_pic != '-') {
-
-            } else {
-              // 执行下一张图片
-              des_index++
-              if (design_arr[des_index]) {
-                desFun(design_arr[des_index])
-              } else {
-                console.log(table_params[pic_index], "yyy")
-                // 执行外部循环
-                pic_index++
-                if (table_params[pic_index]) {
-                  picFun(table_params[pic_index])
-                } else {
-                  console.log(table_params, "table_paramssssss")
+            for (let key in table_obj) {
+              if (imgall_values[key]) {
+                if (table_obj[key].data_params && Array.isArray(table_obj[key].data_params) && table_obj[key].data_params.length) {
+                  const design_pic = table_obj[key].data_params.find((item: any) => item.design_pic)
+                  if (design_pic) {
+                    table_obj[key].data_params.map((item: any) => {
+                      if (item.design_pic && imgall_values[key][item.design_pic]) {
+                        const { width, height, url, type } = imgall_values[key][item.design_pic]
+                        item['width'] = width
+                        item['height'] = height
+                        item['file'] = url
+                        item['type'] = type
+                        console.log(item)
+                      }
+                      return item
+                    })
+                  }
                 }
               }
             }
+            console.log(imgall_values, '-imgall_values', table_obj)
+            imgFetchFun(table_obj)
           }
-          let des_index = 0;
-          desFun(design_arr[des_index])
         }
+        imgUpdate()
+        return
       }
-
-      if (table_params[pic_index]) {
-        picFun(table_params[pic_index])
-      }
-
-      return
-
-      const FetchFun = async (params: any) => {
-        // console.log(params, "params")
-        // 创建 FormData 对象用于上传二进制文件
-        const formData = new FormData();
-        formData.append('api_token', token || '');
-        formData.append('order_no', params.order_no);
-        formData.append('design_sku', params.design_sku);
-        formData.append('data_params', JSON.stringify(params.data_params));
-
-        if (Array.isArray(params.data_params) && params.data_params.length) {
-          let design_index = 0, design_files: any = [];
-          const designFun = () => {
-            let design_item = params.data_params[design_index];
-            if (design_item && design_item.design_pic) {
-              urlToFile(design_item.design_pic, `${params.order_no}_${design_item.region}.jpg`).then(file => {
-                console.log(file, "file"); // 成功获取到 File 对象
-                design_files.push({
-                  ...design_item,
-                  design_pic: file,
-                })
-                console.log(design_files, "design_files")
-                design_index++
-                if (params.data_params[design_index]) {
-                  designFun()
-                }
-              });
+      function imgFetchFun(table_obj: any) {
+        const table_params = Object.values(table_obj)
+        let arr_index = 0
+        const FetchFun = (params: any) => {
+          params['api_token'] = token
+          fetch(fetch_url, {
+            method: 'POST',
+            headers: {
+              'Content-Type': 'application/json',
+            },
+            body: JSON.stringify(params),
+          }).then(resjson => {
+            return resjson.json();
+          }).then(res => {
+            if (res.data.error && res.data.error.length) {
+              // 未上传成功的 图片
+              console.log(res.data.error, "arr_index", arr_index)
+              res.data.error.forEach((item: any) => {
+                CustomMessage.error(item.design_pic)
+              })
             }
-
-            formData.append('design_files', JSON.stringify(design_files));
-            console.log(formData, "formData")
-
             arr_index++
             if (arr_index < table_params.length) {
               // tableData循环出备货单相同的数据,修改表格操作数据 is_upload
@@ -732,57 +611,22 @@ export default function DesignPic() {
               setTableData([])
               CustomMessage.success("图片上传结束")
             }
-            return
-            fetch(fetch_url, {
-              method: 'POST',
-              // 注意:使用 FormData 时不要设置 Content-Type,浏览器会自动设置
-              body: formData,
-            }).then(response => response.json()).then(res => {
-              if (res.data?.error?.length) {
-                // 未上传成功的图片
-                console.log(res.data.error, "arr_index", arr_index)
-                res.data.error.forEach((item: any) => {
-                  CustomMessage.error(item.design_pic)
-                })
-              }
-              arr_index++
-              if (arr_index < table_params.length) {
-                // tableData循环出备货单相同的数据,修改表格操作数据 is_upload
-                let tableData1 = tableData.map(item => {
-                  if (item.order_no == params.order_no) {
-                    console.log(item.order_no, "item.order_no", params)
-                    item.is_upload = true
-                  }
-                  return item
-                })
-                // console.log(tableData1,"tableData111")
-                setTableData(tableData1)
-                FetchFun(table_params[arr_index])
-              } else {
-                setLoading(false)
-                setTableData([])
-                CustomMessage.success("图片上传结束")
-              }
-            }).catch(err => {
-              console.log(err, "err")
-              arr_index++
-              if (arr_index < table_params.length) {
-                FetchFun(table_params[arr_index])
-              } else {
-                setLoading(false)
-                setTableData([])
-                CustomMessage.success("图片上传结束")
-              }
-            })
-          }
-          designFun()
-        } else {
-          // 无定制信息情况
-          setLoading(false)
+          }).catch(err => {
+            console.log(err, "err")
+            arr_index++
+            if (arr_index < table_params.length) {
+              FetchFun(table_params[arr_index])
+            } else {
+              setLoading(false)
+              setTableData([])
+              CustomMessage.success("图片上传结束")
+            }
+          })
         }
+        setLoading(true)
+        FetchFun(table_params[arr_index])
       }
-      setLoading(true)
-      FetchFun(table_params[arr_index])
+      imgFetchFun(table_obj)
     } catch (error) {
       console.error(error, "报错")
     }

+ 95 - 21
entrypoints/popup/pages/utils.ts

@@ -1,28 +1,102 @@
-export const urlToBlob = (url: string): Promise<Blob> => {
-    return new Promise((resolve, reject) => {
-        const xhr = new XMLHttpRequest();
-        xhr.open("GET", url, true);
-        xhr.responseType = "blob";
-        xhr.onload = function () {
-            if (this.status === 200) {
-                resolve(this.response as Blob); // 显式断言为 Blob 类型
-            } else {
-                reject(new Error("Error loading image"));
+// utils.ts
+
+// 带重试机制的 fetch 封装
+const fetchWithRetry = async (url: string, options: RequestInit, maxRetries = 3, delay = 1000): Promise<Response> => {
+    let lastError: Error;
+
+    for (let i = 0; i <= maxRetries; i++) {
+        try {
+            const response = await fetch(url, options);
+            if (response.status === 429) {
+                if (i < maxRetries) {
+                    const retryDelay = delay * Math.pow(2, i) + Math.random() * 1000; // 指数退避+随机抖动
+                    await new Promise(resolve => setTimeout(resolve, retryDelay));
+                    continue;
+                } else {
+                    throw new Error(`Too Many Requests (429). Max retries exceeded.`);
+                }
+            }
+            if (!response.ok) {
+                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
             }
-        };
-        xhr.onerror = function () {
-            reject(new Error("Network error"));
-        };
-        xhr.send();
-    });
+            return response;
+        } catch (error) {
+            lastError = error as Error;
+            if (i < maxRetries) {
+                const retryDelay = delay * Math.pow(2, i) + Math.random() * 1000;
+                await new Promise(resolve => setTimeout(resolve, retryDelay));
+            }
+        }
+    }
+    throw lastError!;
 };
 
-export const urlToFile = async (url: string, fileName: string) => {
-    console.log("urlToFile")
-    return urlToBlob(url).then(blob => {
+export const urlToBlob = async (url: string): Promise<Blob> => {
+    try {
+        const response = await fetchWithRetry(url, {
+            headers: {
+                "accept": 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
+            }
+        }, 3, 2000); // 最多重试3次,基础延迟2秒
+
+        return await response.blob();
+    } catch (error) {
+        console.error(`获取图片失败 (${url}):`, error);
+        throw error;
+    }
+};
+
+export const urlToFile = async (url: string, fileName: string): Promise<File | null> => {
+    try {
+        const blob = await urlToBlob(url);
         return new File([blob], fileName, {
             type: blob.type,
             lastModified: new Date().getTime()
         });
-    });
-}
+    } catch (error) {
+        console.error(`图片转文件失败 (${url}):`, error);
+        return null;
+    }
+};
+// export const urlToBlob = async (url: string): Promise<Blob> => {
+//     return new Promise(async (resolve, reject) => {
+//         const response = await fetch(url, {
+//             headers: {
+//                 "accept": 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
+//             }
+//         });
+//         if (!response.ok) {
+//             reject(null)
+//         };
+
+//         resolve(await response.blob() as Blob); // 显式断言为 Blob 类型
+//         return
+//         const xhr = new XMLHttpRequest();
+//         xhr.open("GET", url, true);
+//         xhr.responseType = "blob";
+//         xhr.onload = function () {
+//             if (this.status === 200) {
+//                 resolve(this.response as Blob); // 显式断言为 Blob 类型
+//             } else {
+//                 reject(new Error("Error loading image"));
+//             }
+//         };
+//         xhr.onerror = function () {
+//             reject(new Error("Network error"));
+//         };
+//         xhr.send();
+//     });
+// };
+
+// export const urlToFile = async (url: string, fileName: string) => {
+//     console.log("urlToFile")
+//     return urlToBlob(url).then(blob => {
+//         if (!blob) return null;
+//         return new File([blob], fileName, {
+//             type: blob.type,
+//             lastModified: new Date().getTime()
+//         });
+//     }).catch(error => {
+//         return null;
+//     })
+// }