liqiuying vor 2 Monaten
Ursprung
Commit
22dacb5768
2 geänderte Dateien mit 405 neuen und 29 gelöschten Zeilen
  1. 377 29
      entrypoints/popup/pages/DesignPic.tsx
  2. 28 0
      entrypoints/popup/pages/utils.ts

+ 377 - 29
entrypoints/popup/pages/DesignPic.tsx

@@ -1,6 +1,8 @@
 import React, { useState, useEffect } from 'react'
-import { Button, Table, Input, Message, Loading } from '@alifd/next';
+import { Button, Table, Input, Message, Loading, Radio } from '@alifd/next';
 import { CustomMessage } from '@/components/CustomMessage'
+import { urlToFile } from './utils';
+const RadioGroup = Radio.Group
 
 export default function DesignPic() {
   const [uploadUrl, setUploadUrl] = useState<string>("");
@@ -9,6 +11,8 @@ export default function DesignPic() {
   const [loading, setLoading] = useState(false);
   const [isPage, setIsPage] = useState(true);
   const [btnLoading, setBtnLoading] = useState(false);
+  const [isPreImg, setIsPreImg] = useState(-1)
+
 
   useEffect(() => {
     is_temu_design()
@@ -39,13 +43,24 @@ export default function DesignPic() {
     )
   }
 
+  const design_render = (value: any, index: any, record: any) => {
+    return <>
+      {
+        record.pre_info && record.pre_info.pre_pic ? <>
+          <div className='flex items-center justify-center'><img className='size-20' src={record.pre_info?.pre_pic} /></div></> : <>
+          <span>暂无图片</span>
+        </>
+      }
+    </>
+  }
+
 
   const pic_render = (value: any, index: any, record: any) => {
     return (
       <>
         {
-          record.file ? <>
-            <div className='flex items-center justify-center'><img className='size-20' src={record.file} /></div></> : <>
+          record.design_pic ? <>
+            <div className='flex items-center justify-center'><img className='size-20' src={record.design_pic} /></div></> : <>
             <span>暂无图片</span>
           </>
         }
@@ -151,7 +166,6 @@ export default function DesignPic() {
       if (tab.id) {
         // 发送消息到content script请求获取tbody数据
         const response = await browser.tabs.sendMessage(tab.id, { action: "getTbodyData" });
-        const table_datas = []
         // 在控制台输出结果
         if (response.tables && response.tables.length > 0) {
           // console.log("找到的表格数据(包含背景图片):");
@@ -161,6 +175,7 @@ export default function DesignPic() {
             sku_info: any;
             order_no: any;
             design_sku: any;
+            pre_design_info: any;
             design_info: { region: any; text: any; picture: any }[];
           }[] = [];
           let table_boj: {
@@ -168,12 +183,14 @@ export default function DesignPic() {
             sku_info: any;
             order_no: any;
             design_sku: any;
+            pre_design_info: any;
             design_info: { region: any; text: any; picture: any }[];
           } = {
             good_info: null,
             sku_info: null,
             order_no: null,
             design_sku: null,
+            pre_design_info: null,
             design_info: []
           };
 
@@ -192,6 +209,7 @@ export default function DesignPic() {
                   sku_info: null,
                   order_no: null,
                   design_sku: null,
+                  pre_design_info: null,
                   design_info: []
                 }
               }
@@ -200,6 +218,7 @@ export default function DesignPic() {
                 sku_info: table_node[2],
                 order_no: table_node[3],
                 design_sku: table_node[4],
+                pre_design_info: table_node[13],
                 design_info: [{
                   region: table_node[9],
                   text: table_node[10],
@@ -228,10 +247,36 @@ export default function DesignPic() {
           // 上传图片和文字的参数处理
           let pic_text_arr: any[] = [], img_values: any = {}
           tables_arr.forEach(item => {
-            let order_no = "", data_params: any[] = []
+            let order_no = "", data_params: any[] = [], pre_info = {};
             if (item.order_no && item.order_no != "-") {
               order_no = item.order_no.substring(0, 15); // 取前15位
             }
+            if (order_no) {
+              let pre_pic = ""
+              if (item.pre_design_info && item.pre_design_info != '-') {
+                let pre_pic1 = (item.pre_design_info.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
+                pre_pic = pre_pic1.split('&imageMogr2/thumbnail')[0]
+                if (!img_values[pre_pic]) {
+                  img_values[pre_pic] = {
+                    src: pre_pic,
+                    width: '',
+                    height: '',
+                    order_no,
+                    file: ''
+                  }
+                }
+                if (pre_pic) {
+                  pre_info = {
+                    pre_pic,
+                    width: 400,
+                    height: 400
+                  }
+                }
+              } else {
+                pre_pic = ""
+              }
+            }
+            // 定制信息处理
             if (item.design_info.length) {
               item.design_info.forEach(items => {
                 const param: any = {}
@@ -239,7 +284,7 @@ export default function DesignPic() {
                   let bg_pic = ""
                   if (items.picture && items.picture != '-') {
                     let bg_pic1 = (items.picture.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
-                    bg_pic = bg_pic1.split('&imageMogr2/thumbnail/60x60')[0]
+                    bg_pic = bg_pic1.split('&imageMogr2/thumbnail')[0]
                     if (!img_values[bg_pic]) {
                       img_values[bg_pic] = {
                         src: bg_pic,
@@ -272,6 +317,7 @@ export default function DesignPic() {
               pic_text_arr.push({
                 order_no,
                 design_sku: item.design_sku,
+                pre_info,
                 data_params
               })
             }
@@ -286,20 +332,27 @@ export default function DesignPic() {
 
           const queueImg = () => {
             if (img_values1[cIndex]) {
-              let img = new Image()
-              img.onload = function () {
-                img_values1[cIndex].width = img.width
-                img_values1[cIndex].height = img.height
-                img_values[img_values1[cIndex]?.src]['width'] = img.width
-                img_values[img_values1[cIndex]?.src]['height'] = img.height
-                cIndex++
-                queueImg()
-              }
-              img.onerror = function () {
-                cIndex++
-                queueImg()
+              cIndex++
+              queueImg()
+              return
+              {
+                let img = new Image()
+                img.onload = function () {
+                  img_values1[cIndex].width = img.width
+                  img_values1[cIndex].height = img.height
+                  img_values[img_values1[cIndex]?.src]['width'] = img.width
+                  img_values[img_values1[cIndex]?.src]['height'] = img.height
+                  cIndex++
+                  queueImg()
+
+                }
+
+                img.onerror = function () {
+                  cIndex++
+                  queueImg()
+                }
+                img.src = img_values1[cIndex]?.src
               }
-              img.src = img_values1[cIndex]?.src
 
             } else {
               getImgWh()
@@ -318,9 +371,14 @@ export default function DesignPic() {
                   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[] = []
@@ -329,8 +387,10 @@ export default function DesignPic() {
                 item.data_params.forEach((items: any) => {
                   table_data.push({
                     order_no: item.order_no,
+                    pre_info: item.pre_info,
                     design_sku: item.design_sku,
-                    file: items.design_pic,
+                    design_pic: items.design_pic,
+                    file: items.file,
                     region: items.region,
                     text: items.text,
                     width: items.width || "",
@@ -357,19 +417,37 @@ export default function DesignPic() {
     }
   };
 
+  interface imgValuesProps {
+    [key: string]: {
+      design_pic: string,
+      url: string
+      width: string | number
+      height: string | number
+    },
+  }
   const uploadPic = () => {
     try {
       const token = localStorage.getItem("access_token");
       console.log(tableData, "tableData")
-      let table_obj: { [key: string]: any } = {};
+      let table_obj: { [key: string]: any } = {},
+        img_values: imgValuesProps = {}, fetch_url = "";
       tableData.forEach(item => {
+        if (item.design_pic && !img_values[item.design_pic]) {
+          img_values[item.design_pic] = {
+            design_pic: item.design_pic,
+            url: '',
+            width: '',
+            height: ''
+          }
+        }
         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,
+            design_pic: item.design_pic,
+            file: item.file || "",
             region: item.region,
             text: item.text,
             width: item.width,
@@ -384,7 +462,8 @@ export default function DesignPic() {
             order_no: item.order_no,
             design_sku: item.design_sku,
             data_params: [{
-              design_pic: item.file,
+              design_pic: item.design_pic,
+              file: item.file || '',
               region: item.region,
               text: item.text,
               width: item.width,
@@ -393,21 +472,77 @@ export default function DesignPic() {
           }
         }
       })
+      if (uploadUrl.includes('http')) {
+        fetch_url = `${uploadUrl}photo/temuUploadStepTwo`
+      } else {
+        fetch_url = `https:${uploadUrl}photo/temuUploadStepTwo`
+      }
+      if (Object.values(img_values) && Object.values(img_values).length) {
+        let queImgs: any = {}, queImgsCindex = 0;
+        Object.values(img_values).forEach((v, cindex) => {
+          if (!queImgs[cindex]) {
+            queImgs[cindex] = {
+              design_pic: v.design_pic
+            }
+          }
+        })
+        const imgUpdate = () => {
+          if (queImgs[queImgsCindex]) {
+            urlToFile(queImgs[queImgsCindex]?.design_pic, `${new Date().getTime()}.png`).then(file => {
+              // photo/temuUploadStepTwo
+              let form_data = new FormData()
+              form_data.append('api_token', token as string)
+              form_data.append('file', file)
+              fetch(fetch_url, {
+                method: 'POST',
+                headers: {
+                  'Content-Type': 'multipart/form-data',
+                  'access-control-allow-credentials': 'true',
+                  'X-CSRF-TOKEN': 'Bearer ' + token,
+                  'Authorization': 'Bearer ' + token,
+                },
+                body: form_data,
+              }).then(resjson => {
+                return resjson.json();
+              }).then(res => {
+                console.log(res, '-resres')
+                queImgsCindex++
+                imgUpdate()
+
+              })
+            })
+          }
+        }
+        imgUpdate()
+
+        return
+
+      }
+      return
       console.log(table_obj, "table_obj", Object.values(table_obj))
       const table_params = Object.values(table_obj)
-      let fetch_url = "", arr_index = 0
+      let arr_index = 0
       if (!uploadUrl) {
         CustomMessage.warning("上传地址丢失,请再次点击获取定制数据!")
         return
       }
-      if (uploadUrl.includes('http')) {
-        fetch_url = `${uploadUrl}photo/temuUpload`
-      } else {
-        fetch_url = `http:${uploadUrl}photo/temuUpload`
-      }
+
+      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: {
@@ -461,6 +596,203 @@ export default function DesignPic() {
     }
   }
 
+
+
+  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")
+                }
+              }
+            }
+          }
+          let des_index = 0;
+          desFun(design_arr[des_index])
+        }
+      }
+
+      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()
+                }
+              });
+            }
+
+            formData.append('design_files', JSON.stringify(design_files));
+            console.log(formData, "formData")
+
+            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("图片上传结束")
+            }
+            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)
+        }
+      }
+      setLoading(true)
+      FetchFun(table_params[arr_index])
+    } catch (error) {
+      console.error(error, "报错")
+    }
+  }
+
+  const evChangeRadio = (e: any) => {
+    let ev = e && e.target ? e.target.value : e
+    setIsPreImg(ev)
+  }
+
   return (
     <Loading visible={loading} fullScreen>
       <div className='w-3xl h-fit'>
@@ -479,8 +811,24 @@ export default function DesignPic() {
             uploadPic()
           }}>上传定制信息</Button>
         <span className='text-red-500'>ps:需在Temu定制商品内容页面获取数据,且上传图片过程中请勿关闭插件</span>
+        <div className='flex items-center' style={{ marginBottom: '10px' }}>
+          <p style={{ fontSize: 14, marginBottom: 0, marginRight: 5 }}>是否获取合成预览图: </p>
+          <RadioGroup value={isPreImg} onChange={(e) => {
+            evChangeRadio(e)
+          }} aria-labelledby="groupId">
+            <Radio value={1}>
+              是
+            </Radio>
+            <Radio value={-1}>
+              否
+            </Radio>
+          </RadioGroup>
+        </div>
         <Table dataSource={dataSourceWithIndex}>
           <Table.Column title="序号" cell={order_render} align="center" />
+          {
+            isPreImg == 1 && <Table.Column title="定制区域图" cell={design_render} align="center" />
+          }
           <Table.Column title="图片" cell={pic_render} align="center" />
           <Table.Column title="备货单" cell={name_render} align="center" />
           <Table.Column title="定制区域" cell={label_render} align="center" />

+ 28 - 0
entrypoints/popup/pages/utils.ts

@@ -0,0 +1,28 @@
+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"));
+            }
+        };
+        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 => {
+        return new File([blob], fileName, {
+            type: blob.type,
+            lastModified: new Date().getTime()
+        });
+    });
+}