DesignPic.tsx 16 KB

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