<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 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 @click="handleView(row)">查看</el-button>
						<el-button @click="handleEdit(row)">编辑</el-button>
						<el-button @click="startPlan(row)" v-show="row.isOpen == 0">启用</el-button>
						<el-button @click="stopPlan(row)" v-show="row.isOpen == 1">停用</el-button>
						<el-button @click="deletePlan(row)">删除</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 != '查看'" @click="handleSave">保 存</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 { 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:{}
		};
	},
	mounted() {
		this.tableData = this.mergeTableRow(this.tableData, ['majorName'])
		console.log('tableData--------------->', this.tableData)
		this.getLeftLab()
	},
	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()
					}
				})
			})
		},
		/**
 * 方法一
 *  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 = {}
		},
		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;
		},
		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 query = {
				id:addForm.id ? addForm.id : null,			// 编辑的时候传
				deptId:addForm.unitId,			// 实验室id
				deptName:addForm.unitName,				// 实验室名称
				planContent:addForm.content,				// 巡检说明
				details:this.$refs.addDialog.tableData,
				attaches:this.$refs.addDialog.filesList
			}
			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 = {
				unitName:this.search.unitName ? this.search.unitName : null,			//单位名称
				positionId:this.search.positionId ? this.search.positionId : null,			//位置id
				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>