单词设置

<template>
	<div class="repContainer scrollBarReset">

		<el-form :inline="true" :model="searchForm" class="demo-form-inline">
			<el-form-item label="原口岸">
				<el-select v-model="dataForm.cusDeptData" multiple filterable placeholder="请选择" filterable size="mini" style="width:750px">
					<el-option v-for="item in cusDepts" :key="item.cusDeptCode" :label="item.cusDeptCode" :value="item.cusDeptCode">
						<span style="float: left">{{ item.cusDeptCode }}</span>
						<span style="float: right; color: #8492a6; font-size: 13px">{{ item.cusDeptName }}    </span>
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="是否开启单词自动替换">
				<template slot-scope="scope">
					<el-switch v-model="dataForm.onOff">
					</el-switch>
				</template>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="getModule" size="mini" icon="el-icon-refresh">刷新</el-button>
				<el-button @click="UpdateConfig" icon="el-icon-document" type="primary" size="mini">保存配置</el-button>
			</el-form-item>
		</el-form>

		<el-form :inline="true" :model="searchForm" class="demo-form-inline">
			<el-form-item label="英文单词">
				<el-input size="mini" placeholder="英文单词" v-model="searchForm.orgWord" width="90px">
				</el-input>
			</el-form-item>
			<el-form-item label="中文词义">
				<el-input size="mini" placeholder="中文词义" v-model="searchForm.trWord" width="90px">
				</el-input>
			</el-form-item>
			<el-form-item label="修改人">
				<el-input size="mini" placeholder="修改人" v-model="searchForm.modifyBy" width="90px">
				</el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="getModule" size="mini" icon="el-icon-search"><span>查询</span></el-button>
				<el-button @click="showAddDiv" icon="el-icon-circle-plus-outline" type="primary" size="mini">新增</el-button>
				<el-button @click="submitUpdateRows" icon="el-icon-document" type="primary" size="mini">保存</el-button>
				<el-button @click="deleteSelRows" type="primary" size="mini" icon="el-icon-delete">删除</el-button>
				<el-button @click="uploadFile()" icon="el-icon-upload2" type="primary" size="mini">导入</el-button>
				<el-button @click="downloadFile(excelData)" icon="el-icon-download" type="primary" size="mini">导出</el-button>
			</el-form-item>

		</el-form>

		<div>
			<template>
				<div class="index" v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="拼命加载中...">
					<input type="file" @change="importFile(this)" id="imFileAuto" style="display: none" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
					<a id="downlink"></a>

					<!--错误信息提示-->
					<el-dialog title="提示" v-model="errorDialog" size="tiny">
						<span>{{errorMsg}}</span>
						<span slot="footer" class="dialog-footer">
		    <el-button type="primary" @click="errorDialog=false">确认</el-button>
		  </span>
					</el-dialog>
					<el-table v-loading="loading" :data="excelData" style="width: 100%" border @selection-change="handleSelectionChange" highlight-current-row height="450">
						<el-table-column type="selection" width="40">
						</el-table-column>
						<el-table-column type="index" label="序号" width="60" :index="indexMethod">
						</el-table-column>
						<el-table-column sortable prop="orgWord" label="英文单词">
							<template slot-scope="scope">
								<el-input v-model:value="scope.row.orgWord" @change="lostInput(scope.row)" size="mini"></el-input>
							</template>
						</el-table-column>
						<el-table-column sortable prop="trWord" label="中文词义">
							<template slot-scope="scope">
								<el-input v-model:value="scope.row.trWord" @change="lostInput(scope.row)" size="mini"></el-input>
							</template>
						</el-table-column>
						<el-table-column sortable prop="enabled" label="是否启用">
							<template slot-scope="scope">
								<el-switch v-model="scope.row.enabled" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" @change="lostInput(scope.row)" size="mini">
								</el-switch>
							</template>
						</el-table-column>
						<!--<el-table-column sortable prop="modifyArea" label="修改地区">
						</el-table-column>-->
						<el-table-column sortable prop="modifyBy" label="修改人">
						</el-table-column>
						<el-table-column sortable prop="modifyTime" label="修改时间">
						</el-table-column>
						<el-table-column sortable prop="usedCount" label="使用次数">
						</el-table-column>
						<el-table-column sortable prop="mark" label="备注">
							<template slot-scope="scope">
								<el-input v-model:value="scope.row.mark" @change="lostInput(scope.row)" size="mini"></el-input>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<el-pagination background @size-change="sizeChange" @current-change="currentChange" :current-page="currentPage1" :page-sizes="[10,20,50,100,500,1000]" :page-size="pageSize" layout="->,total, prev, pager, next" :total="total">
				</el-pagination>
				<el-dialog title="添加商品信息记录" :visible.sync="addVisFlag" width="55%" style="min-width: 1020px;" center>
					<el-form :model="addForm" :inline="true" ref="addForm" :rules="rules" label-width="120px">
						<el-form-item label="英文单词" prop="orgWord">
							<el-input size="mini" v-model="addForm.orgWord" placeholder="请输入英文单词" auto-complete="off"></el-input>
						</el-form-item>
						<el-form-item label="中文词义" prop="trWord">
							<el-input size="mini" v-model="addForm.trWord" placeholder="请输入中文词义" auto-complete="off"></el-input>
						</el-form-item>
						<el-form-item label="是否启用">
							<div style="width:181px;text-align: center;">
								<el-switch v-model="addForm.enabled" active-value="1" inactive-value="0" active-text="是" inactive-text="否" size="mini">
								</el-switch>
								 
							</div>
						</el-form-item>
						<!--<el-form-item label="修改地区" prop="modifyArea">
							<el-input size="mini" v-model.number="addForm.modifyArea" placeholder="请输入修改地区" auto-complete="off"></el-input>
						</el-form-item>-->
						<el-form-item label="备注">
							<el-input size="mini" v-model.number="addForm.mark" placeholder="请输入备注" auto-complete="off"></el-input>
						</el-form-item>
					</el-form>
					<span slot="footer" class="dialog-footer" style="text-align: center;">
				    <el-button @click="addVisFlag = false">取 消</el-button>
				    <el-button type="primary" @click="addData('addForm')">提 交</el-button>
				</span>
				</el-dialog>
			</template>
		</div>
	</div>
</template>

<script>
	import { Notification } from "element-ui"
	import JsonEdit from "./../../../components/jsonEditor.vue" //json对象
	import axios from 'axios'
	import Vue from 'vue'
	var XLSX = require('xlsx')
	export default {
		components: {
			JsonEdit
		},
		data() {
			return {
				currentPage1: 1,
				addVisFlag: false,
				loading: false,
				index: -1,
				show: true,
				excel: false,
				pageSize: 10,
				dataForm: {
					cusDeptData: [],
					onOff: false,
				},
				fullscreenLoading: false,
				errorDialog: false,
				errorMsg: '',
				pageNum: 1,
				dels: [],
				total: 0,
				tableData: new Object(),
				multipleSelection: [],
				updateRowId: 0,
				updateRowsMap: new Map(),
				imFileAuto: '', // 导入文件el
				outFile: '', // 导出文件el
				excelData: [],
				cusDepts: [],
				addForm: {
					enabled: '1',
					orgWord: '',
					trWord: '',
					mark: '',
					modifyArea: ' '

				},
				rules: {
					orgWord: [{
							required: true,
							message: '请输入英文单词',
							trigger: 'blur'
						},
						{
							pattern: /^[a-zA-Z0-9]+$/,
							message: '请输入字母或数字',
							trigger: 'blur'
						},
						{
							min: 1,
							max: 300,
							message: '长度在 1 到 300个字符',
							trigger: 'blur'
						}
					],
					trWord: [{
							required: true,
							message: '请输入中文词义',
							trigger: 'blur'
						},
						{
							min: 1,
							max: 150,
							message: '长度在 1 到 150个字符',
							trigger: 'blur'
						}
					],
					enabled: '0',
					modifyArea: [{
							required: true,
							message: '请输入修改地区',
							trigger: 'blur'
						},
						{
							min: 1,
							max: 1000,
							message: '长度在 1 到 1000个字符',
							trigger: 'blur'
						}
					],
					mark: ''
				},
				searchForm: {
					orgWord: '',
					trWord: '',
					enabled: '',
					modifyBy: '',
					mark: ''
				}
			}
		},
		mounted() {

			//测试键盘keydown事件  关闭全屏预览结果框
			var that = this;
			document.addEventListener("keydown", function(code) {
				if(code.which == 27) {
					that.full = false;
				}
			});
			this.imFileAuto = document.getElementById('imFileAuto');
			this.outFile = document.getElementById('downlink');
			this.getModule();
		},
		methods: {
			uploadFile: function() { // 点击导入按钮
				this.imFileAuto.click()
			},
			downloadFile: function(rs) { // 点击导出按钮
				let data = [{}]
				for(let k in rs[0]) {
					data[0][k] = k
				}
				data = data.concat(rs)
				this.downloadExl(data, '单词设置')
			},
			importFile: function() { // 导入excel
				this.fullscreenLoading = true
				let obj = this.imFileAuto;
				var name = obj.value.split(".");
				if(name[1].toLocaleLowerCase() != "xlsx") {
					Notification.error({
						title: '不支持的文件类型',
						message: "不支持的文件类型,只支持xlsx类型"
					});
					this.imFileAuto.value = [];
					this.fullscreenLoading = false;
					return;
				}
				if(!obj.files) {
					this.fullscreenLoading = false
					return
				}
				var f = obj.files[0]
				var reader = new FileReader()
				let $t = this
				reader.onload = function(e) {
					var data = e.target.result;
					if($t.rABS) {
						$t.wb = XLSX.read(btoa(this.fixdata(data)), { // 手动转化
							type: 'base64'
						})
					} else {
						$t.wb = XLSX.read(data, {
							type: 'binary'
						})
					}
					let json = XLSX.utils.sheet_to_json($t.wb.Sheets[$t.wb.SheetNames[0]])
					console.log(obj)
					$t.dealFile($t.analyzeData(json)) // analyzeData: 解析导入数据
				}
				if(this.rABS) {
					reader.readAsArrayBuffer(f)
				} else {
					reader.readAsBinaryString(f)
				}
			},
			analyzeData: function(data) { // 此处可以解析导入数据
				return data
			},
			dealFile: function(data) { // 处理导入的数据
				console.log(data)
				this.imFileAuto.value = ''
				this.fullscreenLoading = false
				if(data.length <= 0) {
					this.errorDialog = true
					this.errorMsg = '请导入正确信息'
				} else {
					for(var i = 0; i < data.length; i++) {
						if(data[i].enabled === '0' || data[i].enabled === '1') {
							data[i].enabled = parseInt(data[i].enabled)
						}
					}
					console.log(data);
					this.excelData = data
					this.excel = true;
				}
			},

			downloadExl: function(json, downName, type) { // 导出到excel
				let keyMap = [] // 获取键
				for(let k in json[0]) {
					keyMap.push(k)
				}
				console.info('keyMap', keyMap, json)
				let tmpdata = [] // 用来保存转换好的json
				json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
					v: v[k],
					position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
				}))).reduce((prev, next) => prev.concat(next)).forEach(function(v) {
					tmpdata[v.position] = {
						v: v.v
					}
				})
				let outputPos = Object.keys(tmpdata) // 设置区域,比如表格从A1到D10
				let tmpWB = {
					SheetNames: ['mySheet'], // 保存的表标题
					Sheets: {
						'mySheet': Object.assign({},
							tmpdata, // 内容
							{
								'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
							})
					}
				}
				let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB, {
						bookType: (type === undefined ? 'xlsx' : type),
						bookSST: false,
						type: 'binary'
					} // 这里的数据是用来定义导出的格式类型
				))], {
					type: ''
				}) // 创建二进制对象写入转换好的字节流
				var href = URL.createObjectURL(tmpDown) // 创建对象超链接
				this.outFile.download = downName + '.xlsx' // 下载名称
				this.outFile.href = href // 绑定a标签
				this.outFile.click() // 模拟点击实现下载
				setTimeout(function() { // 延时释放
					URL.revokeObjectURL(tmpDown) // 用URL.revokeObjectURL()来释放这个object URL
				}, 100)
			},
			s2ab: function(s) { // 字符串转字符流
				var buf = new ArrayBuffer(s.length)
				var view = new Uint8Array(buf)
				for(var i = 0; i !== s.length; ++i) {
					view[i] = s.charCodeAt(i) & 0xFF
				}
				return buf
			},
			getCharCol: function(n) { // 将指定的自然数转换为26进制表示。映射关系:[0-25] -> [A-Z]。
				let s = ''
				let m = 0
				while(n > 0) {
					m = n % 26 + 1
					s = String.fromCharCode(m + 64) + s
					n = (n - m) / 26
				}
				return s
			},
			fixdata: function(data) { // 文件流转BinaryString
				var o = ''
				var l = 0
				var w = 10240
				for(; l < data.byteLength / w; ++l) {
					o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
				}
				o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
				return o
			},

			indexMethod(index) {
				return(index + 1) + ((this.pageNum - 1) * this.pageSize);
			},
			fullScreen() {
				this.full = true;
			},
			closeFull() {
				this.full = false;
			},
			getModule() { //查询module
				this.loading = true;
				this.$httpExt().post("/cas/MSTEST/autoSignleTrial/queryAutoAuditWordList", {
					"pageIndex": this.pageNum,
					"pageSize": this.pageSize,
					"object": {
						orgWord: '%' + this.searchForm.orgWord + '%',
						trWord: '%' + this.searchForm.trWord + '%',
						modifyBy: '%' + this.searchForm.modifyBy + '%',
					}

				}).then((response) => {
					if(response.succ == "ok") {
						this.tableData = response.result.pageInfo.list;
						this.excelData = response.result.pageInfo.list;
						this.total = response.result.pageInfo.total;
						this.rowIndex = response.result.pageInfo.startRow;
						this.cusDepts = response.result.dataMap.cusDepts;
						if(response.result.dataMap.config.cusDeptData != null) {
							this.dataForm.cusDeptData = response.result.dataMap.config.cusDeptData;
						}
						this.dataForm.onOff = response.result.dataMap.config.onOff;
						this.loading = false;
						if(this.pageNum > 1 && response.result.pageInfo.list.length == 0) {
							this.pageNum = 1;
							this.getModule();
							this.indexMethod(0);
						}
						this.currentPage1 = this.pageNum;
					} else {
						Notification.error({
							title: '异常',
							message: response.msg
						});
					}
				}, (response) => {
					Notification.error({
						title: '异常',
						message: response.msg
					});
				})
			},
			sizeChange(pageSize) {
				this.pageSize = pageSize;
				this.getModule();
			},
			currentChange(val) {
				this.pageNum = val;
				this.getModule();
			},
			handleSelectionChange(val) {
				//alert(JSON.stringify(val));
				this.multipleSelection = val;
			},
			handleClick(row) {
				console.log(JSON.stringify(row));
			},
			currentRowChange(curRow, oldRow) {
				//console.log(JSON.stringify(curRow));
			},
			focusInput(row) {
				console.log("获得焦点: oldRowId:" + this.updateRowId + "---newRowId" + row.id);
			},
			// 失去焦点事件
			lostInput(row) {
				console.log("失去焦点: oldRowId:" + this.updateRowId + "---newRowId" + row.id + "---");
				if(this.updateRowId != 0 && this.updateRowId != row.id) {
					console.log("换行咯,更新上一行的数据");
					this.updateRowId = row.id;
				} else {
					this.updateRowId = row.id;
				}
				this.updateRowsMap.set(row.id, row);
				//console.log(this.updateRowsMap);
			},
			deleteSelRows() {
				if(this.multipleSelection.length > 0) {
					this.$confirm('确定删除英文单词吗?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						var params = [];
						this.multipleSelection.forEach((item) => {
							params.push(item.id);    
						});
						console.log("ids: " + params);
						this.$httpExt().post("/cas/MSTEST/autoSignleTrial/deleteAutoAuditWordRow", params).then((response) => {
							if(response.succ == "ok") {
								params.forEach((item) => {
									for(let i = 0; i < this.tableData.length; i++) {
										if(this.tableData[i].id == item) {
											this.tableData.splice(i, 1);
										}
									}
								});
								this.multipleSelection = [];
								Notification({
									title: '成功',
									message: '删除成功!',
									type: 'success'
								});
							} else {
								Notification.error({
									title: '异常',
									message: response.msg
								});
							}
						}, (response) => {
							Notification.error({
								title: '修改失败',
								message: response.msg
							});
						});
					});
				} else {
					Notification.error({
						title: '异常',
						message: "请选择至少一行数据需要删除的数据!"
					});
				}
			},
			showAddDiv() {
				this.addVisFlag = true;
				this.addForm.mark = '';
			},
			addData(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						this.$httpExt().post("/cas/MSTEST/autoSignleTrial/addAutoAuditWordRow", this.addForm).then((response) => {
							if(response.succ == "ok") {
								this.addVisFlag = false;
								this.$refs[formName].resetFields();
								Notification({
									title: '成功',
									message: '保存成功!',
									type: 'success'
								});
							} else {
								Notification.error({
									title: '异常',
									message: response.msg
								});
							}
						}, (response) => {
							Notification.error({
								title: '保存失败',
								message: response.msg
							});
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			submitUpdateRows() {
				if(this.excel) {
					this.saveData();
				} else {
					if(this.updateRowsMap.size > 0) {
						var params = [];
						this.updateRowsMap.forEach((value, key) => { 
							if(value.orgWord.length == null || value.orgWord.trim() == '') {
								Notification.info({
									title: '提示',
									message: '英文单词不能为空!'
								});
								return;
							}   
							if(value.orgWord.length > 300) {
								Notification.info({
									title: '提示',
									message: '英文单词长度不能大于300!'
								});
								return;
							}  
							if(value.trWord.length == null || value.trWord.trim() == '') {
								Notification.info({
									title: '提示',
									message: '中文词义不能为空!'
								});
								return;
							}  
							if(value.trWord.length > 150) {
								Notification.info({
									title: '提示',
									message: '中文词义长度不能大于150!'
								});
								return;
							} 
							if(value.orgWord.mark > 1000) {
								Notification.info({
									title: '提示',
									message: '备注长度大于1000!'
								});
								return;
							} 

							params.push(value);    
						});
						this.$httpExt().post("/cas/MSTEST/autoSignleTrial/updateAutoAuditWordRow", params).then((response) => {
							if(response.succ == "ok") {
								this.updateRowsMap = new Map();
								Notification({
									title: '成功',
									message: '修改成功!',
									type: 'success'
								});
							} else {
								Notification.error({
									title: '异常',
									message: response.msg
								});
							}
						}, (response) => {
							if(response.msg.search("reason") == -1) {
								this.updateRowsMap = new Map();
								this.getModule();
							}
							Notification.error({
								title: '修改失败',
								message: response.msg
							});
						})
					} else {
						Notification.error({
							title: '异常',
							message: "请选择至少一行数据修改后再提交!"
						});
					}
				}

			},
			UpdateConfig() {
				this.$httpExt().post("/cas/MSTEST/autoSignleTrial/autoAuditWordConfig", this.dataForm).then((response) => {
					if(response.succ == "ok") {
						this.updateRowsMap = new Map();
						Notification({
							title: '成功',
							message: '修改成功!',
							type: 'success'
						});
					} else {
						Notification.error({
							title: '异常',
							message: response.msg
						});
					}
				}, (response) => {
					Notification.error({
						title: '修改失败',
						message: response.msg
					});
				})

			},
			/*	saveData(){
    					this.$httpExt().post("/cas/MSTEST/autoSignleTrial/autoAuditWordSaveData",this.excelData).then((response)=>{
	                        if(response.succ == "ok"){
	                        	this.updateRowsMap =new Map();
	                            Notification({
	                                title: '成功',
							        message: '导入成功!',
							        type: 'success'
	                            });
	                        }else{
	                            Notification.error({
	                                title: '异常',
	                                message: response.msg
	                            });                            
	                        }
	                    },(response)=>{
	                        Notification.error({
	                            title: '修改失败',
	                            message: response.msg
	                        }); 
	                    })
    				
    			},*/
			saveData() {
				this.$confirm('确定保存数据?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$httpExt().post("/cas/MSTEST/autoSignleTrial/autoAuditWordSaveData", this.excelData).then((response) => {
						if(response.succ == "ok") {
							this.excel = false;
							this.updateRowsMap = new Map();
							Notification({
								title: '成功',
								message: '导入成功!',
								type: 'success'
							});
						} else {
							Notification.error({
								title: '异常',
								message: response.msg
							});
						}
					}, (response) => {
						console.log(response.msg);
						Notification.error({
							title: '保存出现异常',
							message: response.msg
						});
					})
				}).catch(() => {});
			},
		}
	}
</script>

<style lang="less">
	.el-table thead th {
		text-align: center;
	}
</style>

  

posted @ 2018-06-11 20:34  杯子茶壶  阅读(152)  评论(0)    收藏  举报