DesignPic.tsx 17 KB

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