<template>
	<el-row>
		<!-- <el-col :span="4">
			<div class="box">
				<el-scrollbar>
					<basic-container>
						<avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick" />
					</basic-container>
				</el-scrollbar>
			</div>
		</el-col> -->
		<el-col :span="24">
			<basic-container>
				<avue-crud :option="option" :search.sync="search" :table-loading="loading" :data="data" ref="crud"
					v-model="form" :permission="permissionList" @row-del="rowDel" @row-update="rowUpdate"
					@row-save="rowSave" :before-open="beforeOpen" :page.sync="page" @search-change="searchChange"
					@search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
					@size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
					<template slot-scope="scope" slot="menuLeft">
						<el-button v-show="permission.contentAdd" type="primary" size="small"
							@click="handleAdd">新建</el-button>
					</template>
					<template slot-scope="{ row }" slot="isOpen">
						<el-tag :type="row.isOpen == 0 ? 'danger' : 'success'">{{ row.isOpen == 0 ? '停用' : '启用'
							}}</el-tag>
					</template>
					<template slot-scope="{ row }" slot="menu">
						<el-button v-show="permission.contentView" @click="handleView(row)">查看</el-button>
						<el-button v-show="permission.contentEdit" @click="handleEdit(row)">编辑</el-button>
						<el-button @click="startPlan(row)"
							v-show="row.isOpen == 0 && permission.contentSetting">启用</el-button>
						<el-button @click="stopPlan(row)"
							v-show="row.isOpen == 1 && permission.contentSetting">停用</el-button>
						<el-button @click="deletePlan(row)" v-show="permission.contentDelete">删除</el-button>
						<el-button @click="handleDownload(row)"
							v-show="permission.contentDelete">下载</el-button>
						<!-- <el-button @click="handleImport(row)">导入</el-button> -->
					</template>
				</avue-crud>
				<el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :append-to-body="true" width="70%">
					<addDialog :unitData="unitData" :title="dialogTitle" :detailForm="detailForm" ref="addDialog">
					</addDialog>
					<span slot="footer" class="dialog-footer">
						<el-button @click="handleCancel">取 消</el-button>
						<el-button v-show="dialogTitle != '查看'" type="primary" @click="handleConfirm">提 交</el-button>
					</span>
				</el-dialog>
			</basic-container>
		</el-col>
	</el-row>
</template>

<script>
import addDialog from './components/addDialog.vue'
import { mapGetters } from "vuex";
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import { getLimsTree, planCreate, getContentList, getPlanDetail, dealPlan, deletePlan, editPlan } from '@/api/labManagement/inspectionManagement'
export default {
	components: {
		addDialog
	},
	data() {
		const validatePass = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入密码'));
			} else {
				callback();
			}
		};
		const validatePass2 = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请再次输入密码'));
			} else if (value !== this.form.password) {
				callback(new Error('两次输入密码不一致!'));
			} else {
				callback();
			}
		};
		return {
			dialogTitle: '',
			form: {},
			search: {},
			roleBox: false,
			excelBox: false,
			platformBox: false,
			initFlag: true,
			selectionList: [],
			query: {},
			loading: true,
			platformLoading: false,
			page: {
				pageSize: 10,
				currentPage: 1,
				total: 0
			},
			platformPage: {
				pageSize: 10,
				currentPage: 1,
				total: 0
			},
			init: {
				roleTree: [],
				deptTree: [],
			},
			props: {
				label: "title",
				value: "key"
			},
			roleGrantList: [],
			roleTreeObj: [],
			treeDeptId: '',
			treeData: [
				// {
				// 	hasChildren: true,
				// 	id: "1123598813738675201",
				// 	key: "1123598813738675201",
				// 	parentId: "0",
				// 	title: "山东区",
				// 	children: [
				// 		{
				// 			hasChildren: true,
				// 			id: "1123598813738675202",
				// 			key: "1123598813738675202",
				// 			parentId: "1123598813738675202",
				// 			title: "安池实验室",
				// 			value: "1123598813738675202",
				// 			children: [
				// 				{
				// 					hasChildren: false,
				// 					id: "1123598813738675204",
				// 					key: "1123598813738675204",
				// 					parentId: "1123598813738675204",
				// 					title: "三楼",
				// 					value: "1123598813738675204",
				// 				},
				// 				{
				// 					hasChildren: false,
				// 					id: "1123598813738675205",
				// 					key: "1123598813738675205",
				// 					parentId: "1123598813738675205",
				// 					title: "四楼",
				// 					value: "1123598813738675205",
				// 				}
				// 			]
				// 		},
				// 		{
				// 			hasChildren: true,
				// 			id: "1123598813738675203",
				// 			key: "1123598813738675203",
				// 			parentId: "1123598813738675203",
				// 			title: "畜牧局实验室",
				// 			value: "1123598813738675203",
				// 		}
				// 	]
				// }
			],
			unitData: [],
			treeOption: {
				nodeKey: 'id',
				// lazy: true,
				// treeLoad: function (node, resolve) {
				//   const parentId = (node.level === 0) ? 0 : node.data.id;
				//   getDeptLazyTree(parentId).then(res => {
				//     resolve(res.data.data.map(item => {
				//       return {
				//         ...item,
				//         leaf: !item.hasChildren
				//       }
				//     }))
				//   });
				// },
				addBtn: false,
				menu: false,
				size: 'small',
				props: {
					labelText: '标题',
					label: 'title',
					value: 'value',
					children: 'children'
				}
			},
			option: {
				height: 'auto',
				calcHeight: 80,
				tip: false,
				searchShow: true,
				searchMenuSpan: 6,
				border: true,
				index: true,
				selection: true,
				addBtn: false,
				viewBtn: false,
				editBtn: false,
				delBtn: false,
				dialogType: 'dialog',
				dialogClickModal: false,
				searchShowBtn: false,
				refreshBtn: false,
				columnBtn: false,
				menuWidth: 300,
				column: [
					{
						label: "单位名称",
						labelWidth: 120,
						prop: "deptName",
						search: true,
						overHidden: true,
					},
					{
						label: "巡检标题",
						labelWidth: 120,
						prop: "planContent",
						overHidden: true,
					},
					{
						label: "是否启用",
						labelWidth: 120,
						prop: "isOpen",
						overHidden: true,
						slot: true
					},
					{
						label: "创建时间",
						labelWidth: 120,
						prop: "createTime",
						overHidden: true,
					},
					// {
					// 	label: "包含专业/设备",
					// 	labelWidth: 120,
					// 	prop: "major",
					// 	labelWidth: 120,
					// 	overHidden: true,
					// },
					// {
					// 	label: "备注",
					// 	labelWidth: 120,
					// 	overHidden: true,
					// 	prop: "remark",
					// },
				],
			},
			data: [],
			dialogVisible: false,
			addForm: {},
			detailForm: {}
		};
	},
	computed: {
		...mapGetters(["userInfo", "permission"]),
	},
	mounted() {
		this.tableData = this.mergeTableRow(this.tableData, ['majorName'])
		console.log('userInfo--------------->', this.userInfo)
		this.getLeftLab()
		// if(this.userInfo.role_id == '1846419477876510721'){
		// 	this.search.deptName = this.userInfo.deptName
		// }
	},
	methods: {
		objectSpanMethod({ row, column, rowIndex, columnIndex }) {
			// console.log('row--------------->',row)
			// console.log('column--------------->',column)
			// console.log('rowIndex--------------->',rowIndex)
			// console.log('columnIndex--------------->',columnIndex)
			const span = column['property'] + '-span'
			if (row[span]) {
				return row[span]
			}

		},
		// 启用计划
		startPlan(row) {
			this.$confirm('确定启用该计划?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				dealPlan({ id: row.id, isOpen: 1 }).then(res => {
					if (res.data.code == 200) {
						this.$message.success('启用成功')
						this.onLoad()
					}
				})
			})
		},
		// 停用计划
		stopPlan(row) {
			this.$confirm('确定停用该计划?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				dealPlan({ id: row.id, isOpen: 0 }).then(res => {
					if (res.data.code == 200) {
						this.$message.success('停用成功')
						this.onLoad()
					}
				})
			})
		},
		deletePlan(row) {
			this.$confirm('确定删除该计划?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				deletePlan({ ids: row.id }).then(res => {
					if (res.data.code == 200) {
						this.$message.success('删除成功')
						this.onLoad()
					}
				})
			})
		},
		getFile(url) {
			return new Promise((resolve, reject) => {
				//通过请求获取文件blob格式
				let xmlhttp = new XMLHttpRequest();
				xmlhttp.open("GET", url, true);
				xmlhttp.responseType = "blob";
				xmlhttp.onload = function () {
				if (xmlhttp.status == 200) {
					resolve(xmlhttp.response);
				} else {
					reject(xmlhttp.response);
				}
				};
				xmlhttp.send();
			});
		},
		// 下载
		handleDownload(row) {
			getPlanDetail({ id: row.id }).then(res => {
				let data = res.data.data.attaches
				if (data.length > 1) {
					const zip = new JSZip();
					// 下载后压缩包的名称
					const blogTitle = '合同.zip'
					const cache = {};
					const promises = [];
					data.forEach(item => {
						if (item.link) {
							const promise = this.getFile(item.link).then(data => {
								// *下载文件, 并存成ArrayBuffer对象
								const arr_name = item.name.split("/");
								const file_name = arr_name[arr_name.length - 1]; // *获取文件名
								zip.file(file_name, data, { binary: true }); // *逐个添加文件
								cache[file_name] = data;
							});
							promises.push(promise);
						}
					});
					Promise.all(promises).then(() => {
						zip.generateAsync({
							type: "blob", compression: 'DEFLATE',  // *STORE: 默认不压缩; DEFLATE：需要压缩
							compressionOptions: {
								level: 9 // *压缩等级 1~9。1: 压缩速度最快，9: 最优压缩方式
							}
						}).then(content => {
							saveAs(content, blogTitle); // *生成二进制流，利用file-saver保存文件，文件名自定义
						});
					});
				} else if (data.length == 1) {
					fetch(data[0].link, {
						method: 'get',
						heanders: {
							'Content-Type': 'application/json;charset=UTF-8'
						}
					})
						.then(res => res.blob())
						.then(blob => {
							const link = document.createElement('a')
							link.style.display = 'none'
							link.download = data[0].name// 设置下载属性 以及文件名
							link.href = URL.createObjectURL(blob)

							document.body.appendChild(link)
							link.click()
							// 释放的 URL 对象以及移除 a 标签
							URL.revokeObjectURL(link.href)
							document.body.removeChild(link)
						})
				}else{
					this.$message.error('该巡检内容没有维护合同附件')
				}
			})
		},
		/**
 * 方法一
 *  table合并行通用 */
		mergeTableRow(data, merge) {
			if (!merge || merge.length === 0) {
				return data
			}
			merge.forEach((m) => {
				const mList = {}
				data = data && data.map((v, index) => {
					const rowVal = v[m]
					if (mList[rowVal] && mList[rowVal].newIndex === index) {
						mList[rowVal]['num']++
						mList[rowVal]['newIndex']++
						data[mList[rowVal]['index']][m + '-span'].rowspan++
						v[m + '-span'] = {
							rowspan: 0,
							colspan: 0
						}
					} else {
						mList[rowVal] = { num: 1, index: index, newIndex: index + 1 }
						v[m + '-span'] = {
							rowspan: 1,
							colspan: 1
						}
					}
					return v
				})
			})
			return data
		},

		handleAdd() {
			this.dialogTitle = '新建'
			this.dialogVisible = true
			this.detailForm = {}
			this.detailForm.tableData = []
			this.getLeftLab()
		},
		handleView(row) {
			getPlanDetail({ id: row.id }).then(res => {
				console.log('res==============>', res)
				this.dialogTitle = '查看'
				if (res.data.code == 200) {
					this.detailForm = res.data.data
					this.dialogVisible = true
				}
			})
		},
		handleEdit(row) {
			getPlanDetail({ id: row.id }).then(res => {
				console.log('res==============>', res)
				this.dialogTitle = '编辑'
				if (res.data.code == 200) {
					this.detailForm = res.data.data
					this.dialogVisible = true
				}
			})
		},
		handleCancel() {
			this.dialogTitle = ''
			this.$refs.addDialog.addForm = {
				tableData: []
			}
			this.$refs.addDialog.tableData = []
			this.$refs.addDialog.floorArr = []
			this.$refs.addDialog.activeFloor = ''
			this.$refs.addDialog.activeRoom = ''
			this.$refs.addDialog.roomArr = []
			this.dialogVisible = false
		},

		getLeftLab() {
			getLimsTree().then(res => {
				console.log('res==============>', res)
				this.treeData = res.data.data
				this.unitData = res.data.data.filter(item => item.parentId == 0)
				console.log('unitData============>', this.unitData)
			})
		},
		nodeClick(data) {
			this.treeDeptId = data.id;
			this.page.currentPage = 1;
			this.onLoad(this.page);
		},
		currentChange(currentPage) {
			this.page.currentPage = currentPage;
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize;
		},
		searchChange(params, done) {
			this.onLoad()
			done()
		},
		searchReset(params, done) {
			this.onLoad()
			done()
		},
		refreshChange() {
			this.onLoad(this.page, this.query);
		},
		handleConfirm() {
			console.log('addDialog==========>', this.$refs.addDialog)
			let addForm = this.$refs.addDialog.addForm
			// this.$refs.addDialog.tableData.map(item => {
			// 	item.nextStartTime = item.startTime
			// })
			let arr = []
			let arr1 = []
			this.$refs.addDialog.filesList.map(item => {
				arr.push({
					name: item.name,
					link: item.url
				})
			})
			this.$refs.addDialog.drawfiles.map(item => {
				arr1.push({
					name: item.name,
					link: item.url
				})
			})
			let query = {
				id: addForm.id ? addForm.id : null,			// 编辑的时候传
				deptId: addForm.unitId,			// 实验室id
				deptName: addForm.unitName,				// 实验室名称
				planContent: addForm.content,				// 巡检说明
				details: this.$refs.addDialog.tableData,
				attaches: arr,
				draws:arr1
			}
			console.log('query===========>', query)
			if (query.id) {
				editPlan(query).then(res => {
					if (res.data.code == 200) {
						this.$message.success('编辑成功')
						this.onLoad()
						this.$refs.addDialog.addForm = {}
						this.$refs.addDialog.floorArr = []
						this.$refs.addDialog.roomArr = []
						this.$refs.addDialog.activeFloor = ''
						this.$refs.addDialog.activeRoom = ''
						this.dialogVisible = false
					}
				})
			} else {
				planCreate(query).then(res => {
					console.log('res=======>', res)
					if (res.data.code == 200) {
						this.$message.success('新增成功')
						this.onLoad()
						this.$refs.addDialog.addForm = {}
						this.$refs.addDialog.floorArr = []
						this.$refs.addDialog.roomArr = []
						this.$refs.addDialog.activeFloor = ''
						this.$refs.addDialog.activeRoom = ''
						this.dialogVisible = false
					}
				})
			}

		},
		onLoad(page, params = {}) {
			let query = {
				deptName: this.search.deptName ? this.search.deptName : null,			//单位名称
				current: this.page.currentPage,		//页数
				size: this.page.pageSize		//条数
			}
			this.loading = true
			getContentList(query).then(res => {
				this.data = res.data.data.records
				this.page.total = res.data.data.total
				this.loading = false
			})
		},
	}
};
</script>

<style>
.box {
	height: 800px;
}

.el-scrollbar {
	height: 100%;
}

.box .el-scrollbar__wrap {
	overflow: scroll;
}
</style>