<template>
	<div class="g-main">
		<div v-show="pageType == 'list'">
			<div class="m-search">
				<el-form :inline="true" :model="formData" ref="ref_searchform" :label-width="'100px'">
					<div>
						<el-form-item label="所属组织" prop="gridId">
							<el-select class="u-item-width-normal" v-model="formData.gridId" placeholder="全部" size="small" clearable>
								<el-option v-for="item in gridList" :key="item.value" :label="item.label" :value="item.value"></el-option>
							</el-select>
						</el-form-item>

						<el-form-item label="隐患场所" prop="dangerPlaceName">
							<el-input v-model="formData.dangerPlaceName" class="u-item-width-normal" size="small" clearable placeholder="请输入"></el-input>
						</el-form-item>
						<el-form-item label="处理情况" prop="handleState">
							<el-select v-model="formData.handleState" placeholder="请选择" size="small" clearable class="u-item-width-normal">
								<el-option v-for="item in handleStateArray" :key="item.value" :label="item.label" :value="item.value"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="隐患内容" prop="dangerContent">
							<el-input v-model="formData.dangerContent"  class="u-item-width-normal" size="small" clearable placeholder="请输入"></el-input>
						</el-form-item>
						<el-form-item label="上报人" prop="reportPerson">
							<el-input v-model="formData.reportPerson" class="u-item-width-normal" size="small" clearable placeholder="请输入"></el-input>
						</el-form-item>
						<el-form-item label="隐患位置" prop="location">
							<el-input v-model="formData.location" class="u-item-width-normal" size="small" clearable placeholder="请输入"></el-input>
						</el-form-item>
						<el-form-item label="上报时间" prop="reportTime">
							
								<el-date-picker v-model="formData.reportTime" type="date" class="input-width" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
							
						</el-form-item>
						<el-row>
							<el-col :span="24" align="right">
								<el-button style="margin-left: 30px" size="small" type="primary " @click="handleSearch">查询</el-button>
								<el-button style="margin-left: 10px" size="small" class="diy-button--white" @click="resetSearch">重置</el-button>
							</el-col>
						</el-row>
					</div>
				</el-form>
			</div>
			<div class="m-table">
				<div class="div_btn">
					<el-button size="small" type="primary " @click="handleAdd({}, 'add')">新增</el-button>
					<el-button class="diy-button--white" size="small" @click="handleExportModule('room')">下载导入模板</el-button>
					<el-upload
						:headers="$getElUploadHeaders()"
						ref="upload"
						class="upload-btn"
						action="uploadUlr"
						:limit="1"
						:accept="'.xls,.xlsx'"
						:with-credentials="true"
						:show-file-list="false"
						:auto-upload="true"
						:on-progress="handleProgress"
						:on-success="handleExcelSuccess"
						:before-upload="beforeExcelUpload"
						:http-request="uploadHttpRequest"
						style="display: inline-block;margin:0px 10px"
					>
						<el-button size="small" class="diy-button--white" :loading="importLoading">导入模板</el-button>
					</el-upload>

					<el-button @click="handleExport" class="diy-button--white" size="small">导出</el-button>
				</div>
				<el-table :data="tableData" border class="m-table-item" style="width: 100%" @selection-change="handleSelectionChange" :height="maxTableHeight">
					<el-table-column label="" fixed="left" type="selection" align="center" width="50" />
					<el-table-column label="序号" fixed="left" type="index" align="center" width="50" />
					<el-table-column prop="gridName" align="center" label="所属组织" :show-overflow-tooltip="true"></el-table-column>
					<el-table-column prop="location" align="center" width="80" label="隐患位置"></el-table-column>
					<el-table-column prop="dangerPlaceName" label="隐患场所" min-width="140" align="center" :show-overflow-tooltip="true" />
					<el-table-column prop="reportPerson" align="center" width="110" label="上报人" :show-overflow-tooltip="true"></el-table-column>
					<el-table-column prop="mobile" align="center" :show-overflow-tooltip="true" label="联系电话"></el-table-column>
					<el-table-column prop="dangerContent" align="center" :show-overflow-tooltip="true" label="隐患内容"></el-table-column>

					<el-table-column prop="handleStateName" align="center" label="处理结果" :show-overflow-tooltip="true"></el-table-column>
					<el-table-column fixed="right" label="操作" align="center" width="130">
						<template slot-scope="scope">
							<el-button @click="handleAdd(scope.row, 'view')" type="text" size="small">查看</el-button>
							<el-button style="margin-right: 10px" @click="handleAdd(scope.row, 'edit')" size="small" type="text">编辑</el-button>
							<el-button @click="handleDel(scope.row)" type="text" size="small" class="">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div>
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page.sync="pageNo"
						:page-sizes="[20, 50, 100, 200]"
						:page-size="parseInt(pageSize)"
						layout="sizes, prev, pager, next, total"
						:total="total"
					></el-pagination>
				</div>
			</div>
		</div>
		<div v-if="pageType != 'list'">
			<addForm
				:pageType="pageType"
				:disabled="disabled"
				:detailId="detailId"
				:detailData="detailData"
				@handleClose="handleClose"
				@handleOk="handleOk"
				@dialogOk="handleEditSuccess"
			/>
		</div>
	</div>
</template>

<script>
import { requestPost } from '@/js/dai/request';
import nextTick from 'dai-js/tools/nextTick';
import { mapGetters } from 'vuex';
import addForm from './addForm.vue';
import axios from 'axios';

export default {
	data() {
		return {
			importLoading: false,
			disabled: false,
			user: '',
			agencyId: '',
			formData: {
				gridId: '',
				dangerPlaceName: '',
				dangerContent: '',
				reportPerson: '',
				reportTime: '',
				handleState: '',
				location: ''
			},
			pageType: 'list', // 列表list 新增add  处理dispose 详情info
			gridList: [], //所属网格list--场所区域
			placeTypeList: [], //场所类型
			tableData: [],
			resultArray: [{ value: '0', label: '合格' }, { value: '1', label: '不合格' }],
			handleStateArray: [{ value: '0', label: '待处理' }, { value: '1', label: '处理完成' }],
			pageNo: 1,
			pageSize: window.localStorage.getItem('pageSize') || 20,
			total: 1,
			detailId: '',
			detailData: {},
			multipleSelection: [],
			rowObj: {}
		};
	},
	components: { addForm },
	created() {},
	computed: {
		maxTableHeight() {
			return this.$store.state.inIframe ? this.clientHeight - 410 + this.iframeHeigh : this.clientHeight - 410;
		},
		...mapGetters(['clientHeight', 'iframeHeight'])
	},
	watch: {},
	mounted() {
		this.user = this.$store.state.user;
		this.agencyId = this.user.agencyId;
		this.loadGrid();

		this.getTableData();
	},
	methods: {
		handleSelectionChange(val) {
			this.multipleSelection = [];
			val.forEach(element => {
				this.multipleSelection.push(element.icEventId);
			});
		},
		handleSearch(val) {
			console.log(this.formData);
			this.pageNo = 1;
			this.getTableData();
		},
		async loadGrid() {
			const url = '/gov/org/customergrid/gridoption';
			let params = {
				agencyId: this.agencyId,
				purpose: 'query'
			};
			const { data, code, msg } = await requestPost(url, params);
			if (code === 0) {
				this.gridList = data;
			} else {
				this.$message.error(msg);
			}
		},

		async handleExport() {
			// 导出
			const url = '/actual/base/hiddenDangerRecord/export';
			const { pageSize, pageNo, formData } = this;
			axios({
				url: window.SITE_CONFIG['apiURL'] + url,
				method: 'post',
				data: {
					pageSize,
					pageNo,
					...formData
				},
				responseType: 'blob'
			})
				.then(res => {
					let fileName = window.decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]);
					console.log('filename', fileName);
					let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
					var url = window.URL.createObjectURL(blob);
					var aLink = document.createElement('a');
					aLink.style.display = 'none';
					aLink.href = url;
					aLink.setAttribute('download', fileName);
					document.body.appendChild(aLink);
					aLink.click();
					document.body.removeChild(aLink); //下载完成移除元素
					window.URL.revokeObjectURL(url); //释放掉blob对象
				})
				.catch(err => {
					console.log('获取导出情失败', err);
					return this.$message.error('网络错误');
				});
		},
		handleAdd(row, type) {
			if (row.id) {
				this.detailId = row.id;
			}
			this.pageType = type;
			if (type == 'view') {
				this.disabled = true;
			} else {
				this.disabled = false;
			}
		},
		handleClose() {
			this.pageType = 'list';
			this.detailId = '';
			this.getTableData();
		},
		handleOk() {
			this.pageType = 'list';
			this.detailId = '';
			this.pageNo = 1;
			this.getTableData();
		},
		handleEditSuccess() {
			this.handleClose();
			this.getTableData();
		},
		async handleDel(rowData) {
			let message = '确认删除?';
			this.$confirm(message, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.del(rowData.id);
				})
				.catch(err => {});
		},
		async del(id) {
			const url = '/actual/base/hiddenDangerRecord/delete';
			let idArr=[id]
			const { data, code, msg } = await requestPost(url, idArr);
			if (code === 0) {
				this.$message.success('删除成功！');
				this.getTableData();
			} else {
				this.$message.error('操作失败！');
			}
		},
		async getTableData() {
			const url = '/actual/base/hiddenDangerRecord/page';
			// const url = 'http://yapi.elinkservice.cn/mock/330/actual/base/enterprise/list';
			const { pageSize, pageNo, formData } = this;
			const { data, code, msg } = await requestPost(url, {
				pageSize,
				pageNo,
				...formData
			});
			if (code === 0) {
				this.total = data.total || 0;
				this.tableData = data.list
					? data.list.map(item => {
							return item;
					  })
					: [];
			} else {
				this.$message.error(msg);
			}
		},
		handleSizeChange(val) {
			this.pageSize = val;
			window.localStorage.setItem('pageSize', val);
			this.getTableData();
		},
		handleCurrentChange(val) {
			this.pageNo = val;
			this.getTableData();
		},
		resetSearch() {
			this.formData = {
				gridId: '',
				dangerPlaceName: '',
				dangerContent: '',
				reportPerson: '',
				reportTime: '',
				handleState: '',
				location: ''
			};
			this.pageNo = 1;
			this.getTableData();
		},
		async handleExportModule() {
			let url = '/actual/base/hiddenDangerRecord/downloadTemplate';
			let params = {};
			await this.$http({
				method: 'POST',
				url,
				responseType: 'blob',
				data: params
			})
				.then(res => {
					// this.download(res.data, title + '.xls')
					if (res.headers['content-disposition']) {
						let fileName = window.decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]);
						console.log('filename', fileName);
						let blob = new Blob([res.data], {
							type: 'application/vnd.ms-excel'
						});
						var url = window.URL.createObjectURL(blob);
						var aLink = document.createElement('a');
						aLink.style.display = 'none';
						aLink.href = url;
						aLink.setAttribute('download', fileName);
						document.body.appendChild(aLink);
						aLink.click();
						document.body.removeChild(aLink); //下载完成移除元素
						window.URL.revokeObjectURL(url); //释放掉blob对象
					} else this.$message.error('下载失败');
				})
				.catch(err => {
					console.log('err', err);
					return this.$message.error('网络错误');
				});
		},
		handleExcelSuccess(res, file) {
			if (res.code === 0 && res.msg === 'success') {
				console.log('resss---ppp', res);
			} else {
				this.$message.error(res.msg);
			}
		},
		handleProgress(event, file, fileList) {
			console.log('percentage', file.percentage);
		},

		beforeExcelUpload(file) {
			console.log('file', file);
			const isType = file.type === 'application/vnd.ms-excel';
			const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
			const fileType = isType || isTypeComputer;
			const isLt1M = file.size / 1024 / 1024 < 10;
			if (!fileType) {
				this.$message.error('上传文件只能是xls/xlsx格式！');
			}

			if (!isLt1M) {
				this.$message.error('上传文件大小不能超过 10MB!');
			}
			return fileType && isLt1M;
		},

		async uploadHttpRequest(file) {
			this.importLoading = true;
			this.importBtnTitle = '正在上传中...';
			const formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
			formData.append('file', file.file); //添加文件对象
			formData.append('code', ''); //添加文件对象
			await this.$http
				.post('/actual/base/hiddenDangerRecord/import', formData)
				.then(res => {
					console.log('res-up', res);
					if (res.data.code == 0 && res.data.msg == 'success') {
						console.log(res.data.data);
						const data = res.data.data;

						this.dataList = [
							...Object.keys(data.option.exist).map(k => {
								return {
									index: k,
									srcField: data.option.exist[k],
									exist: true,
									field: data.option.exist[k]
								};
							}),
							...Object.keys(data.option.notExist).map(k => {
								return {
									index: k,
									srcField: data.option.notExist[k],
									exist: false,
									field: ''
								};
							})
						];
						this.importOption = data.option;
						this.importCode = data.code;
						this.fileData = file;
					} else this.$message.error(res.data.msg);
				})
				.catch(err => {
					console.log('失败', err);
					file.onError(); //上传失败的文件会从文件列表中删除
					// this.$message.error('导入失败')
				});
			this.importLoading = false;
			this.importBtnTitle = '导入';
			this.$refs.upload.clearFiles();
		}
	}
};
</script>

<style lang="scss" scoped>
@import '@/assets/scss/modules/management/list-main.scss';
.m-search {
	.u-item-width-normal {
		width: 200px;
	}
}
</style>
