<template>
	<div class="qpage">
		<el-form :inline="true" :model="queryForm" class="query-form-inline"  label-width="auto">
		  <el-form-item label="备份对象">
		    <el-select v-model="queryForm.tabsort" clearable>
				<el-option v-for="(item,index) in backupTargets" :key="index" :label="item.name" :value="item.sort"/>
			</el-select>
		  </el-form-item>
		  
		  <el-form-item label="备份时间">
		    <el-date-picker
		            v-model="queryForm.dataTime"
		            type="daterange"
		            start-placeholder="开始时间"
		            end-placeholder="截止时间"
		            :unlink-panels="true"
		    		   value-format="YYYY-MM-DD"
		  						  
		          />
		  </el-form-item>
		  
		  <el-form-item>
		    <el-button type="primary" :loading="isQuerying" @click="queryHandle">检索</el-button>
		  </el-form-item>
		</el-form>
		
		<div class="qpage-body">
			<CrudTable 
			ref="crudTable"
			page-info-opts="total, prev, pager, next,sizes"
			url="/backup/log/query"
			:pageSize="20"
			>
			  
				<template #tabColumns={indexGenerate}>
					  <el-table-column type="index" :index="indexGenerate" label="序号" width="60" align="center"/>
					  <el-table-column prop="taskName" label="备份任务" width="160" />
					  <el-table-column prop="startTime" label="开始时间" width="160" />
					  <el-table-column prop="endTime" label="结束时间" width="160" />
					  <el-table-column prop="duration" label="用时(秒)" width="100" />
					  <el-table-column prop="operator" label="操作人" width="120"/>
					  <el-table-column prop="status" label="状态" width="90">
						  <template #default="scope">
							  {{ {'success':'成功','running':'备份中','failed':'已失败'}[scope.row.status] || '' }}
						  </template>
					  </el-table-column>
					  <el-table-column prop="note" label="备份文件" width="100" align="center">
						  <template #default="scope">
							  <el-button type="primary"  plain  size="small" v-if="scope.row.status=='success'" @click="dwnbackup(scope.row)">下载</el-button>
						  </template>
						  
					  </el-table-column>
					  
				</template>
				
			</CrudTable>
		</div>
		
		
		
	</div>
</template>

<script setup>
	import {reactive,ref,onMounted,toRaw} from 'vue'
	import CrudTable from "../../components/crudtable/CrudTable.vue"
	import {ElMessageBox,ElMessage} from 'element-plus'
	import api from "../../api/dbBackup.js"
	
	const crudTable=ref(null)
	
	const isQuerying=ref(false)
	
	
	
	const queryForm = reactive({
	  tabsort: null,
	  dataTime:null
	})
	
	const backupTargets=ref([])
	
	const queryHandle=()=>{
		isQuerying.value=true
		let formdata=toRaw(queryForm)
		let [startTime,endTime]=formdata.dataTime||[]
		formdata['startTime']=startTime
		formdata['endTime']=endTime
		crudTable.value.query(formdata).then(resp=>{
			isQuerying.value=false
		})
		
	}
	
	onMounted(()=>{
		load()
	})
	
	const load=()=>{
		api.getBackupTarget().then(resp=>{
			if(resp.code!=0){
				ElMessage.error(resp.msg || '加载数据失败')
			}
			else{
				backupTargets.value=respProcess(resp.data)
			}
		}).catch(err=>{
			console.log(err)
			ElMessage.error('加载数据出错')
		})
	}
	
	const respProcess=(datas)=>{
		let sortary=[],sortidx={}
		datas.forEach(data=>{
			if(!sortidx[data.tagCode]){
				sortary.push({sort:data.tagCode,name:data.tagName})
				sortidx[data.tagCode]=true
			}
		})
		let defaultBack={sort:'glb',name:'全库表结构'}
		return [defaultBack,...sortary]
	}
	

	const dwnbackup=(record)=>{
		api.downloadBackup(record.backupId).then(resp=>{
			//console.log(resp)
			
			const fileReader = new FileReader();
			fileReader.readAsText(resp.data)
			fileReader.onload = (event) => {
				try{
					const data = JSON.parse(event.target.result)
					if(data.code!=0){
						ElMessage.error(data.msg || '下载文件失败')
					}
				}
				catch(err){
					parseDownloadFile(resp)
				}
			}
		}).catch(err=>{
			console.log(err)
			ElMessage.error('下载文件出现网络错误')
		})
	}
	
	const parseDownloadFile=(res)=>{
		const fileName = decodeURI(res.headers['content-disposition']).replace(/\w+;filename=(.*)/, '$1')
		//console.log(fileName)
		const blob = new Blob([res.data], { type: "application/octet-stream"})
		const fileUrl = window.URL.createObjectURL(blob)
		
		let link = document.createElement('a') 
		link.href = fileUrl 
		link.download = decodeURI(fileName) //设置下载的文件名
		link.style.display = 'none'  
		document.body.appendChild(link) 
		link.click() 
		 
		document.body.removeChild(link)
		window.URL.revokeObjectURL(fileUrl)
		
	}
	
	
	
	
	
	
	
	
</script>

<style scoped>
	@import url('../../assets/css/qpage.css');
	
	.edit-form-item{
		width:260px;
	}
</style>