import React from 'react'; import { Input, Modal, Button, message } from 'antd'; import { demandTypeList } from '../../dataDic.js'; import ajax from 'jquery/src/ajax/xhr.js'; import $ from 'jquery/src/ajax'; const BatchImport = React.createClass({ getInitialState: function () { return { loading: false, error: false }; }, showModal() { this.setState({ visible: true, }); }, handleOk(e) { this.setState({ visible: false, }); }, handleCancel(e) { this.setState({ visible: false, }); }, //数据反向转化 getDataCategory(e, row) { switch (e) { case "个人需求": return 0; case "单位需求": return 1; default: message.warning("第 " + row + " 行中没有对应的数据类型!"); this.state.error = true; break; } }, getDemandType(e, row) { let theType, _me = this; if (e) { demandTypeList.map(function (item) { if (item.key == e) { theType = Number(item.value); }; }); if (theType == null) { message.warning("第 " + row + " 行中没有对应的需求类型!"); _me.state.error = true; } return theType; }; }, //提交 handleSubmit() { let rowsArr = this.state.inputValue.split(/[\r\n]/g); let columnArr = [], _me = this; if (!rowsArr.length) { return; }; let columnLength = 9;//定义数据正常长度 for (let i = 0; i < rowsArr.length; i++) { if (_me.state.error) { this.state.error = false; return; }; let theArr = rowsArr[i].split(/\t/); if (theArr.length == columnLength) { columnArr.push({ dataCategory: _me.getDataCategory(theArr[0], i + 1), name: theArr[1], keyword: theArr[2], demandType: _me.getDemandType(theArr[3], i + 1), problemDes: theArr[4], employerName: theArr[5], employerContacts: theArr[6], employerContactsMobile: theArr[7], employerContactsMailbox: theArr[8] }); } else if (rowsArr[i].replace(/(^\s+)|(\s+$)/g, "").length) { message.warning("第" + (i + 1) + "行数据长度错误!"); return; }; }; if (columnArr.length > 1000) { message.warning("数据条数不能多于1000条!"); return; }; this.setState({ loading: true }); $.ajax({ method: "POST", dataType: "json", crossDomain: false, url: globalConfig.context + '/api/admin/demand/importDemand', data: { data: JSON.stringify(columnArr) } }).done(function (data) { this.setState({ loading: false }); if (!data.error.length) { message.success('导入成功!'); this.props.closeDesc(false, true); this.handleOk(); } else { message.warning(data.error[0].message); }; }.bind(this)); }, render() { return ( <div> <Button type="primary" onClick={this.showModal}>批量导入</Button> <Modal title="批量导入" visible={this.state.visible} onCancel={this.handleCancel} width='1000px' footer={[ <Button key="ok" className="set-submit" type="primary" loading={this.state.loading} onClick={this.handleSubmit}>保存</Button>, <Button key="clancel" className="set-submit" type="ghost" onClick={this.handleCancel}>取消</Button> ]} > <Input type="textarea" rows={12} onChange={(e) => { this.state.inputValue = e.target.value; }} /> </Modal> </div> ); } }); export default BatchImport;