DesignPic_20250813170203.tsx 14 KB

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