DesignPic.tsx 18 KB

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