DesignPic_20250813162307.tsx 13 KB

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