<template>
	<div class="information-export-con">
		<Form ref="formData" :model="formData" :rules="ruleValidate" :label-width="0">
			<FormItem prop="sql">
				<Input v-model="formData.sql" type="textarea" :rows="5" placeholder="请输入要执行的SQL..." />
			</FormItem>
		</Form>
		<div class="form-btn">
			<Button>清空</Button>
			<Button type="primary" @click="submitData">确定</Button>
		</div>
		<div class="form-down" v-if="exportData.url">
			<p>SQL执行成功，请点击右侧按钮，下载检索数据</p>
			<Button :size="10" icon="md-download" shape="circle" @click="downLoad"></Button>
		</div>
		<div class="sql-error" v-if="exportData.error">
			<p class="label">SQL执行失败，异常信息如下:</p>
			<p>{{exportData.error}}</p>
		</div>
	</div>
</template>
<script>
export default {
	data(){
		const validateSql = (rule, value, callback) => {
			if (!value) {
				callback(new Error('请输入要执行的SQL'));
			} else {
				var re= /update|delete|insert|%/i;
				if (re.test(value.toLowerCase())){
					callback(new Error('禁止输入update/delete/insert'));
				}
				callback();
			}
		};
		return{
			formData:{
				sql:""
			},
			exportData:{
				error:'',
				url:""
			},
			ruleValidate:{
				sql: [
					{ validator: validateSql, trigger: 'blur' }
				],
			}
		}
	},
	methods:{
		submitData(){
			this.exportData={
				error:'',
				url:""
			}
			this.$refs['formData'].validate((valid) => {
				if (valid) {
					this.api({
						apiName: 'dataInfocensusexport',
						postdata: this.formData,
						complete: () => {
							this.loading = false
						},
						success: (res) => {
							this.$Notice.success({ title: '提交成功,请点击下载！' })
							this.exportData.url=res.data
						},
						error:(err)=>{
							console.log(err)
							this.$Notice.success({ title: 'sql语句错误' })
							this.exportData.error=err.data
						}
					})
				} else {
					this.formModal = true
				}
			})
		},
		downLoad(){
			if(!this.exportData.url){
				this.$Message.error('请提交sql！')
			}
			window.open(this.exportData.url)
		}
	}
}
</script>
<style lang="less" scoped>
.information-export-con{
	padding-top: 10px;
	.form-btn{
		display: flex;
		justify-content: center;
		.ivu-btn{
			margin:0 30px;
			width: 200px;
			height: 50px;
		}
	}
	.form-down{
		display: flex;
		align-items: center;
		padding: 10px;
		.ivu-btn{
			margin-left: 10px;
			border: 0;
			background-color: transparent;
		}
	}
	.sql-error{
		padding: 20px 10px;
		.label{
			font-size: 14px;
			margin-bottom: 10px;
		}
	}
}
</style>