DesignPic.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. import React, { useState, useEffect } from 'react'
  2. import { Button, Table, Input, Message, Loading } from '@alifd/next';
  3. import { CustomMessage } from '@/components/CustomMessage'
  4. export default function DesignPic() {
  5. const [uploadUrl, setUploadUrl] = useState<string>("");
  6. // 添加状态管理表格数据
  7. const [tableData, setTableData] = useState<any[]>([]);
  8. const [loading, setLoading] = useState(false);
  9. const [isPage, setIsPage] = useState(true);
  10. useEffect(() => {
  11. is_temu_design()
  12. }, [])
  13. const is_temu_design = async () => {
  14. try {
  15. // 获取当前活动标签页
  16. const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
  17. // 获取页面域名
  18. if (tab.url) {
  19. const url = tab.url
  20. console.log('当前页面域名:', url);
  21. if (url.includes('main/customize-goods')) {
  22. // temu定制页面
  23. setIsPage(false)
  24. }
  25. }
  26. } catch (error) {
  27. console.error('获取当前页面域名时出错:', error);
  28. }
  29. }
  30. const pic_render = (value: any, index: any, record: any) => {
  31. return (
  32. <>
  33. {
  34. record.file ? <>
  35. <img className='size-20' src={record.file} /></> : <>
  36. <span>暂无图片</span>
  37. </>
  38. }
  39. </>
  40. );
  41. }
  42. const text_render = (value: any, index: any, record: any) => {
  43. return (
  44. <p>{record.text}</p>
  45. );
  46. }
  47. // 修改图片名称渲染函数
  48. const name_render = (value: any, index: number, record: any) => {
  49. return <>
  50. <div>{record.design_sku}</div>
  51. </>
  52. };
  53. // 修改图片标签渲染函数
  54. const label_render = (value: any, index: number, record: any) => {
  55. return <>
  56. <div>{record.region}</div>
  57. </>
  58. };
  59. // 完善删除功能
  60. const handleDelete = (index: number, record: any) => {
  61. // 方案1: 直接删除
  62. const newData = [...tableData];
  63. newData.splice(index, 1);
  64. setTableData(newData);
  65. // 方案2: 带确认的删除 (可选)
  66. // if (window.confirm(`确定要删除 "${record.title.name}" 吗?`)) {
  67. // const newData = [...tableData];
  68. // newData.splice(index, 1);
  69. // setTableData(newData);
  70. // Message.success('删除成功');
  71. // }
  72. };
  73. // 删除操作渲染函数
  74. const option_render = (value: any, index: number, record: any) => {
  75. return (
  76. <a
  77. className='text-red-600 cursor-pointer'
  78. onClick={() => handleDelete(index, record)}
  79. >
  80. 删除
  81. </a>
  82. );
  83. };
  84. // 添加行索引以确保正确删除
  85. const dataSourceWithIndex = tableData.map((item, index) => ({
  86. ...item,
  87. index
  88. }));
  89. const getPicData = async () => {
  90. try {
  91. setLoading(true)
  92. // 获取上传路径
  93. fetch('http://merchant.landwu.com/api/photo/getUploadUrl', {
  94. method: 'POST',
  95. headers: {
  96. 'Content-Type': 'application/json',
  97. },
  98. body: JSON.stringify({
  99. api_token: localStorage.getItem('access_token'),
  100. }),
  101. }).then(resjson => {
  102. return resjson.json();
  103. }).then(res => {
  104. if (res.data) {
  105. const { data = {} } = res;
  106. const { url = null } = data;
  107. setUploadUrl(url)
  108. setLoading(false)
  109. }
  110. })
  111. // 获取当前活动标签页
  112. const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
  113. if (tab.id) {
  114. // 发送消息到content script请求获取tbody数据
  115. const response = await browser.tabs.sendMessage(tab.id, { action: "getTbodyData" });
  116. const table_datas = []
  117. // 在控制台输出结果
  118. if (response.tables && response.tables.length > 0) {
  119. // console.log("找到的表格数据(包含背景图片):");
  120. // 显式声明类型
  121. let tables_arr: {
  122. good_info: any;
  123. sku_info: any;
  124. order_no: any;
  125. design_sku: any;
  126. design_info: { region: any; text: any; picture: any, cur_index: number }[];
  127. }[] = [];
  128. let table_boj: {
  129. good_info: any;
  130. sku_info: any;
  131. order_no: any;
  132. design_sku: any;
  133. design_info: { region: any; text: any; picture: any, cur_index: number }[];
  134. } = {
  135. good_info: null,
  136. sku_info: null,
  137. order_no: null,
  138. design_sku: null,
  139. design_info: []
  140. };
  141. response.tables.forEach((table_node: any, index: number) => {
  142. console.log(`表格 ${index + 1}:`, table_node);
  143. // 处理成接口参数
  144. // 处理成数组对象
  145. if (table_node.length > 4) {
  146. if (table_boj.design_info.length) {
  147. // 一个商品的定制信息
  148. tables_arr.push(table_boj)
  149. // 重置
  150. table_boj = {
  151. good_info: null,
  152. sku_info: null,
  153. order_no: null,
  154. design_sku: null,
  155. design_info: []
  156. }
  157. }
  158. table_boj = {
  159. good_info: table_node[1],
  160. sku_info: table_node[2],
  161. order_no: table_node[3],
  162. design_sku: table_node[4],
  163. design_info: [{
  164. region: table_node[9],
  165. text: table_node[10],
  166. picture: table_node[11],//11
  167. cur_index: index + 1,
  168. }]
  169. }
  170. } else {
  171. table_boj.design_info.push({
  172. region: table_node[0],
  173. text: table_node[1],
  174. picture: table_node[2],//2
  175. cur_index: index + 1,
  176. })
  177. // 循环结束
  178. if (index == response.tables.length - 1) {
  179. if (table_boj.design_info.length) {
  180. // 一个商品的定制信息
  181. tables_arr.push(table_boj)
  182. }
  183. }
  184. }
  185. // good_info sku_info design_info: region text picture cur_index
  186. });
  187. console.log(tables_arr, "tables_arrddd")
  188. // 上传图片的参数处理
  189. // let params_arr: any[] = []
  190. // tables_arr.forEach(item => {
  191. // // const sku_info = item.sku_info?.text?.split('SKU:')
  192. // let order_no = ""
  193. // if (item.order_no && item.order_no != "-") {
  194. // order_no = item.order_no.substring(0, 15); // 取前15位
  195. // }
  196. // if (item.design_info.length) {
  197. // item.design_info.forEach(design_item => {
  198. // const prarm = {
  199. // title: '',
  200. // label: '',
  201. // category_id: '',
  202. // category_name: '',
  203. // file: '',
  204. // cur_index: ''
  205. // };
  206. // if (order_no && design_item.picture && design_item.picture != '-') {
  207. // // const text = design_item.text.split('}')
  208. // const bg_pic = (design_item.picture.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
  209. // let bg_file = bg_pic.split('&imageMogr2/thumbnail/60x60')[0]
  210. // prarm.title = `${order_no}-${design_item.region}`
  211. // prarm.label = `${order_no}-${design_item.region}`
  212. // prarm.file = bg_file ?? '';
  213. // params_arr.push(prarm)
  214. // }
  215. // })
  216. // }
  217. // })
  218. // console.log(params_arr, "params_arr")
  219. // setTableData(params_arr)
  220. // 上传图片和文字的参数处理
  221. let pic_text_arr: any[] = []
  222. tables_arr.forEach(item => {
  223. let order_no = "", data_params: any[] = []
  224. if (item.order_no && item.order_no != "-") {
  225. order_no = item.order_no.substring(0, 15); // 取前15位
  226. }
  227. if (item.design_info.length) {
  228. item.design_info.forEach(items => {
  229. const param: any = {}
  230. if (order_no || item.design_sku) {
  231. let bg_pic = ""
  232. if (items.picture && items.picture != '-') {
  233. let bg_pic1 = (items.picture.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
  234. bg_pic = bg_pic1.split('&imageMogr2/thumbnail/60x60')[0]
  235. } else {
  236. bg_pic = ""
  237. }
  238. let des_text = ""
  239. if (items.text && items.text != '-') {
  240. const des_text1 = items.text.split(";}")[1]
  241. des_text = des_text1.split("查看")[0]
  242. } else {
  243. des_text = ""
  244. }
  245. param['region'] = items.region
  246. param['text'] = des_text
  247. param['design_pic'] = bg_pic
  248. data_params.push(param)
  249. }
  250. })
  251. }
  252. if (order_no || item.design_sku) {
  253. pic_text_arr.push({
  254. order_no,
  255. design_sku: item.design_sku,
  256. data_params
  257. })
  258. }
  259. })
  260. console.log(pic_text_arr, "pic_text_arr")
  261. // const params = {...pic_text_arr[0],api_token: localStorage.getItem('access_token')}
  262. // console.log(params,"params")
  263. // fetch(`http:${uploadUrl}photo/temuUpload `, {
  264. // method: 'POST',
  265. // headers: {
  266. // 'Content-Type': 'application/json',
  267. // },
  268. // body: JSON.stringify(params),
  269. // }).then(resjson => {
  270. // return resjson.json();
  271. // }).then(res => {
  272. // if (res.data) {
  273. // }
  274. // })
  275. // 数据显示
  276. let table_data: any[] = []
  277. pic_text_arr.forEach(item => {
  278. if (item.data_params.length) {
  279. item.data_params.forEach((items: any) => {
  280. table_data.push({
  281. order_no: item.order_no,
  282. design_sku: item.design_sku,
  283. file: items.design_pic,
  284. region: items.region,
  285. text: items.text,
  286. })
  287. })
  288. }
  289. })
  290. setTableData(table_data)
  291. // const table_arrs = response.tables // 表格数组
  292. // let i = 0, table_node = table_arrs[i], tables_arr = [];
  293. // let table_boj: {
  294. // good_info: any;
  295. // sku_info: any;
  296. // design_info: { region: any; text: any; picture: any }[];
  297. // } = {
  298. // good_info: null,
  299. // sku_info: null,
  300. // design_info: []
  301. // };
  302. // while (i < response.tables.length) {
  303. // // 长度大于4时,指针改变
  304. // if (table_node.length > 4) {
  305. // if (table_boj.design_info.length) {
  306. // // 一个商品的定制信息
  307. // tables_arr.push(table_boj)
  308. // // 重置
  309. // table_boj = {
  310. // good_info: null,
  311. // sku_info: null,
  312. // design_info: []
  313. // }
  314. // }
  315. // table_boj = {
  316. // good_info: table_node[1],
  317. // sku_info: table_node[2],
  318. // design_info: [{
  319. // region: table_node[9],
  320. // text: table_node[10],
  321. // picture: table_node[11],
  322. // }]
  323. // }
  324. // i++
  325. // table_node = table_arrs[i]
  326. // } else {
  327. // table_boj.design_info.push({
  328. // region: table_node[0],
  329. // text: table_node[1],
  330. // picture: table_node[2],
  331. // })
  332. // i++
  333. // table_node = table_arrs[i]
  334. // }
  335. // }
  336. } else {
  337. console.log("页面上未找到表格数据");
  338. CustomMessage.error("页面上未找到表格数据");
  339. }
  340. }
  341. } catch (error) {
  342. console.error("获取表格数据失败:", error);
  343. CustomMessage.error("获取表格数据失败");
  344. }
  345. };
  346. const uploadPic = () => {
  347. const token = localStorage.getItem("access_token");
  348. console.log(tableData, "tableData")
  349. let table_obj: { [key: string]: any } = {};
  350. tableData.forEach(item => {
  351. if (table_obj[item.design_sku]) {
  352. const data_params = table_obj[item.design_sku].data_params
  353. data_params.push({
  354. design_pic: item.file,
  355. region: item.region,
  356. text: item.text
  357. })
  358. table_obj[item.design_sku] = {
  359. ...table_obj[item.design_sku],
  360. data_params,
  361. }
  362. } else {
  363. table_obj[item.design_sku] = {
  364. order_no: item.order_no,
  365. design_sku: item.design_sku,
  366. data_params: [{
  367. design_pic: item.file,
  368. region: item.region,
  369. text: item.text
  370. }]
  371. }
  372. }
  373. })
  374. console.log(table_obj, "table_obj", Object.values(table_obj))
  375. const table_params = Object.values(table_obj)
  376. let fetch_url = "", arr_index = 0
  377. if (uploadUrl.includes('http')) {
  378. fetch_url = `${uploadUrl}photo/temuUpload`
  379. } else {
  380. fetch_url = `http:${uploadUrl}photo/temuUpload`
  381. }
  382. const FetchFun = (params: any) => {
  383. // console.log(params, "params")
  384. params['api_token'] = token
  385. fetch(fetch_url, {
  386. method: 'POST',
  387. headers: {
  388. 'Content-Type': 'application/json',
  389. },
  390. body: JSON.stringify(params),
  391. }).then(resjson => {
  392. return resjson.json();
  393. }).then(res => {
  394. if (res.data.error && res.data.error.length) {
  395. // 未上传成功的 图片
  396. console.log(res.data.error, "arr_index", arr_index)
  397. res.data.error.forEach((item: any) => {
  398. CustomMessage.error(item.design_pic)
  399. })
  400. }
  401. arr_index++
  402. if (arr_index < table_params.length) {
  403. FetchFun(table_params[arr_index])
  404. } else {
  405. setLoading(false)
  406. setTableData([])
  407. CustomMessage.success("图片上传结束")
  408. }
  409. }).catch(err => {
  410. console.log(err, "err")
  411. arr_index++
  412. if (arr_index < table_params.length) {
  413. FetchFun(table_params[arr_index])
  414. } else {
  415. setLoading(false)
  416. setTableData([])
  417. CustomMessage.success("图片上传结束")
  418. }
  419. })
  420. }
  421. setLoading(true)
  422. FetchFun(table_params[arr_index])
  423. return
  424. // 在此处添加下标索引参数
  425. const table_datas = tableData.map((item, index) => {
  426. item.cur_index = index + 1
  427. item.api_token = token
  428. return item
  429. })
  430. if (!uploadUrl) {
  431. Message.error("图片上传路径未获取到,请重新点击获取定制图片数据按钮")
  432. return
  433. }
  434. const fetch_fn = (data: any) => {
  435. const formData = new FormData()
  436. for (var key in data) {
  437. formData.append(key, data[key])
  438. }
  439. fetch(fetch_url, {
  440. method: 'POST',
  441. // headers: {
  442. // 'Content-Type': 'application/json',
  443. // },
  444. body: formData,
  445. mode: 'cors'
  446. }).then(resjson => {
  447. return resjson.json();
  448. }).then(res => {
  449. if (res.code == -1) {
  450. Message.error(res.msg)
  451. }
  452. arr_index++
  453. if (arr_index < table_datas.length) {
  454. fetch_fn(table_datas[arr_index])
  455. } else {
  456. // 上传完成
  457. Message.success(res.msg)
  458. setLoading(false)
  459. }
  460. }).catch(error => {
  461. setLoading(false)
  462. Message.error(error.message)
  463. arr_index++
  464. if (arr_index < table_datas.length) {
  465. fetch_fn(table_datas[arr_index])
  466. }
  467. })
  468. }
  469. console.log(table_datas, "table_datasss")
  470. setLoading(true)
  471. fetch_fn(table_datas[arr_index])
  472. // setTableData(tableData)
  473. }
  474. return (
  475. <Loading visible={loading} fullScreen>
  476. <div className='w-3xl h-fit'>
  477. <Button
  478. type="primary"
  479. disabled={isPage}
  480. style={{ marginBottom: '10px', marginRight: '10px' }}
  481. onClick={() => {
  482. getPicData()
  483. }}>获取定制数据</Button>
  484. <Button
  485. disabled={(!tableData.length) || isPage}
  486. type="primary"
  487. style={{ marginBottom: '10px', marginRight: '10px' }}
  488. onClick={() => {
  489. uploadPic()
  490. }}>上传定制信息</Button>
  491. <span className='text-red-500'>ps:需在Temu定制商品内容页面获取数据,且上传图片过程中请勿关闭插件</span>
  492. <Table dataSource={dataSourceWithIndex}>
  493. <Table.Column title="图片" cell={pic_render} />
  494. <Table.Column title="定制SKU" cell={name_render} />
  495. <Table.Column title="定制区域" cell={label_render} />
  496. <Table.Column title="文字" cell={text_render} />
  497. <Table.Column title="操作" cell={option_render} />
  498. </Table>
  499. <p className='text-red-500'>ps:若获取不到数据,可能是插件未连接成功,请刷新页面</p>
  500. </div>
  501. </Loading>
  502. )
  503. }