| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502 |
- import React, { useState } from 'react'
- import { Button, Table, Input, Message, Loading, Icon } from '@alifd/next';
- import '@alifd/next/dist/next.css'
- export default function DesignPic() {
- const [uploadUrl, setUploadUrl] = useState<string>("");
- // 添加状态管理表格数据
- const [tableData, setTableData] = useState<any[]>([]);
- const [loading, setLoading] = useState(false);
- const pic_render = (value: any, index: any, record: any) => {
- return (
- <>
- {
- record.file ? <>
- <img className='size-20' src={record.file}/></> : <>
- {/* <span>暂无图片</span> */}
- <Icon type="warning" />
- </>
- }
- </>
- );
- }
- const text_render = (value: any, index: any, record: any) => {
- return (
- <p>{record.text}</p>
- );
- }
- // 修改图片名称渲染函数
- const name_render = (value: any, index: number, record: any) => {
- return <>
- <div>{record.design_sku}</div>
- </>
- };
- // 修改图片标签渲染函数
- const label_render = (value: any, index: number, record: any) => {
- return <>
- <div>{record.region}</div>
- </>
- };
- // 完善删除功能
- const handleDelete = (index: number, record: any) => {
- // 方案1: 直接删除
- const newData = [...tableData];
- newData.splice(index, 1);
- setTableData(newData);
- // 方案2: 带确认的删除 (可选)
- // if (window.confirm(`确定要删除 "${record.title.name}" 吗?`)) {
- // const newData = [...tableData];
- // newData.splice(index, 1);
- // setTableData(newData);
- // Message.success('删除成功');
- // }
- };
- // 删除操作渲染函数
- const option_render = (value: any, index: number, record: any) => {
- return (
- <a
- className='text-red-600 cursor-pointer'
- onClick={() => handleDelete(index, record)}
- >
- 删除
- </a>
- );
- };
- // 添加行索引以确保正确删除
- const dataSourceWithIndex = tableData.map((item, index) => ({
- ...item,
- index
- }));
- const getPicData = async () => {
- try {
- setLoading(true)
- // 获取上传路径
- fetch('http://merchant.landwu.com/api/photo/getUploadUrl', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- api_token: localStorage.getItem('access_token'),
- }),
- }).then(resjson => {
- return resjson.json();
- }).then(res => {
- if (res.data) {
- const { data = {} } = res;
- const { url = null } = data;
- setUploadUrl(url)
- setLoading(false)
- }
- })
- // 获取当前活动标签页
- const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
- if (tab.id) {
- // 发送消息到content script请求获取tbody数据
- const response = await browser.tabs.sendMessage(tab.id, { action: "getTbodyData" });
- const table_datas = []
- // 在控制台输出结果
- if (response.tables && response.tables.length > 0) {
- console.log("找到的表格数据(包含背景图片):");
- // 显式声明类型
- let tables_arr: {
- good_info: any;
- sku_info: any;
- order_no: any;
- design_sku: any;
- design_info: { region: any; text: any; picture: any, cur_index: number }[];
- }[] = [];
- let table_boj: {
- good_info: any;
- sku_info: any;
- order_no: any;
- design_sku: any;
- design_info: { region: any; text: any; picture: any, cur_index: number }[];
- } = {
- good_info: null,
- sku_info: null,
- order_no: null,
- design_sku: null,
- design_info: []
- };
- response.tables.forEach((table_node: any, index: number) => {
- console.log(`表格 ${index + 1}:`, table_node);
- // 处理成接口参数
- // 处理成数组对象
- if (table_node.length > 4) {
- if (table_boj.design_info.length) {
- // 一个商品的定制信息
- tables_arr.push(table_boj)
- // 重置
- table_boj = {
- good_info: null,
- sku_info: null,
- order_no: null,
- design_sku: null,
- design_info: []
- }
- }
- table_boj = {
- good_info: table_node[1],
- sku_info: table_node[2],
- order_no: table_node[3],
- design_sku: table_node[4],
- design_info: [{
- region: table_node[9],
- text: table_node[10],
- picture: table_node[11],//11
- cur_index: index + 1,
- }]
- }
- } else {
- table_boj.design_info.push({
- region: table_node[0],
- text: table_node[1],
- picture: table_node[2],//2
- cur_index: index + 1,
- })
- // 循环结束
- if (index == response.tables.length - 1) {
- if (table_boj.design_info.length) {
- // 一个商品的定制信息
- tables_arr.push(table_boj)
- }
- }
- }
- // good_info sku_info design_info: region text picture cur_index
- });
- console.log(tables_arr, "tables_arrddd")
- // 上传图片的参数处理
- // let params_arr: any[] = []
- // tables_arr.forEach(item => {
- // // const sku_info = item.sku_info?.text?.split('SKU:')
- // let order_no = ""
- // if (item.order_no && item.order_no != "-") {
- // order_no = item.order_no.substring(0, 15); // 取前15位
- // }
- // if (item.design_info.length) {
- // item.design_info.forEach(design_item => {
- // const prarm = {
- // title: '',
- // label: '',
- // category_id: '',
- // category_name: '',
- // file: '',
- // cur_index: ''
- // };
- // if (order_no && design_item.picture && design_item.picture != '-') {
- // // const text = design_item.text.split('}')
- // const bg_pic = (design_item.picture.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
- // let bg_file = bg_pic.split('&imageMogr2/thumbnail/60x60')[0]
- // prarm.title = `${order_no}-${design_item.region}`
- // prarm.label = `${order_no}-${design_item.region}`
- // prarm.file = bg_file ?? '';
- // params_arr.push(prarm)
- // }
- // })
- // }
- // })
- // console.log(params_arr, "params_arr")
- // setTableData(params_arr)
- // 上传图片和文字的参数处理
- let pic_text_arr: any[] = []
- tables_arr.forEach(item => {
- let order_no = "", data_params: any[] = []
- if (item.order_no && item.order_no != "-") {
- order_no = item.order_no.substring(0, 15); // 取前15位
- }
- if (item.design_info.length) {
- item.design_info.forEach(items => {
- const param: any = {}
- if (order_no || item.design_sku) {
- let bg_pic = ""
- if (items.picture && items.picture != '-') {
- let bg_pic1 = (items.picture.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
- bg_pic = bg_pic1.split('&imageMogr2/thumbnail/60x60')[0]
- } else {
- bg_pic = ""
- }
- let des_text = ""
- if (items.text && items.text != '-') {
- const des_text1 = items.text.split(";}")[1]
- des_text = des_text1.split("查看")[0]
- } else {
- des_text = ""
- }
- param['region'] = items.region
- param['text'] = des_text
- param['design_pic'] = bg_pic
- data_params.push(param)
- }
- })
- }
- if (order_no || item.design_sku) {
- pic_text_arr.push({
- order_no,
- design_sku: item.design_sku,
- data_params
- })
- }
- })
- console.log(pic_text_arr, "pic_text_arr")
- // const params = {...pic_text_arr[0],api_token: localStorage.getItem('access_token')}
- // console.log(params,"params")
- // fetch(`http:${uploadUrl}photo/temuUpload `, {
- // method: 'POST',
- // headers: {
- // 'Content-Type': 'application/json',
- // },
- // body: JSON.stringify(params),
- // }).then(resjson => {
- // return resjson.json();
- // }).then(res => {
- // if (res.data) {
- // }
- // })
- // 数据显示
- let table_data: any[] = []
- pic_text_arr.forEach(item => {
- if (item.data_params.length) {
- item.data_params.forEach((items: any) => {
- table_data.push({
- order_no: item.order_no,
- design_sku: item.design_sku,
- file: items.design_pic,
- region: items.region,
- text: items.text,
- })
- })
- }
- })
- setTableData(table_data)
- // const table_arrs = response.tables // 表格数组
- // let i = 0, table_node = table_arrs[i], tables_arr = [];
- // let table_boj: {
- // good_info: any;
- // sku_info: any;
- // design_info: { region: any; text: any; picture: any }[];
- // } = {
- // good_info: null,
- // sku_info: null,
- // design_info: []
- // };
- // while (i < response.tables.length) {
- // // 长度大于4时,指针改变
- // if (table_node.length > 4) {
- // if (table_boj.design_info.length) {
- // // 一个商品的定制信息
- // tables_arr.push(table_boj)
- // // 重置
- // table_boj = {
- // good_info: null,
- // sku_info: null,
- // design_info: []
- // }
- // }
- // table_boj = {
- // good_info: table_node[1],
- // sku_info: table_node[2],
- // design_info: [{
- // region: table_node[9],
- // text: table_node[10],
- // picture: table_node[11],
- // }]
- // }
- // i++
- // table_node = table_arrs[i]
- // } else {
- // table_boj.design_info.push({
- // region: table_node[0],
- // text: table_node[1],
- // picture: table_node[2],
- // })
- // i++
- // table_node = table_arrs[i]
- // }
- // }
- } else {
- console.log("页面上未找到表格数据");
- }
- }
- } catch (error) {
- console.error("获取表格数据失败:", error);
- }
- };
- const uploadPic = () => {
- const token = localStorage.getItem("access_token");
- console.log(tableData, "tableData")
- let table_obj: { [key: string]: any } = {};
- tableData.forEach(item => {
- if (table_obj[item.design_sku]) {
- const data_params = table_obj[item.design_sku].data_params
- data_params.push({
- design_pic: item.file,
- region: item.region,
- text: item.text
- })
- table_obj[item.design_sku] = {
- ...table_obj[item.design_sku],
- data_params,
- }
- } else {
- table_obj[item.design_sku] = {
- order_no: item.order_no,
- design_sku: item.design_sku,
- data_params: [{
- design_pic: item.file,
- region: item.region,
- text: item.text
- }]
- }
- }
- })
- console.log(table_obj, "table_obj", Object.values(table_obj))
- const table_params = Object.values(table_obj)
- let fetch_url = "", arr_index = 0
- if (uploadUrl.includes('http')) {
- fetch_url = `${uploadUrl}photo/temuUpload`
- } else {
- fetch_url = `http:${uploadUrl}photo/temuUpload`
- }
- const FetchFun = (params: any) => {
- console.log(params, "params")
- params['api_token'] = token
- fetch(fetch_url, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(params),
- }).then(resjson => {
- return resjson.json();
- }).then(res => {
- if (res.data.error && res.data.error.length) {
- // 未上传成功的 图片
- console.log(res.data.error, "arr_index", arr_index)
- }
- arr_index++
- if (arr_index < table_params.length) {
- FetchFun(table_params[arr_index])
- } else {
- setLoading(false)
- Message.success("图片上传结束")
- }
- }).catch(err => {
- console.log(err, "err")
- arr_index++
- if (arr_index < table_params.length) {
- FetchFun(table_params[arr_index])
- } else {
- setLoading(false)
- Message.success("图片上传结束")
- }
- })
- }
- setLoading(true)
- FetchFun(table_params[arr_index])
- return
- // 在此处添加下标索引参数
- const table_datas = tableData.map((item, index) => {
- item.cur_index = index + 1
- item.api_token = token
- return item
- })
- if (!uploadUrl) {
- Message.error("图片上传路径未获取到,请重新点击获取定制图片数据按钮")
- return
- }
- const fetch_fn = (data: any) => {
- const formData = new FormData()
- for (var key in data) {
- formData.append(key, data[key])
- }
- fetch(fetch_url, {
- method: 'POST',
- // headers: {
- // 'Content-Type': 'application/json',
- // },
- body: formData,
- mode: 'cors'
- }).then(resjson => {
- return resjson.json();
- }).then(res => {
- if (res.code == -1) {
- Message.error(res.msg)
- }
- arr_index++
- if (arr_index < table_datas.length) {
- fetch_fn(table_datas[arr_index])
- } else {
- // 上传完成
- Message.success(res.msg)
- setLoading(false)
- }
- }).catch(error => {
- setLoading(false)
- Message.error(error.message)
- arr_index++
- if (arr_index < table_datas.length) {
- fetch_fn(table_datas[arr_index])
- }
- })
- }
- console.log(table_datas, "table_datasss")
- setLoading(true)
- fetch_fn(table_datas[arr_index])
- // setTableData(tableData)
- }
- return (
- <Loading visible={loading} fullScreen>
- <div className='w-3xl h-fit'>
- <Button type="primary" style={{ marginBottom: '10px', marginRight: '10px' }}
- onClick={() => {
- getPicData()
- }}>获取定制数据</Button>
- <Button disabled={!tableData.length} type="primary" style={{ marginBottom: '10px', marginRight: '10px' }}
- onClick={() => {
- uploadPic()
- }}>上传定制信息</Button>
- <span className='text-red-500'>ps:上传图片过程中请勿关闭插件</span>
- <Table dataSource={dataSourceWithIndex}>
- <Table.Column title="图片" cell={pic_render} />
- <Table.Column title="定制SKU" cell={name_render} />
- <Table.Column title="定制区域" cell={label_render} />
- <Table.Column title="文字" cell={text_render} />
- <Table.Column title="操作" cell={option_render} />
- </Table>
- </div>
- </Loading>
- )
- }
|