Commit 8fdf6f3e authored by 刘燕芳's avatar 刘燕芳

通信

parent 4e86efe9
......@@ -27,8 +27,7 @@
"matches": [
"*://myseller.taobao.com/*",
"*://admin.rtxmdz.com/*",
"http://localhost:8082/*",
"http://localhost:8083/*",
"http://localhost:10823/*",
"*://*.rtxmdz.com/*"
],
"js": ["content.js"],
......
......@@ -9,67 +9,18 @@ const PlatfromsMap = new Map([
[2, /.+:\/\/jd.*\.fahuoyi.com\/scanPrinting\/index/]
])
let monitoringRemoveTabId = new Map();
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.action === StartPrint) {
// console.log("startPrint")
// 通知fahuoyi的content开始点击
chrome.tabs.query({
url: "*://*.fahuoyi.com/scanPrinting/index"
}, function (tabs) {
let exp = new RegExp(PlatfromsMap.get(message.value.platform)!, 'i')
console.log(tabs, 'tabs66')
tabs && tabs.forEach(tab => {
if (exp.test(tab.url!)) {
chrome.tabs.sendMessage(tab.id!, { action: Print, value: message.value })
}
})
// // sendResponse("")
// if (tabs[0]) {
// chrome.tabs.sendMessage(tabs[0].id!, { action: Print, value: message.value })
// }
})
chrome.tabs.query({
url: "*://*.fahuoyi.com/features/scanPrinting"
}, function (tabs) {
console.log(tabs, 'tabs11')
tabs && tabs.forEach(tab => {
chrome.tabs.executeScript(tab.id!, {code: 'console.log(window["scan-printing-form"])'});
})
})
} else if (message.action === "sendNewWaybillNo") {
// 从bg页面转发给厂家页面的content.js
chrome.tabs.query({
url: factoryContentUrls
}, function (tabs) {
tabs && tabs.forEach(tab => {
// chrome.tabs.sendMessage(tab.id!, message)
const port = chrome.tabs.connect(tab.id!, { name: "sendNewWaybillNo" })
port.onMessage.addListener(function (msg, port) {
if (msg.action === "answer") {
// console.log(msg, port, 'bg')
port.disconnect()
}
})
port.postMessage(message)
})
})
// let port = chrome.runtime.connect({ name: "bgSendMessage" })
// port.postMessage(message)
}else if (message.action === ACTION.task) {
let result_sendResponse:boolean = false
chrome.runtime.onMessage.addListener(async function (message, sender, sendResponse) {
if (message.action === ACTION.task) {
// 从bg页面转发给厂家页面的content.js
chrome.tabs.query({
url: bookingV2Urls
}, function (tabs) {
tabs && tabs.forEach(tab => {
// chrome.tabs.sendMessage(tab.id!, message)
chrome.tabs.update(tab.id!, { active: true}, function(tab1) {});
chrome.tabs.sendMessage(tab.id!, { action: ACTION.task, value: message.value },res=>{
console.log(3333,res,tab,new Date());
if(res){
sendResponse(res);
chrome.tabs.update(sender.tab!.id!, { active: true}, function(tab1) {});
......@@ -77,84 +28,117 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
})
})
if(tabs.length==0){
alert('请打开新版发货易发货页面')
sendResponse({status:1,msg:"请打开新版发货易发货页面"});
alert('请打开千牛商家工作台')
sendResponse({status:1,msg:"请打开千牛商家工作台"});
}
chrome.storage.sync.get("tb_user",function(res){
let userData = res.tb_user
if (userData == null) {
alert('请登录千牛商家工作台')
sendResponse({status:1,msg:"请登录千牛商家工作台"});
}
})
})
// let port = chrome.runtime.connect({ name: "bgSendMessage" })
// port.postMessage(message)
}else if(message.action==='getUserLoginData'){
getUserLoginData()
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
//加载完毕后在执行一些动作
if (tab.status== "complete") {
//如果进入了千牛首页 则开始获取对应的数据信息
if(tab.url&&tab.url.indexOf("loginmyseller.taobao.com") != -1){
chrome.storage.sync.remove("tb_user")
sendResponse();
return
}
if (tab.url&&tab.url.indexOf("myseller.taobao.com/home.htm/QnworkbenchHome") != -1) {
let userNickCookie:any = await getCookies(tab.url, "sn");
if (userNickCookie === null || userNickCookie === undefined || userNickCookie === "") userNickCookie = await getCookies(tab.url, "_nk_");
console.log('userNickCookie',userNickCookie);
if (userNickCookie === null || userNickCookie === undefined) {
chrome.storage.sync.remove("tb_user")
sendResponse();
return
};
let tuDe1 = decodeURI(userNickCookie.value);
let tuDe2 = unescape(tuDe1.replace(/\\(u[0-9a-fA-F]{4})/gm, '%$1'));
if (tuDe2.indexOf(":") != -1) tuDe2 = tuDe2.split(":")[0];
let createUrl = isTm(tuDe2) ? tmIssueUrl : tbIssueUrl;
let tabId = await createTab(createUrl);
monitoringRemoveTabId.set(tabId, tuDe2);
}
if (tab.url&&(tab.url.indexOf("item.upload.taobao.com/sell/merge") != -1 || tab.url.indexOf("sell.publish.tmall.com/tmall/smart") != -1)) {
if (monitoringRemoveTabId.has(tab.id)) {
let userNick:string = monitoringRemoveTabId.get(tab.id);
let cookie = await getCookieAll(tab.url);
let token:any = await getCookies(tab.url, "XSRF-TOKEN");
let userData:object = {
cookie:cookie,
token: token.value,
userNick: userNick,
}
console.log("user data :", userData,new Date().getMinutes(),new Date().getSeconds());
// let serverNum = SoketDispatchManage.hosts[config.evn].length;
// if (SoketDispatchManage.userNick == null || SoketDispatchManage.userNick != userData.userNick || SoketDispatchManage.getActiveConnectNum() != serverNum) {
// //与服务器建立webSocket连接 后续与服务器通信将依赖此链接
// SoketDispatchManage.connection(userData.userNick);
// if (SoketDispatchManage.getActiveConnectNum() <= 0) {
// console.log("socket未连接至任何服务器!")
// }
// }
let id:any = tab.id
chrome.storage.sync.set({"tb_user":JSON.stringify(userData)})
sendResponse();
}else{
console.log(222,new Date().getMinutes(),new Date().getSeconds());
chrome.storage.sync.remove("tb_user")
sendResponse();
}
}
if(monitoringRemoveTabId.has(tab.id)){
let id:any = tab.id
chrome.tabs.remove(id);
}
}
})
await getUserLoginData()
sendResponse()
}
return true;
})
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
console.log('tab',tab);
//加载完毕后在执行一些动作
if (tab.status== "complete") {
//如果进入了千牛首页 则开始获取对应的数据信息
if(tab.url&&tab.url.indexOf("loginmyseller.taobao.com") != -1){
if(monitoringRemoveTabId.has(tab.id)){
let id:any = tab.id
chrome.tabs.remove(id);
}
chrome.storage.sync.remove("tb_user")
result_sendResponse=true;
return
}
if (tab.url&&tab.url.indexOf("myseller.taobao.com/home.htm/QnworkbenchHome") != -1) {
let userNickCookie:any = await getCookies(tab.url, "sn");
if (userNickCookie === null || userNickCookie === undefined || userNickCookie === "") userNickCookie = await getCookies(tab.url, "_nk_");
console.log('userNickCookie',userNickCookie);
if (userNickCookie === null || userNickCookie === undefined) {
chrome.storage.sync.remove("tb_user")
result_sendResponse=true;
return
};
let tuDe1 = decodeURI(userNickCookie.value);
let tuDe2 = unescape(tuDe1.replace(/\\(u[0-9a-fA-F]{4})/gm, '%$1'));
if (tuDe2.indexOf(":") != -1) tuDe2 = tuDe2.split(":")[0];
let createUrl = isTm(tuDe2) ? tmIssueUrl : tbIssueUrl;
let tabId = await createTab(createUrl);
monitoringRemoveTabId.set(tabId, tuDe2);
}
if (tab.url&&(tab.url.indexOf("item.upload.taobao.com/sell/merge") != -1 || tab.url.indexOf("sell.publish.tmall.com/tmall/smart") != -1)) {
if (monitoringRemoveTabId.has(tab.id)) {
let userNick:string = monitoringRemoveTabId.get(tab.id);
let cookie = await getCookieAll(tab.url);
let token:any = await getCookies(tab.url, "XSRF-TOKEN");
let userData:object = {
cookie:cookie,
token: token.value,
userNick: userNick,
}
console.log("user data :", userData,new Date().getMinutes(),new Date().getSeconds());
// let serverNum = SoketDispatchManage.hosts[config.evn].length;
// if (SoketDispatchManage.userNick == null || SoketDispatchManage.userNick != userData.userNick || SoketDispatchManage.getActiveConnectNum() != serverNum) {
// //与服务器建立webSocket连接 后续与服务器通信将依赖此链接
// SoketDispatchManage.connection(userData.userNick);
// if (SoketDispatchManage.getActiveConnectNum() <= 0) {
// console.log("socket未连接至任何服务器!")
// }
// }
let id:any = tab.id
chrome.storage.sync.set({"tb_user":JSON.stringify(userData)})
result_sendResponse=true;
}else{
// console.log(222,new Date().getMinutes(),new Date().getSeconds());
chrome.storage.sync.remove("tb_user")
result_sendResponse=true;
}
}
if(monitoringRemoveTabId.has(tab.id)){
let id:any = tab.id
chrome.tabs.remove(id);
}
}
})
async function getUserLoginData(){
result_sendResponse = false
let tabId = await createTab(homeUrl);
monitoringRemoveTabId.set(tabId, "");
await newTab()
return new Promise<void>((resolve, reject) => {
resolve()
})
}
function newTab(){
return new Promise<void>((resolve, reject) => {
if(result_sendResponse){
resolve()
}else{
setTimeout(() => {
newTab()
},500);
}
})
}
async function createTab(url:string) {
......
let domEle = {
divNav:document.getElementsByClassName("nav-link") as HTMLCollection,
inputOrderId: "#originalIds",
btnSearch: "#root > section > main > div > div > div > div.order-main > div.order-table-container > div.order-search-pane > div > div > div:nth-child(2) > button:nth-child(2)",
checkBoxSelectAll: "div.bottom-operation-bar > span input.ant-checkbox-input",
btnPrint: ".ec-print-waybill-button",
modalTips:"ant-modal-confirm-title",
btnTipsConfirm:"div.ant-modal-confirm-body-wrapper > div > button.ant-btn-primary",
spanWaybillTemplate: ():any=>document.getElementsByClassName("ant-modal-body")[0].getElementsByClassName("ant-select-selector")[0] ,
divWaybillTemplateList: ():any=>document.getElementsByClassName("rc-virtual-list-holder-inner")[0] ,
radioGetNewWaybill: ():any=>document.querySelector(".ant-modal-body input.ant-radio-input") ,
inputWaybillNoOnly: ():any=>document.querySelector("#isGenerateWaybillNoOnly") ,
btnDialogPrint: ():any=>document.querySelector("div.ant-modal-footer button"),
modalResult: "#printEwaybillResultDialog",
tableResult: ():any=>document.querySelector("#ewaybill-result-table > div > div.ant-table-body > table"),
btnClose: ():any=>document.querySelector("div.ant-modal-footer button:nth-child(3)") ,
btnDeliver: ():any=>document.querySelector("div.ant-modal-footer button:nth-child(2)") ,
deliverResult:():any=>document.querySelector(".ant-modal-body>div.ant-table-wrapper .ant-table-tbody"),
deliverClose: ():any=>document.querySelector("div.ant-modal-footer button") ,
}
import { bookingV2Urls } from "../config";
async function booking(info: any) {
return ;
}
async function waitOrder() {
let result = {
status: 4,
msg: "获取订单超时",
data: [],
}
for (let i = 0; i < 10; i++) {
await delayDate(1000);
let loadingMask = document.querySelector("#root > section > main > div > div > div > div.order-main > div.order-table-container > div.loading-mark-container > div") as any;
if (loadingMask.style.display=="none" ) {
if (document.querySelector("#root > section > main > div > div > div > div.order-main > div.order-table-container > div.loading-mark-container > table > tbody > tr > td > div > div.mb10 > p")) {
//无订单
result.status = 2;
result.msg = "无相关订单"
return result;
} else {
result.status = 0;
result.msg = ""
return result;
}
}
}
return result;
}
async function waitDialog() {
let result = {
status: 4,
msg: "获取打印按钮超时",
data: [],
}
for (let i = 0; i < 10; i++) {
await delayDate(1000);
if (document.getElementsByClassName("ant-modal-content").length) {
result.status = 0;
result.msg = ""
return result;
}
}
return result;
}
async function waitPrintResult() {
let result = {
status: 4,
msg: "获取打印结果超时",
data: [],
}
for (let i = 0; i < 10; i++) {
await delayDate(1000);
if (domEle.tableResult()) {
result.status = 0;
result.msg = ""
return result;
}
}
return result;
}
function delayDate(time: number) {
console.log(2222);
let data:object = { catId: 150704, jsonBody: info}
return new Promise((resolve, reject) => {
setTimeout(() => {
//console.log(‘开始执行‘)
resolve("success");
}, time);
});
}
function changeReactInputValue(inputDom:any,newText:string){
let lastValue = inputDom.value;
inputDom.value = newText;
let event = new Event('input', { bubbles: true });
// @ts-ignore
event.simulated = true;
let tracker = inputDom._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
inputDom.dispatchEvent(event);
}
const mouseClickEvents = ['mousedown', 'click', 'mouseup'];
function simulateMouseClick(element:any){
mouseClickEvents.forEach(mouseEventType =>
element.dispatchEvent(
new MouseEvent(mouseEventType, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1
fetch("https://item.upload.taobao.com/sell/v2/submit.htm", { method: "POST",body:JSON.stringify(data) }).then(res => {
console.log('fetch 111',res);
resolve(res)
})
)
);
})
}
export default {
booking
}
\ No newline at end of file
......@@ -6,16 +6,24 @@ import { message } from "antd";
import { ACTION, Print, StartPrint } from "../types";
import BookingV2 from "./bookingV2"
type Params = {
a: number // 运单号
b: number
}
interface Message {
action: "Print",
value: Params
}
// web页面通信
window.addEventListener("message",function(message:any){
console.log('web页面通信',message);
console.log('web页面通信1',message,new Date());
if(message.data.action == ACTION.task){
chrome.runtime.sendMessage(message.data,(ret)=>{
// window.postMessage({isResult:1,...ret},"*")
console.log("message ret:",ret,message.data);
console.log(2222,ret);
window.postMessage({isResult:1,...ret},"*")
console.log("message ret:1",ret,message.data);
})
}
})
......@@ -37,10 +45,10 @@ chrome.runtime.onMessage.addListener(function (message, sender, response) {
* 发货易content
*/
window.addEventListener("message", function (msg) {
console.log('发货易content',msg);
// window.addEventListener("message", function (msg) {
// console.log('发货易content',msg,new Date());
})
// })
import React, { useState, useCallback, useEffect } from "react";
import { Select, Button } from "antd";
import "./index.scss";
const { Option } = Select
export interface IwaybillTemplate {
name: string,
value: string
}
interface Item {
wayCompanyId: string | undefined,
waybillTemplateList: (string | undefined)[]
printId: string | undefined
}
type List = Item[]
//
const AllWayCompany = [
{ name: "圆通速递", value: "YTO" }
, { name: "申通快递", value: "STO" }
, { name: "中通快递", value: "ZTO" }
, { name: "韵达快递", value: "YUNDA" }
, { name: "顺丰速运", value: "SF" }
, { name: "百世快递", value: "HTKY" }
, { name: "EMS", value: "EMS" }
, { name: "EMS经济快递", value: "EYB" }
, { name: "邮政标准快递", value: "DISTRIBUTOR_1715055" }
, { name: "邮政快递包裹", value: "POSTB" }
, { name: "中国邮政", value: "POST" }
, { name: "京东快递", value: "EX_JD_EXPRESS" }
, { name: "天天快递", value: "TTKDEX" }
, { name: "国通快递", value: "GTO" }
, { name: "安能快递(小包)", value: "DISTRIBUTOR_12017865" }
, { name: "安能物流", value: "ANE56" }
, { name: "全峰快递", value: "QFKD" }
, { name: "联邦快递", value: "FEDEX" }
, { name: "德邦快递", value: "DBKD" }
, { name: "德邦物流", value: "DBL" }
, { name: "宅急送", value: "ZJS" }
, { name: "优速快递", value: "UC" }
, { name: "龙邦速递", value: "LB" }
, { name: "亚风", value: "AIR" }
, { name: "天地华宇", value: "HOAU" }
, { name: "速尔快运", value: "SURE" }
, { name: "大田", value: "DTW" }
, { name: "保宏物流", value: "BHWL" }
, { name: "发网", value: "UNIPS" }
, { name: "长发", value: "YUD" }
, { name: "长宇", value: "CYEXP" }
, { name: "远长", value: "YC" }
, { name: "东方汇", value: "DFH" }
, { name: "飞远配送 ", value: "GZLT" }
, { name: "派易国际物流77", value: "PKGJWL" }
, { name: "信丰物流", value: "XFWL" }
, { name: "飞远(爱彼西)配送", value: "HZABC" }
, { name: "华强物流", value: "SHQ" }
, { name: "百世物流", value: "BEST" }
, { name: "新邦物流", value: "XB" }
, { name: "美国速递", value: "MGSD" }
, { name: "远成快运", value: "YCKY" }
, { name: "品骏快递", value: "PJBEST" }
, { name: "苏宁物流", value: "DISTRIBUTOR_13452378" }
, { name: "WnDirect", value: "WND" }
, { name: "能达速递", value: "NEDA" }
, { name: "黑猫宅急便", value: "YCT" }
, { name: "D速物流", value: "DISTRIBUTOR_13460212" }
, { name: "联昊通", value: "LTS" }
, { name: "E速宝", value: "ESB" }
, { name: "佳吉快递", value: "CNEX" }
, { name: "广东EMS", value: "GDEMS" }
, { name: "增益速递", value: "QRT" }
, { name: "全一快递", value: "UAPEX" }
, { name: "快捷快递", value: "FAST" }
, { name: "中铁快运", value: "CRE" }
, { name: "速通物流", value: "EX_SUT56" }
, { name: "顺丰快运", value: "EX_SFKY" }
, { name: "速腾快递", value: "EX_STE56" }
, { name: "顺心捷达", value: "DISTRIBUTOR_13484485" }
, { name: "宽昊物流", value: "EX_KHWL" }
, { name: "都市节奏", value: "EX_DSJZ" }
, { name: "众邮快递", value: "EX_ZYKD" }
, { name: "京东快运", value: "EX_JDKY" }
, { name: "DN快递", value: "EX_TOPSPEED_DN" }
, { name: "九曳供应链", value: "DISTRIBUTOR_13323734" }
, { name: "重庆华宇物流", value: "EX_CQHY" }
, { name: "极兔速递", value: "EX_JTSD" }
, { name: "丹鸟", value: "DISTRIBUTOR_13503931" }
, { name: "如风达配送", value: "BJRFD-001" }
, { name: "韵达点通达", value: "EX_YUNDA_DTD" }
, { name: "壹米滴答", value: "YMDD" }
, { name: "百世国际", value: "DISTRIBUTOR_13433751" }
, { name: "安迅物流", value: "DISTRIBUTOR_13365751" }
, { name: "承诺达特快", value: "DISTRIBUTOR_13469985" }
, { name: "沃埃家", value: "EX_WOWVIP" }
, { name: "京广速递", value: "EX_SZKKE" }
, { name: "鸿昌物流", value: "EX_HC" }
, { name: "华企快运", value: "EX_HUAQIEX" }
, { name: "中骅物流", value: "EX_CHUNGHWA56" }
, { name: "百世快运", value: "BESTQJT" }
, { name: "运通速运", value: "WTO" }
, { name: "中通快运", value: "DISTRIBUTOR_13222803" }
, { name: "菜鸟大件-日日顺配", value: "DISTRIBUTOR_13159132" }
, { name: "安世通快递", value: "DISTRIBUTOR_13415300" }
, { name: "百世云配", value: "DISTRIBUTOR_13468073" }
, { name: "韵达快运", value: "DISTRIBUTOR_13421750" }
, { name: "中通国际直邮", value: "DISTRIBUTOR_13196453" }
, { name: "京东大件开放承运商", value: "EX_JD_HPCP" }
, { name: "加运美速递", value: "DISTRIBUTOR_13468074" }
, { name: "中运全速", value: "EX_TOPSPEED" }
, { name: "其他", value: "OTHER" }
, { name: "跨越速运", value: "DISTRIBUTOR_13211725" }
, { name: "菜鸟大件-中铁配", value: "DISTRIBUTOR_13148625" }
]
const PlatformsMap = new Map([
[0, /.+:\/\/a.*\.fahuoyi.com\//],
[1, /.+:\/\/pdd.*\.fahuoyi.com\//],
[2, /.+:\/\/jd.*\.fahuoyi.com\//]
])
const WayBillModel = function () {
const [list, setList] = useState<List>([])
const [AWaybillTemplate, setAWaybillTemplate] = useState<IwaybillTemplate[]>([])
const [PDDWaybillTemplate, setPDDWaybillTemplate] = useState<IwaybillTemplate[]>([])
const [JDWaybillTemplate, setJDWaybillTemplate] = useState<IwaybillTemplate[]>([])
const [printList, setPrintList] = useState<string[]>([])
const setMap = new Map([
[0, setAWaybillTemplate],
[1, setPDDWaybillTemplate],
[2, setJDWaybillTemplate]
])
const getMap = new Map([
[0, AWaybillTemplate],
[1, PDDWaybillTemplate],
[2, JDWaybillTemplate]
])
// 获取发货易快递模板列表
const getWaybillTemplate = useCallback(async () => {
chrome.tabs.query({
url: "*://*.fahuoyi.com/scanPrinting/index"
}, async function (tabs) {
let platformUrls: string[] = []
for (let value of PlatformsMap.values()) {
let prefixUrl: string;
tabs.forEach(tab => {
console.log(value.test(tab.url!))
if (tab.url && value.test(tab.url!)) {
prefixUrl = tab.url.match(value)![0]
console.log(prefixUrl, 'url')
}
})
platformUrls.push(prefixUrl!)
console.log(platformUrls, 'platformUrls')
}
for (let index in platformUrls) {
let prefix = platformUrls[index]
console.log(prefix, 'prefix')
let data = prefix ? await fetch(prefix + "waybillTemplate/listRest?_=" + new Date().getTime(), { method: "GET" }).then(res => {
console.log("2")
return res.json()
}) : []
console.log("3")
console.log(data, 'data')
setMap.get(Number(index))!(pre => {
// @ts-ignore
return data.map(dataItem => ({
name: dataItem.name,
value: dataItem.id
}))
})
}
})
}, [])
const getPrintList = useCallback(async () => {
chrome.tabs.query({
url: "*://*.fahuoyi.com/scanPrinting/index"
}, async function (tabs) {
if (tabs.length >= 1) {
let port = chrome.tabs.connect(tabs[0].id!, { name: "getPrinter" });
port.postMessage({ action: "getPrint" })
port.onMessage.addListener(function (msg) {
setPrintList(msg)
})
}
})
}, [])
useEffect(() => {
getWaybillTemplate()
getPrintList()
chrome.storage.local.get({ list: [{ wayCompanyId: undefined, waybillTemplateList: [undefined, undefined, undefined], printId: undefined }] }, function (res) {
if (res.list.length === 0) {
chrome.storage.local.set({ list: [{ wayCompanyId: undefined, waybillTemplateList: [undefined, undefined, undefined], printId: undefined }] }, function () {
setList([{ wayCompanyId: undefined, waybillTemplateList: [undefined, undefined, undefined], printId: undefined }])
})
} else {
setList(res.list as List)
}
})
}, [])
useEffect(() => {
chrome.storage.local.set({ list: list })
}, [list])
const onChangeWayCompany = useCallback((value: string, wayIndex: number) => {
setList(pre => {
const newList = [...pre]
newList[wayIndex].wayCompanyId = value
return newList;
})
}, [])
const onChangeWayTemplate = useCallback((e: string, wayIndex: number, tempIndex: number) => {
setList(pre => {
const newList = [...pre]
newList[wayIndex].waybillTemplateList[tempIndex] = e;
return newList
})
}, [])
const onChangePrint = useCallback((e: string, wayIndex: number) => {
setList(pre => {
const newList = [...pre]
newList[wayIndex].printId = e;
return newList;
})
}, [])
// 新增快递
const handleAddWay = useCallback(() => {
setList(pre => {
const newState = [...pre]
newState.push({ wayCompanyId: undefined, waybillTemplateList: [undefined, undefined, undefined], printId: undefined })
return newState;
})
}, [])
// 删除
const remove = useCallback((index: number) => {
setList(pre => {
const newState = [...pre]
newState.splice(index, 1)
return newState
})
}, [])
return (
<>
<div className="waybill-model">
<span className="waybill-model-title" key="one">选择快递</span>
<span className="waybill-model-title" key="two">选择淘系及其他平台订单模板</span>
<span className="waybill-model-title" key="three">选择拼多多订单模板</span>
<span className="waybill-model-title" key="four">选择京东订单模板</span>
<span className="waybill-model-print" key="seven">打印机</span>
<span className="waybill-model-title" key="five">操作</span>
{
list.map((item, wayIndex) => {
return <>
<Select
showSearch
key={ wayIndex + "wayCompany" }
style={ { width: 150 } }
placeholder="请选择快递"
optionFilterProp="children"
onChange={ (value) => onChangeWayCompany(value, wayIndex) }
value={ item.wayCompanyId }
>
{
AllWayCompany.map((item, index) => {
return <Option key={ index } value={ item.value }>{ item.name }</Option>
})
}
</Select>
{
item.waybillTemplateList.map((item, tempIndex) => {
return <Select
key={ tempIndex + "wayTemplate" }
showSearch
style={ { width: 150 } }
placeholder="选择快递模板"
optionFilterProp="children"
onChange={ (value) => onChangeWayTemplate(value, wayIndex, tempIndex) }
value={ item }
>
{
getMap.get(tempIndex)!.map((item, index) => {
return <Option key={ index } value={ item.value }>{ item.name }</Option>
})
}
</Select>
})
}
<Select
key={ item.printId + 'print' }
showSearch
style={ { width: 150 } }
placeholder="选择打印机"
optionFilterProp="children"
onChange={ (value) => onChangePrint(value, wayIndex) }
value={ item.printId }
>
{
printList.map((item, index) => {
return <Option key={ index } value={ item }>{ item }</Option>
})
}
</Select>
<Button type="default" key={ item.printId + "btn" } style={ { padding: "0 5px" } } onClick={ () => remove(wayIndex) }>删除</Button>
</>
})
}
</div>
<Button type="link" onClick={ handleAddWay }>新增快递</Button>
</>
)
}
export default WayBillModel
\ No newline at end of file
......@@ -4,4 +4,7 @@
overflow-y: auto;
overflow-x: hidden;
margin-left: 10px;
}
.btn{
margin: 10px 0 0 10px;
}
\ No newline at end of file
......@@ -7,6 +7,7 @@ interface User {
cookie:string,
token:string
}
let initTime = 0
const WayBillModel = function () {
// 当前是否连接成功
const [link,setLink] = useState<boolean>(false)
......@@ -18,6 +19,8 @@ const WayBillModel = function () {
cookie:'',
token:''
})
// 刷新时候的状态
const [loading,setLoading] = useState<boolean>(false)
// 获取发货易快递模板列表
const getLogin = useCallback(async () => {
chrome.tabs.query({
......@@ -43,7 +46,6 @@ const WayBillModel = function () {
// 获取用户信息
chrome.storage.sync.get("tb_user",function(res){
console.log(res);
let userData = res.tb_user
if (userData == null) {
setIsLogin(false)
......@@ -61,6 +63,9 @@ const WayBillModel = function () {
// 刷新连接状态
const refresh = useCallback(() => {
if(initTime>0)return
setLoading(true)
initTime++
getLogin()
chrome.runtime.sendMessage({ action: 'getUserLoginData' },async()=>{
let userData:any = await getStorageItem("tb_user")
......@@ -76,6 +81,8 @@ const WayBillModel = function () {
setUser(userDataJson)
setLink(true)
}
initTime = 0
setLoading(false)
})
// alert("刷新完毕");
}, [])
......@@ -85,7 +92,7 @@ const WayBillModel = function () {
<div className="waybill-model-title" key="one">千牛登录账号:{is_login?user.userNick:'未登录'}</div>
<div className="waybill-model-title" key="two">通信状态:{link?'连接成功':'连接中断'}</div>
</div>
<Button type="link" onClick={ refresh }>刷新连接状态</Button>
<Button className="btn" type="primary" loading={loading} disabled={loading} onClick={ refresh }>刷新连接状态</Button>
</>
)
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment