DesignPic.tsx 15 KB

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