DesignPic_20250813172554.tsx 15 KB

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