DesignPic_20250813173917.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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[0],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: any[] = []
  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. setTableData(table_data)
  284. // const table_arrs = response.tables // 表格数组
  285. // let i = 0, table_node = table_arrs[i], tables_arr = [];
  286. // let table_boj: {
  287. // good_info: any;
  288. // sku_info: any;
  289. // design_info: { region: any; text: any; picture: any }[];
  290. // } = {
  291. // good_info: null,
  292. // sku_info: null,
  293. // design_info: []
  294. // };
  295. // while (i < response.tables.length) {
  296. // // 长度大于4时,指针改变
  297. // if (table_node.length > 4) {
  298. // if (table_boj.design_info.length) {
  299. // // 一个商品的定制信息
  300. // tables_arr.push(table_boj)
  301. // // 重置
  302. // table_boj = {
  303. // good_info: null,
  304. // sku_info: null,
  305. // design_info: []
  306. // }
  307. // }
  308. // table_boj = {
  309. // good_info: table_node[1],
  310. // sku_info: table_node[2],
  311. // design_info: [{
  312. // region: table_node[9],
  313. // text: table_node[10],
  314. // picture: table_node[11],
  315. // }]
  316. // }
  317. // i++
  318. // table_node = table_arrs[i]
  319. // } else {
  320. // table_boj.design_info.push({
  321. // region: table_node[0],
  322. // text: table_node[1],
  323. // picture: table_node[2],
  324. // })
  325. // i++
  326. // table_node = table_arrs[i]
  327. // }
  328. // }
  329. } else {
  330. console.log("页面上未找到表格数据");
  331. }
  332. }
  333. } catch (error) {
  334. console.error("获取表格数据失败:", error);
  335. }
  336. };
  337. const uploadPic = () => {
  338. const token = localStorage.getItem("access_token");
  339. // 在此处添加下标索引参数
  340. const table_datas = tableData.map((item, index) => {
  341. item.cur_index = index + 1
  342. item.api_token = token
  343. return item
  344. })
  345. if (!uploadUrl) {
  346. Message.error("图片上传路径未获取到,请重新点击获取定制图片数据按钮")
  347. return
  348. }
  349. let fetch_url = "", arr_index = 0
  350. if (uploadUrl.includes('http')) {
  351. fetch_url = `${uploadUrl}sheInPhoto/upload`
  352. } else {
  353. fetch_url = `http:${uploadUrl}sheInPhoto/upload`
  354. }
  355. const fetch_fn = (data: any) => {
  356. const formData = new FormData()
  357. for (var key in data) {
  358. formData.append(key, data[key])
  359. }
  360. fetch(fetch_url, {
  361. method: 'POST',
  362. // headers: {
  363. // 'Content-Type': 'application/json',
  364. // },
  365. body: formData,
  366. mode: 'cors'
  367. }).then(resjson => {
  368. return resjson.json();
  369. }).then(res => {
  370. if (res.code == -1) {
  371. Message.error(res.msg)
  372. }
  373. arr_index++
  374. if (arr_index < table_datas.length) {
  375. fetch_fn(table_datas[arr_index])
  376. } else {
  377. // 上传完成
  378. Message.success(res.msg)
  379. setLoading(false)
  380. }
  381. }).catch(error => {
  382. setLoading(false)
  383. Message.error(error.message)
  384. arr_index++
  385. if (arr_index < table_datas.length) {
  386. fetch_fn(table_datas[arr_index])
  387. }
  388. })
  389. }
  390. console.log(table_datas, "table_datasss")
  391. setLoading(true)
  392. fetch_fn(table_datas[arr_index])
  393. // setTableData(tableData)
  394. }
  395. return (
  396. <Loading visible={loading} fullScreen>
  397. <div className='w-3xl h-fit'>
  398. <Button type="primary" style={{ marginBottom: '10px', marginRight: '10px' }}
  399. onClick={() => {
  400. getPicData()
  401. }}>获取定制图片数据</Button>
  402. <Button disabled={!tableData.length} type="primary" style={{ marginBottom: '10px', marginRight: '10px' }}
  403. onClick={() => {
  404. uploadPic()
  405. }}>上传图片</Button>
  406. <span className='text-red-500'>ps:上传图片过程中请勿关闭插件</span>
  407. <Table dataSource={dataSourceWithIndex}>
  408. <Table.Column title="图片" cell={pic_render} />
  409. <Table.Column title="" cell={name_render} />
  410. <Table.Column title="图片标签" cell={label_render} />
  411. <Table.Column title="文字" cell={text_render} />
  412. <Table.Column title="操作" cell={option_render} />
  413. </Table>
  414. </div>
  415. </Loading>
  416. )
  417. }