公司需求:导入数据,然后对数据进行打印功能
import React, { Component } from "react";
import moment from "moment";
import { Route, Switch } from "react-router-dom";
import { PageHeader, Table, Pagination, Modal, Button, Space, Spin, Upload, message, Input, Form, Select, Drawer } from "antd";
import { DeleteOutlined, ReloadOutlined, UploadOutlined } from "@ant-design/icons";
import AppContext from "../components/context";
import * as XLSX from "xlsx";
let db = new zango.Db("mydb", { informations: ["Goods"] });
let Goods = db.collection("informations");
import routers from "../routers";
import * as Printer from "./assets.print.drawers/print.function";
export default class AssetsPrint extends Component {
constructor(props) {
super(props);
this.state = {
//数据
dataSource: [],
data: [],
file: [],
//表格
loading: false,
//分页
currentPage: 1,
pageSize: 25,
//多选
selectedRowKey: [],
selectedRow: [],
doubleArr: [],
title: [],
searchType: null,
// drawer
visibleDrawer: false,
hasChild: false,
};
}
static contextType = AppContext;
componentDidMount() {
this.setState({ SpinLoading: true });
this.props.history.push({ pathname: "/main/assets_print" });
this.getZangoDB();
}
//获取本地数据库的数据
getZangoDB = async () => {
let res = await Goods.find({}).toArray(function (err, result) {
// 返回集合中所有数据
return result;
});
this.getTitle(res);
this.setState(
{
file: JSON.parse(JSON.stringify(res)),
dataSource: JSON.parse(JSON.stringify(res)),
SpinLoading: false,
},
() => this.pageNumberOnChange(this.state.currentPage, this.state.pageSize)
);
};
//分页
pageNumberOnChange = (page, pageSize) => {
let startNum = page > 0 ? (page - 1) * pageSize : 0;
let ChangeData = this.state.file.slice(startNum, startNum + pageSize);
this.setState({
data: ChangeData,
currentPage: page,
pageSize: pageSize,
});
};
render() {
const { file, data, visibleDrawer, title, searchValue } = this.state;
const { isSmallScreen, tableHeight } = this.context;
const sumTableHeight = tableHeight + 20;
return (
<div style={{ position: "relative" }}>
{file && file.length > 0 && data.length > 0 && (
<span>
<div className="workspace-header">
<PageHeader
title={
<Input.Group compact style={{ paddingLeft: 8 }}>
<Select
showSearch
allowClear
onChange={this.onChangeSearch}
style={{ width: 200 }}
optionFilterProp="children"
filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
// filterSort={(optionA, optionB) =>
// optionA.children.toLowerCase().localeCompare(optionB.children.toLowerCase())
// }
placeholder="请先选择搜索的标题"
>
{title.map((item, index) => {
return (
<Select.Option value={item.title} key={index}>
{item.title}
</Select.Option>
);
})}
</Select>
<Input.Search
style={{ width: 200, height: 32 }}
onSearch={this.onSearch}
placeholder="请输入查询关键词"
allowClear
/>
</Input.Group>
}
extra={
<span>
<DeleteOutlined className="show-icon " onClick={this.showModalConfirm} />
</span>
}
/>
</div>
<div className="workspace-content table-page">
<Table
style={{ marginTop: 15 }}
rowKey={(record) => record._id}
rowSelection={{
onChange: this.onChangeData,
selectedRowKeys: this.state.selectedRowKey,
}}
size="small"
bordered={true}
columns={this.state.title}
loading={this.state.loading}
dataSource={this.state.data}
pagination={false}
scroll={{ y: sumTableHeight, x: this.state.title && this.state.title.length * 200 }}
/>
</div>
<div className="workspace-footer">
<div style={{ float: "left", paddingLeft: 16 }}>
<Space>
<Button type="primary" onClick={this.bathPrint} loading={this.state.loading}>
批量打印
</Button>
</Space>
</div>
<div style={{ float: "right", paddingTop: isSmallScreen ? 4 : 8, paddingRight: 8 }}>
<Pagination
pageSizeOptions={["25", "50", "100", "200"]}
showSizeChanger
onChange={this.pageNumberOnChange}
total={this.state.dataSource.length}
showTotal={(total) => `共 ${this.state.dataSource.length} 条`}
current={this.state.currentPage}
pageSize={this.state.pageSize}
disabled={this.state.loading}
/>
</div>
</div>
</span>
)}
{/* 文件选择 */}
{file && file.length === 0 && (
<div>
<Upload
name="excel"
accept=".xlsx , .xls,"
beforeUpload={this.onImportExcelNew}
showUploadList={false}
onRemove={this.handleOnRemove}
>
<div className="Upload" style={{ width: 400 }}>
<Button type="primary" shape="round" style={{ height: 40, width: 160, marginLeft: 580, marginTop: 220 }}>
<UploadOutlined />
点击导入文件
</Button>
</div>
</Upload>
</div>
)}
{this.state.SpinLoading === true && (
<Spin size="large" className="SpinModal" style={{ textAlign: "center", opacity: "1", position: "fixed", left: "55%" }} />
)}
{/* 路由drawers */}
<Drawer
title="打印"
placement="right"
width={1000}
getContainer={false}
closable={true}
onClose={() => this.onCloseDrawer()}
visible={visibleDrawer}
>
<Switch>
{routers.assetsTableListDrawers.map((item, index) => {
if (item.page) {
let RouterPage = require(`../pages/${item.page}`).default;
return (
<Route
key={index}
path={item.path}
render={() =>
this.state.hasChild ? <RouterPage {...this.props} onCloseDrawer={this.onCloseDrawer} /> : null
}
/>
);
}
})}
</Switch>
</Drawer>
</div>
);
}
onChangeSearch = (value) => {
if (value) {
this.setState({ searchType: value });
} else {
this.getZangoDB();
}
};
//搜索功能
onSearch = (value) => {
const { searchType, dataSource } = this.state;
if (!searchType) return message.warn("请先选择查询标题类");
if (value) {
let newArr = [];
dataSource.forEach((item) => {
if (item[searchType] && item[searchType].toString().indexOf(value) !== -1) {
newArr.push(item);
}
});
console.log(newArr);
if (newArr.length === 0) return message.info("未查询到当前信息");
this.setState(
{
dataSource: newArr,
file: newArr,
},
() => this.pageNumberOnChange(this.state.currentPage, this.state.pageSize)
);
} else {
this.getZangoDB();
}
};
bathPrint = () => {
this.setState({
loading: true,
});
if (this.state.selectedRow.length > 0) {
if (Printer.PrinterList().length > 0) {
this.setState({
visibleDrawer: true,
hasChild: true,
loading: false,
});
this.props.history.push({
pathname: "/main/assets_print/print",
state: {
selectedRow: this.state.selectedRow,
allTitle: this.state.title,
PrinterData: Printer.PrinterList(),
},
});
} else {
this.setState({
loading: false,
});
message.warn("您还未连接打印机");
}
} else {
message.warn("您还未勾选条目");
}
};
onCloseDrawer = () => {
this.props.history.push({ pathname: "/main/assets_print" });
this.setState({
visibleDrawer: false,
hasChild: false,
selectedRowKey: [],
selectedRow: [],
});
this.componentDidMount();
};
//删除数据库
showModalConfirm = () => {
Modal.confirm({
title: "删除提醒",
okText: "确定",
content: "确定删除数据?",
onOk: () => {
this.handleOnRemove();
},
});
};
//移除数据
handleOnRemove = () => {
//清空数据库
Goods.remove({});
this.setState({
file: [],
dataSource: [],
data: [],
newArr: [],
title: [],
});
localStorage.clear();
};
//上传文件并转数据
onImportExcelNew = async (file) => {
this.setState({ SpinLoading: true });
let data = []; // 存储获取到的数据
// 通过FileReader对象读取文件
const fileReader = new FileReader();
fileReader.readAsBinaryString(file); //二进制 转xlsx的文件需要
// fileReader.readAsText(file);//转csv文件需要
fileReader.onload = (event) => {
try {
const { result } = event.target;
// 以二进制流方式读取得到整份excel表格对象
const workbook = XLSX.read(result, { type: "binary" });
// 遍历每张工作表进行读取(这里默认只读取第一张表)
for (const sheet in workbook.Sheets) {
if (workbook.Sheets.hasOwnProperty(sheet)) {
// 利用 sheet_to_json 方法将 excel 转成 json 数据
data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
// break; // 如果只取第一张表,就取消注释这行
}
}
if (data.length === 0) {
this.setState({ SpinLoading: false });
return message.warning("该文件没有资产,不能导入!");
}
this.getTable(data);
} catch (e) {
// 这里可以抛出文件类型错误不正确的相关提示
this.setState({ SpinLoading: false });
message.error("文件类型不正确!");
return;
}
};
};
//存储数据到本地数据库
getTable = (newData) => {
Goods.insert(newData);
this.getZangoDB();
};
//生成标题
getTitle = (newData) => {
let title = [];
let index = 0;
if (newData.length > 0) {
for (let pl in newData[0]) {
index++;
if (pl !== "_id" && pl !== "打印次数") {
let obj = {};
obj.title = pl;
obj.align = "center";
obj.dataIndex = pl;
obj.key = index;
title.push(obj);
} else if (pl !== "_id") {
let obj = {};
obj.title = pl;
obj.align = "center";
obj.dataIndex = pl;
obj.key = index;
title.unshift(obj);
}
}
title[0].fixed = "left";
this.setState({ title });
}
};
//多选表格数据
onChangeData = (selectedRowKeys, selectedRows) => {
// console.log(selectedRowKeys)
const { doubleArr } = this.state;
// 勾选生成二维数组
doubleArr[this.state.currentPage ? this.state.currentPage - 1 : 0] = selectedRows;
// 这块扁平化成为一位数组
const filterRows = this.mapRows(doubleArr);
// console.log(filterRows); // 这块可以打印出来拼接的结果
this.setState({
selectedRowKey: selectedRowKeys,
selectedRow: filterRows, // 存放拼接好的一维数组
});
};
// 扁平化二维数组的方法
mapRows = (params) => {
let res = [];
for (let i = 0; i < params.length; i++) {
if (Array.isArray(params[i])) {
res = res.concat(this.mapRows(params[i]));
} else {
res.push(params[i]);
}
}
return res.filter(Boolean); //去掉undefined的情况
};
}
import React, { Component } from "react";
import { Table, Row, Col, Button, Modal, Input, message, Select, Checkbox, Card, Spin, Empty, Form, Drawer, Descriptions, Tooltip } from "antd";
import { QuestionCircleTwoTone } from "@ant-design/icons";
import printPsd from "./print.psd.json";
import * as Printer from "./print.function";
const { Meta } = Card;
const { Option } = Select;
const layout = {
labelCol: { span: 3 },
wrapperCol: { span: 18 },
};
let db = new zango.Db("mydb", { informations: ["Goods"] });
let Goods = db.collection("informations");
export default class Print extends Component {
constructor(props) {
super(props);
this.state = {
selectedRow: props.history.location.state ? props.history.location.state.selectedRow : [],
titleData: props.history.location.state
? props.history.location.state.allTitle.filter((item) => {
return item.title !== "二维码";
})
: [], //选择打印的标签
codeTitleSelect: props.history.location.state ? props.history.location.state.allTitle : [],
CheckboxList: [],
indeterminate: false,
checkAll: false,
loading: false,
titleValue: null,
PrinterList: props.history.location.state ? props.history.location.state.PrinterData : [], //所有打印机
dataSource: [], //选择的打印数据
visible: false,
currentPsd: null, //选择的母版
psdList: [], //母版列表
setPsdData: [], //缓存的打印模板
selectDefault: null, //选择的模板
selectDefaultText: null,
isCreate: true, //是否点击创建新的
};
//存储模板的form
this.FormRef = React.createRef();
//打印的form
this.formRefPrint = React.createRef();
this.changeFun = this.throttle(this.changeValueFun);
}
async componentDidMount() {
// console.log(this.props);
if (window.localStorage && window.localStorage.getItem("print")) {
//判断浏览器是否支持localStorage
let obj = window.localStorage.getItem("print");
this.setState({
setPsdData: JSON.parse(obj),
isCreate: false,
});
}
this.setState({
psdList: printPsd,
});
}
//检索功能
changeData = (e) => {
this.setState({
loading: true,
titleValue: e.target.value,
});
let res = e.target.value;
this.changeFun(res);
};
//闭包节流
throttle = (fun) => {
let last, deferTimer;
var preTime = Date.now();
return function (args) {
let that = this;
let _args = arguments;
let nowTime = Date.now();
if (nowTime - preTime >= 1000) {
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
preTime = Date.now();
fun.apply(that, _args);
}, 1000);
} else {
preTime = Date.now();
fun.apply(that, _args);
}
};
};
//改变的函数
changeValueFun = (val) => {
let { titleData } = this.state;
titleData.forEach((item, index) => {
if (val && item.title.indexOf(val) !== -1) {
item.ifHot = true;
} else {
item.ifHot = false;
}
});
this.setState({
titleData,
loading: false,
});
};
//全选
onCheckAllChange = (e) => {
const { titleData } = this.state;
let arr = [],
AllData = [];
titleData.forEach((item) => {
arr.push(item.key);
});
titleData.forEach((item, indexs) => {
let obj = {};
obj.index = indexs;
obj.title = item.title;
obj.dataIndex = item.dataIndex;
obj.key = (indexs + 1).toString();
AllData.push(obj);
});
this.setState({
CheckboxList: e.target.checked ? arr : [],
dataSource: e.target.checked ? AllData : [],
indeterminate: false,
checkAll: e.target.checked,
});
};
//多选
onChange = (val) => {
const { titleData, dataSource, currentPsd } = this.state;
let newArr = [];
val.forEach((items) => {
titleData.forEach((item, indexs) => {
if (items === item.key) {
let obj = {};
//这个key是用来排序的,必须是0-1-2这个顺序
obj.index = items;
//标题
obj.title = item.title;
//键值对
obj.dataIndex = item.dataIndex;
//唯一键值
obj.key = (indexs + 1).toString();
newArr.push(obj);
}
});
});
if (newArr.length > this.state.currentPsd.labelContentNum) {
return message.info("打印项超出了当前标签纸条目");
}
let obj = {};
newArr.forEach((item) => {
obj[item.title] = item.title;
});
this.setState(
{
dataSource: newArr,
CheckboxList: val,
},
() => {
this.FormRef.current.setFieldsValue(obj);
}
);
};
//选择模板
selectTagboard = () => {
this.setState({
visible: true,
titleValue: null,
});
this.changeFun("");
};
//错误提示
handleFinishFailed = ({ values, errorFields, outOfDate }) => {
console.log(errorFields);
if (errorFields.length > 0) {
message.warn("您输入的内容有误,请核对后再提交");
}
//this.createFormRef.current.scrollToField(errorFields[0].name.toString());
};
//保存模板
onFinish = (values) => {
let storage = window.localStorage.getItem("print");
let obj = {},
data = storage ? JSON.parse(storage) : [];
obj.data = values;
obj.psd = this.state.currentPsd;
data.push(obj);
// console.log(values);
this.setState({
setPsdData: data,
isCreate: false,
currentPsd: null,
});
window.localStorage.setItem("print", JSON.stringify(data));
};
//选择默认模板
selectPsd = (value) => {
const { setPsdData } = this.state;
let newArr = setPsdData.filter((item, index) => {
return item.psd.labelSeno === value;
});
let dataArr = [];
for (let key in newArr[0].data) {
if (key !== "code" && key !== "psdname") {
dataArr.push({
name: newArr[0].data[key],
});
}
}
this.setState({
selectDefault: newArr[0],
selectDefaultText: dataArr,
});
};
// 开始打印
handleBeginPint = () => {
const { selectPrinter, PrinterList, selectedRow, selectDefault } = this.state;
if (PrinterList.length === 0) {
return message.warn("暂未检查到打印机,无法打印");
}
if (!selectPrinter) {
return message.warn("请先选择打印机");
}
if (selectedRow.length === 0) {
return message.warn("未选择到数据,请重试");
}
// console.log(selectDefault.psd);
//打印方法
Printer.doPrinterLabel(selectPrinter, selectDefault, selectedRow, 0);
console.log(selectedRow);
selectedRow.forEach((item) => {
if (item["打印次数"]) {
item["打印次数"] = item["打印次数"] + 1;
} else {
item["打印次数"] = 1;
}
Goods.update({ _id: item._id }, item);
});
};
render() {
const {
titleData,
codeTitleSelect,
CheckboxList,
dataSource,
currentPsd,
visible,
psdList,
setPsdData,
loading,
PrinterList,
selectDefault,
selectDefaultText,
isCreate,
titleValue,
} = this.state;
return (
<div>
{/* *************打印模块的******** */}
{setPsdData && setPsdData.length > 0 && !isCreate ? (
<Card
title="选择打印模板"
size="small"
extra={
<span>
<Button loading={loading} onClick={() => this.props.onCloseDrawer()}>
取消
</Button>
<Button type="primary" style={{ marginLeft: 20 }} loading={loading} onClick={this.handleBeginPint}>
打印
</Button>
<Button type="primary" style={{ marginLeft: 20 }} loading={loading} onClick={() => this.setState({ isCreate: true })}>
新建标签模板
</Button>
</span>
}
>
<Form {...layout} name="basic" ref={this.formRefPrint}>
<Form.Item label="选择打印机" name="print" rules={[{ required: true, message: "请选择打印机!" }]}>
<Select
placeholder="请选择打印机"
style={{ width: "100%" }}
onChange={(value) =>
this.setState({
selectPrinter: value,
})
}
>
{PrinterList.map((item, index) => {
return (
item.type === 1 && (
<Option key={index} value={item.name}>
{item.name}-{item.hostname}-{item.ip}
</Option>
)
);
})}
</Select>
</Form.Item>
<Form.Item label="选择模板" name="psd" rules={[{ required: true, message: "请选择打印机!" }]}>
<Select placeholder="请选择打印模板" style={{ width: "100%" }} onChange={this.selectPsd}>
{setPsdData &&
setPsdData.length > 0 &&
setPsdData.map((item, index) => {
return (
<Option key={index} value={item.psd.labelSeno}>
{item.data.psdname}
</Option>
);
})}
</Select>
</Form.Item>
<Form.Item label="标签文字" name="text">
{selectDefaultText && selectDefaultText.length > 0 ? (
<Descriptions bordered>
{selectDefaultText.map((item, index) => {
return (
<Descriptions.Item key={index} label={`名称${index + 1}:`} span={2}>
{item.name}
</Descriptions.Item>
);
})}
</Descriptions>
) : (
<div>暂无默认模板</div>
)}
</Form.Item>
<Form.Item
label={
<span>
标签纸样式
<Tooltip placement="top" title="上述内容是与标签纸对应的位置">
<QuestionCircleTwoTone theme="twoTone" style={{ marginLeft: 5 }} />
</Tooltip>
</span>
}
name="img"
>
{selectDefault && selectDefault.psd ? (
<Card
hoverable
style={{ width: 240, marginBottom: 20 }}
cover={<img alt="加载中..." src={selectDefault.psd.labelImage.path} width="100%" height="100%" />}
>
<Meta
style={{ textAlign: "center" }}
title={selectDefault.psd.labelName}
description={selectDefault.psd.labelSize}
/>
</Card>
) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂时未选择模板" />
)}
</Form.Item>
</Form>
</Card>
) : (
<Card title="当前标签纸" extra={<Button onClick={this.selectTagboard}>选择标签纸</Button>} size="small">
{currentPsd ? (
<Card
hoverable
style={{ width: 240, margin: "0 auto" }}
cover={<img alt="example" src={require("./imags/" + currentPsd.labelImage.file)} width="100%" height="100%" />}
>
<Meta style={{ textAlign: "center" }} title={currentPsd.labelName} description={currentPsd.labelSize} />
</Card>
) : (
<Empty description="暂无标签纸,请先选择标签纸" style={{ margin: "10px auto" }} />
)}
</Card>
)}
{/* ************制作模板的****************** */}
{currentPsd && (
<div>
{/* 标题 */}
<Card title="打印的标题" size="small" style={{ marginTop: 10 }}>
<Row>
<Col style={{ margin: "10px 0" }}>
<Input
placeholder="请选择需要查询标题名称"
value={titleValue}
onChange={(e) => this.changeData(e)}
style={{ width: "300px" }}
/>
</Col>
</Row>
<Spin spinning={this.state.loading}>
{/* <Checkbox indeterminate={indeterminate} onChange={this.onCheckAllChange} checked={checkAll}>
全选
</Checkbox> */}
<Checkbox.Group style={{ width: "100%" }} value={CheckboxList} onChange={this.onChange}>
<Row>
{titleData.length > 0 &&
titleData.map((item, index) => {
return (
<Col span={6} key={index}>
<Checkbox value={item.key}>
<span style={item.ifHot && item.ifHot === true ? { color: "red" } : null}>
{item.title}
</span>
</Checkbox>
</Col>
);
})}
</Row>
</Checkbox.Group>
</Spin>
</Card>
{/* 模板设置 */}
<Card title="打印的模板" size="small" style={{ marginTop: 10 }}>
{dataSource && dataSource.length > 0 ? (
<Form ref={this.FormRef} onFinish={this.onFinish} onFinishFailed={this.handleFinishFailed}>
<Row>
{dataSource.map((item, index) => {
return (
<Col span={12} key={index}>
<Form.Item
label={`名称${index + 1}(${item.title})`}
name={item.title}
rules={[{ required: true, message: "请输入打印标题" }]}
>
<Input placeholder="请输入打印标题" style={{ width: "90%" }} />
</Form.Item>
</Col>
);
})}
<Col span={12}>
<Form.Item label="二维码" name="code" rules={[{ required: true, message: "请选择二维码" }]}>
<Select placeholder="请选择二维码将要打印的数据" style={{ width: "90%" }}>
{codeTitleSelect.map((item, index) => {
return (
<Option key={index} value={item.title}>
{item.title}
</Option>
);
})}
</Select>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item label="模板名称" name="psdname" rules={[{ required: true, message: "请输入模板名称" }]}>
<Input placeholder="请输入模板名称" style={{ width: "90%" }} />
</Form.Item>
</Col>
</Row>
<Button type="primary" htmlType="submit">
保存
</Button>
</Form>
) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="请选择要打印的标签字段" />
)}
</Card>
</div>
)}
{/* 模板数据 */}
<Drawer title="选择模板" placement="right" visible={visible} width={800} onClose={() => this.handleDrawerChildrenClose()}>
<Row gutter={16}>
{psdList.length > 0 &&
psdList.map((item, index) => {
return (
<Col key={index} span={8}>
<Card
hoverable
style={{ width: 220, marginBottom: 20 }}
onClick={(e) => this.handleDrawerChildrenClose(item)}
cover={
<div>
<img
alt="加载中..."
src={require("./imags/" + item.labelImage.file)}
className="psd"
width="100%"
height="100%"
/>
{currentPsd && currentPsd.labelSeno === item.labelSeno && (
<img alt="def..." src={require("./def.png")} className="def" />
)}
</div>
}
>
<Meta style={{ textAlign: "center" }} title={item.labelName} description={item.labelSize} />
</Card>
</Col>
);
})}
</Row>
</Drawer>
</div>
);
}
//关闭draws
handleDrawerChildrenClose = (item) => {
// console.log(item);
if (item) {
this.setState({
currentPsd: item,
visible: false,
dataSource: [],
CheckboxList: [],
});
} else {
this.setState({
visible: false,
});
}
};
}
更新上面代码
import React, { Component } from "react";
import moment from "moment";
import { Route, Switch } from "react-router-dom";
import { PageHeader, Table, Pagination, Modal, Button, Space, Spin, Upload, message, Input, Form, Select, Drawer } from "antd";
import { DeleteOutlined, ReloadOutlined, UploadOutlined } from "@ant-design/icons";
import AppContext from "../components/context";
import * as XLSX from "xlsx";
let db = new zango.Db("mydb", { informations: ["Goods"] });
let Goods = db.collection("informations");
import routers from "../routers";
import * as Printer from "./assets.print.drawers/print.function";
export default class AssetsPrint extends Component {
constructor(props) {
super(props);
this.state = {
//数据
dataSource: [],
file: [],
//表格
loading: false,
SpinLoading: false,
//分页
pageSize: 25,
page: 1,
totalCount: 0,
//多选
selectedRowKey: [],
selectedRow: [],
doubleArr: [],
title: [],
searchType: null,
searchData: null,
// drawer
visibleDrawer: false,
hasChild: false,
};
}
static contextType = AppContext;
componentDidMount() {
this.props.history.push({ pathname: "/main/assets_print" });
this.getZangoDB();
}
//获取本地数据库的数据
getZangoDB = async () => {
let { searchType, searchData, file } = this.state;
this.setState({ SpinLoading: true });
let totalCount, res;
if (searchType && searchData) {
totalCount = await Goods.find({ [searchType]: searchData.replace(/\s+/g, "") }).toArray(function (err, result) {
// 返回集合中所有数据
return result;
});
res = await Goods.find({ [searchType]: searchData })
.skip((this.state.page - 1) * this.state.pageSize)
.limit(this.state.pageSize)
.toArray(function (err, result) {
// 返回集合中所有数据
return result;
});
} else {
totalCount = await Goods.find().toArray(function (err, result) {
// 返回集合中所有数据
return result;
});
res = await Goods.find()
.skip((this.state.page - 1) * this.state.pageSize)
.limit(this.state.pageSize)
.toArray(function (err, result) {
// 返回集合中所有数据
return result;
});
}
if (this.state.title.length === 0) {
this.getTitle(res);
}
if (file.length > 0) {
this.setState({
dataSource: JSON.parse(JSON.stringify(res)),
SpinLoading: false,
totalCount: JSON.parse(JSON.stringify(totalCount)).length,
});
} else {
this.setState({
file: JSON.parse(JSON.stringify(res)),
dataSource: JSON.parse(JSON.stringify(res)),
SpinLoading: false,
totalCount: JSON.parse(JSON.stringify(totalCount)).length,
});
}
};
render() {
const { file, dataSource, visibleDrawer, title, SpinLoading, pageSize, page, totalCount } = this.state;
const { isSmallScreen, tableHeight } = this.context;
const sumTableHeight = tableHeight + 20;
const pagenationProps = {
pageSizeOptions: ["25", "50", "100", "200"],
showSizeChanger: true,
current: page,
size: "default",
position: ["none", "bottomCenter"],
hideOnSinglePage: false,
total: totalCount,
showTotal: (total, range) => `共 ${total} 条`,
defaultPageSize: pageSize,
pageSize: pageSize,
itemRender: (current, type, originalElement) => {
if (type === "prev") return <a>上一页</a>;
if (type === "next") return <a>下一页</a>;
return originalElement;
},
onChange: (page, pageSize) => {
this.setState({ page, pageSize }, () => this.getZangoDB());
},
onShowSizeChange: (current, size) => {
this.setState({ page: 1, pageSize: size }, () => this.getZangoDB());
},
};
return (
<Spin tip="加载中..." spinning={SpinLoading}>
<div style={{ position: "relative" }}>
{file && file.length > 0 && (
<span>
<div className="workspace-header">
<PageHeader
title={
<Input.Group compact style={{ paddingLeft: 8 }}>
<Select
showSearch
allowClear
onChange={this.onChangeSearch}
style={{ width: 200 }}
optionFilterProp="children"
filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
// filterSort={(optionA, optionB) =>
// optionA.children.toLowerCase().localeCompare(optionB.children.toLowerCase())
// }
placeholder="请先选择搜索的标题"
>
{title.map((item, index) => {
return (
<Select.Option value={item.title} key={index}>
{item.title}
</Select.Option>
);
})}
</Select>
<Input.Search
style={{ width: 200, height: 32 }}
onSearch={this.onSearch}
placeholder="请输入查询关键词"
allowClear
/>
</Input.Group>
}
extra={
<span>
<DeleteOutlined className="show-icon " onClick={this.showModalConfirm} />
</span>
}
/>
</div>
<div className="workspace-content table-page">
<Table
style={{ marginTop: 15 }}
rowKey={(record) => record._id}
rowSelection={{
onChange: this.onChangeData,
selectedRowKeys: this.state.selectedRowKey,
}}
size="small"
bordered={true}
columns={this.state.title}
loading={this.state.loading}
dataSource={dataSource}
pagination={false}
scroll={{ y: sumTableHeight, x: this.state.title && this.state.title.length * 200 }}
/>
</div>
<div className="workspace-footer">
<div style={{ float: "left", paddingLeft: 16 }}>
<Space>
<Button type="primary" onClick={this.bathPrint} loading={this.state.loading}>
批量打印
</Button>
</Space>
</div>
<div style={{ float: "right", paddingTop: isSmallScreen ? 4 : 8, paddingRight: 8 }}>
<Pagination {...pagenationProps} />
</div>
</div>
</span>
)}
{/* 文件选择 */}
{file && file.length === 0 && (
<div>
<Upload
name="excel"
accept=".xlsx , .xls,"
beforeUpload={this.onImportExcelNew}
showUploadList={false}
onRemove={this.handleOnRemove}
>
<div className="Upload" style={{ width: 400 }}>
<Button type="primary" shape="round" style={{ height: 40, width: 160, marginLeft: 580, marginTop: 220 }}>
<UploadOutlined />
点击导入文件
</Button>
</div>
</Upload>
</div>
)}
{/* 路由drawers */}
<Drawer
title="打印"
placement="right"
width={1000}
getContainer={false}
closable={true}
onClose={() => this.onCloseDrawer()}
visible={visibleDrawer}
>
<Switch>
{routers.assetsTableListDrawers.map((item, index) => {
if (item.page) {
let RouterPage = require(`../pages/${item.page}`).default;
return (
<Route
key={index}
path={item.path}
render={() =>
this.state.hasChild ? <RouterPage {...this.props} onCloseDrawer={this.onCloseDrawer} /> : null
}
/>
);
}
})}
</Switch>
</Drawer>
</div>
</Spin>
);
}
onChangeSearch = (value) => {
if (value) {
this.setState({ searchType: value });
} else {
this.getZangoDB();
}
};
//搜索功能
onSearch = (value) => {
const { searchType, file } = this.state;
if (!searchType) return message.warn("请先选择查询标题类");
this.setState(
{
searchData: value,
},
() => {
this.getZangoDB();
}
);
};
bathPrint = () => {
let { selectedRow } = this.state;
if (this.state.selectedRow.length > 0) {
this.setState({
loading: true,
});
if (Printer.PrinterList().length > 0) {
this.setState({
visibleDrawer: true,
hasChild: true,
loading: false,
});
console.log(selectedRow);
this.props.history.push({
pathname: "/main/assets_print/print",
state: {
selectedRow: selectedRow,
allTitle: this.state.title,
PrinterData: Printer.PrinterList(),
},
});
} else {
this.setState({
loading: false,
});
message.warn("您还未连接打印机");
}
} else {
message.warn("您还未勾选条目");
}
};
onCloseDrawer = () => {
this.props.history.push({ pathname: "/main/assets_print" });
this.setState(
{
visibleDrawer: false,
hasChild: false,
selectedRowKey: [],
selectedRow: [],
doubleArr: [],
},
() => {
this.componentDidMount();
}
);
};
//删除数据库
showModalConfirm = () => {
Modal.confirm({
title: "删除提醒",
okText: "确定",
content: "确定删除数据?",
onOk: () => {
this.handleOnRemove();
},
});
};
//移除数据
handleOnRemove = () => {
//清空数据库
Goods.remove({});
this.setState({
file: [],
dataSource: [],
data: [],
newArr: [],
title: [],
pageSize: 25,
page: 1,
totalCount: 0,
});
// localStorage.clear();
};
//上传文件并转数据
onImportExcelNew = async (file) => {
this.setState({ SpinLoading: true });
let data = []; // 存储获取到的数据
// 通过FileReader对象读取文件
const fileReader = new FileReader();
fileReader.readAsBinaryString(file); //二进制 转xlsx的文件需要
// fileReader.readAsText(file);//转csv文件需要
fileReader.onload = (event) => {
try {
const { result } = event.target;
// 以二进制流方式读取得到整份excel表格对象
const workbook = XLSX.read(result, { type: "binary" });
// 遍历每张工作表进行读取(这里默认只读取第一张表)
for (const sheet in workbook.Sheets) {
if (workbook.Sheets.hasOwnProperty(sheet)) {
// 利用 sheet_to_json 方法将 excel 转成 json 数据
data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
// break; // 如果只取第一张表,就取消注释这行
}
}
if (data.length === 0) {
this.setState({ SpinLoading: false });
return message.warning("该文件没有资产,不能导入!");
}
this.getTable(data);
} catch (e) {
// 这里可以抛出文件类型错误不正确的相关提示
this.setState({ SpinLoading: false });
message.error("文件类型不正确!");
return;
}
};
};
//存储数据到本地数据库
getTable = (newData) => {
Goods.insert(newData);
this.getZangoDB();
};
//生成标题
getTitle = (newData) => {
let title = [];
let index = 0;
if (newData.length > 0) {
for (let pl in newData[0]) {
index++;
if (pl !== "_id") {
let obj = {};
obj.title = pl;
obj.align = "center";
obj.dataIndex = pl;
obj.key = index;
title.push(obj);
}
}
let ifHasNum = title.every((item) => {
return item.title !== "打印次数";
});
let ifHasTime = title.every((item) => {
return item.title !== "打印次数";
});
//如果==true;说明没有一个是满足的的
if (ifHasNum) {
let obj = {};
obj.title = "打印次数";
obj.align = "center";
obj.dataIndex = "打印次数";
obj.key = title.length + 1;
title.unshift(obj);
}
if (ifHasTime) {
let obj = {};
obj.title = "打印时间";
obj.align = "center";
obj.dataIndex = "打印时间";
obj.key = title.length + 1;
title.push(obj);
}
title[0].fixed = "left";
this.setState({ title });
}
};
//多选表格数据
onChangeData = (selectedRowKeys, selectedRows) => {
// console.log(selectedRowKeys)
const { doubleArr } = this.state;
// 勾选生成二维数组
doubleArr[this.state.currentPage ? this.state.currentPage - 1 : 0] = selectedRows;
// 这块扁平化成为一位数组
const filterRows = this.mapRows(doubleArr);
// console.log(filterRows); // 这块可以打印出来拼接的结果
this.setState({
selectedRowKey: selectedRowKeys,
selectedRow: filterRows, // 存放拼接好的一维数组
});
};
// 扁平化二维数组的方法
mapRows = (params) => {
let res = [];
for (let i = 0; i < params.length; i++) {
if (Array.isArray(params[i])) {
res = res.concat(this.mapRows(params[i]));
} else {
res.push(params[i]);
}
}
return res.filter(Boolean); //去掉undefined的情况
};
}