DesignPic_20250813163428.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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_info: { region: any; text: any; picture: any, cur_index: number }[];
  119. }[] = [];
  120. let table_boj: {
  121. good_info: any;
  122. sku_info: any;
  123. order_no: any;
  124. design_info: { region: any; text: any; picture: any, cur_index: number }[];
  125. } = {
  126. good_info: null,
  127. sku_info: null,
  128. order_no: null,
  129. design_info: []
  130. };
  131. response.tables.forEach((table_node: any, index: number) => {
  132. console.log(`表格 ${index + 1}:`, table_node);
  133. // 处理成接口参数
  134. // 处理成数组对象
  135. if (table_node.length > 4) {
  136. if (table_boj.design_info.length) {
  137. // 一个商品的定制信息
  138. tables_arr.push(table_boj)
  139. // 重置
  140. table_boj = {
  141. good_info: null,
  142. sku_info: null,
  143. order_no: null,
  144. design_info: []
  145. }
  146. }
  147. table_boj = {
  148. good_info: table_node[1],
  149. sku_info: table_node[2],
  150. order_no: table_node[3],
  151. design_info: [{
  152. region: table_node[9],
  153. text: table_node[10],
  154. picture: table_node[11],//11
  155. cur_index: index + 1,
  156. }]
  157. }
  158. } else {
  159. table_boj.design_info.push({
  160. region: table_node[0],
  161. text: table_node[1],
  162. picture: table_node[2],//2
  163. cur_index: index + 1,
  164. })
  165. // 循环结束
  166. if (index == response.tables.length - 1) {
  167. if (table_boj.design_info.length) {
  168. // 一个商品的定制信息
  169. tables_arr.push(table_boj)
  170. }
  171. }
  172. }
  173. // good_info sku_info design_info: region text picture cur_index
  174. });
  175. console.log(tables_arr, "tables_arrddd")
  176. // 上传图片的参数处理
  177. let params_arr: any[] = []
  178. tables_arr.forEach(item => {
  179. // const sku_info = item.sku_info?.text?.split('SKU:')
  180. let order_no = ""
  181. if (item.order_no && item.order_no != "-") {
  182. order_no = item.order_no.substring(0, 15); // 取前15位
  183. }
  184. if (item.design_info.length) {
  185. item.design_info.forEach(design_item => {
  186. const prarm = {
  187. title: '',
  188. label: '',
  189. category_id: '',
  190. category_name: '',
  191. file: '',
  192. cur_index: ''
  193. };
  194. if (order_no && design_item.picture && design_item.picture != '-') {
  195. // const text = design_item.text.split('}')
  196. const bg_pic = (design_item.picture.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
  197. let bg_file = bg_pic.split('&imageMogr2/thumbnail/60x60')[0]
  198. prarm.title = `${order_no}-${design_item.region}`
  199. prarm.label = `${order_no}-${design_item.region}`
  200. prarm.file = bg_file ?? '';
  201. params_arr.push(prarm)
  202. }
  203. })
  204. }
  205. })
  206. console.log(params_arr, "params_arr")
  207. setTableData(params_arr)
  208. // 上传图片和文字的参数处理
  209. let pic_text_arr: any[] = []
  210. tables_arr.forEach(item => {
  211. let order_no = "", data_params: any[] = []
  212. if (item.order_no && item.order_no != "-") {
  213. order_no = item.order_no.substring(0, 15); // 取前15位
  214. }
  215. if (item.design_info.length) {
  216. item.design_info.forEach(items => {
  217. const param: any = {}
  218. if (order_no) {
  219. let bg_pic = ""
  220. if (items.picture && items.picture != '-') {
  221. let bg_pic1 = (items.picture.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
  222. bg_pic = bg_pic1.split('&imageMogr2/thumbnail/60x60')[0]
  223. } else {
  224. bg_pic = ""
  225. }
  226. let des_text = ""
  227. if (items.text && items.text != '-') {
  228. const des_text1 = items.text.split(";}")[1]
  229. des_text = des_text1.split("查看")[0]
  230. } else {
  231. des_text = ""
  232. }
  233. param['region'] = items.region
  234. param['text'] = des_text
  235. param['design_pic'] = bg_pic
  236. data_params.push(param)
  237. }
  238. })
  239. }
  240. if (order_no) {
  241. pic_text_arr.push({
  242. order_no,
  243. data_params
  244. })
  245. }
  246. })
  247. console.log(pic_text_arr, "pic_text_arr")
  248. // const table_arrs = response.tables // 表格数组
  249. // let i = 0, table_node = table_arrs[i], tables_arr = [];
  250. // let table_boj: {
  251. // good_info: any;
  252. // sku_info: any;
  253. // design_info: { region: any; text: any; picture: any }[];
  254. // } = {
  255. // good_info: null,
  256. // sku_info: null,
  257. // design_info: []
  258. // };
  259. // while (i < response.tables.length) {
  260. // // 长度大于4时,指针改变
  261. // if (table_node.length > 4) {
  262. // if (table_boj.design_info.length) {
  263. // // 一个商品的定制信息
  264. // tables_arr.push(table_boj)
  265. // // 重置
  266. // table_boj = {
  267. // good_info: null,
  268. // sku_info: null,
  269. // design_info: []
  270. // }
  271. // }
  272. // table_boj = {
  273. // good_info: table_node[1],
  274. // sku_info: table_node[2],
  275. // design_info: [{
  276. // region: table_node[9],
  277. // text: table_node[10],
  278. // picture: table_node[11],
  279. // }]
  280. // }
  281. // i++
  282. // table_node = table_arrs[i]
  283. // } else {
  284. // table_boj.design_info.push({
  285. // region: table_node[0],
  286. // text: table_node[1],
  287. // picture: table_node[2],
  288. // })
  289. // i++
  290. // table_node = table_arrs[i]
  291. // }
  292. // }
  293. } else {
  294. console.log("页面上未找到表格数据");
  295. }
  296. }
  297. } catch (error) {
  298. console.error("获取表格数据失败:", error);
  299. }
  300. };
  301. const uploadPic = () => {
  302. const token = localStorage.getItem("access_token");
  303. // 在此处添加下标索引参数
  304. const table_datas = tableData.map((item, index) => {
  305. item.cur_index = index + 1
  306. item.api_token = token
  307. return item
  308. })
  309. if (!uploadUrl) {
  310. Message.error("图片上传路径未获取到,请重新点击获取定制图片数据按钮")
  311. return
  312. }
  313. let fetch_url = "", arr_index = 0
  314. if (uploadUrl.includes('http')) {
  315. fetch_url = `${uploadUrl}sheInPhoto/upload`
  316. } else {
  317. fetch_url = `http:${uploadUrl}sheInPhoto/upload`
  318. }
  319. const fetch_fn = (data: any) => {
  320. const formData = new FormData()
  321. for (var key in data) {
  322. formData.append(key, data[key])
  323. }
  324. fetch(fetch_url, {
  325. method: 'POST',
  326. // headers: {
  327. // 'Content-Type': 'application/json',
  328. // },
  329. body: formData,
  330. mode: 'cors'
  331. }).then(resjson => {
  332. return resjson.json();
  333. }).then(res => {
  334. if (res.code == -1) {
  335. Message.error(res.msg)
  336. }
  337. arr_index++
  338. if (arr_index < table_datas.length) {
  339. fetch_fn(table_datas[arr_index])
  340. } else {
  341. // 上传完成
  342. Message.success(res.msg)
  343. setLoading(false)
  344. }
  345. }).catch(error => {
  346. setLoading(false)
  347. Message.error(error.message)
  348. arr_index++
  349. if (arr_index < table_datas.length) {
  350. fetch_fn(table_datas[arr_index])
  351. }
  352. })
  353. }
  354. console.log(table_datas, "table_datasss")
  355. setLoading(true)
  356. fetch_fn(table_datas[arr_index])
  357. // setTableData(tableData)
  358. }
  359. return (
  360. <Loading visible={loading} fullScreen>
  361. <div className='w-3xl h-fit'>
  362. <Button type="primary" style={{ marginBottom: '10px', marginRight: '10px' }}
  363. onClick={() => {
  364. getPicData()
  365. }}>获取定制图片数据</Button>
  366. <Button disabled={!tableData.length} type="primary" style={{ marginBottom: '10px', marginRight: '10px' }}
  367. onClick={() => {
  368. uploadPic()
  369. }}>上传图片</Button>
  370. <span className='text-red-500'>ps:上传图片过程中请勿关闭插件</span>
  371. <Table dataSource={dataSourceWithIndex}>
  372. <Table.Column title="图片" cell={pic_render} />
  373. <Table.Column title="图片名称" cell={name_render} />
  374. <Table.Column title="图片标签" cell={label_render} />
  375. <Table.Column title="文字" cell={text_render} />
  376. <Table.Column title="操作" cell={option_render} />
  377. </Table>
  378. </div>
  379. </Loading>
  380. )
  381. }