<template>
	<div>
		<el-card :body-style="cardBodyStyle">
			<el-form :inline="true">
				<el-form-item style="margin-bottom: 0px;">
					<el-input v-model="query" placeholder="请输入查询条件" style="width: 200px;"></el-input>
				</el-form-item>
				<el-button type="primary" @click="search">查询</el-button>
				<el-button type="success" @click="handleSave">保存</el-button>
				<el-button type="danger" @click="handleClear">清空</el-button>
				<el-button type="primary" plain @click="handleAdd">新增</el-button>

			</el-form>
		</el-card>


		<el-row>
			<el-col :span="6">
				<el-card :body-style="cardBodyStyle">
					<el-table :data="tableData" border highlight-current-row @row-click="handleCurrentRowChange">
						<el-table-column prop="id" label="编号" width="50" v-if="isShow">
						</el-table-column>
						<el-table-column prop="roleCode" label="角色编码" header-align="center" align="center"
							show-overflow-tooltip>
						</el-table-column>
						<el-table-column prop="roleName" label="角色名称" header-align="center" align="center"
							show-overflow-tooltip>
						</el-table-column>
						<el-table-column label="操作" header-align="center" align="center" width="160px">
							<template #default="scope">
								<el-button size="small" plain type="warning"
									@click="handleEdit(scope.row)">编辑</el-button>
								<el-button size="small" plain type="danger"
									@click="handleDelete(scope.row.id)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes"
						:total="totalRows" layout=" sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
						@current-change="handleCurrentChange">
					</el-pagination>
				</el-card>
			</el-col>
			<el-col :span="4">
				<el-card :body-style="cardBodyStyle">
					<el-select v-model="application" clearable value-key="id" @change="changeApplication">
						<el-option v-for="option in options" :key="option.id" :value="option"
							:label="option.applicationName" />
					</el-select>
				</el-card>
				<el-card :body-style="cardBodyStyle">
					<el-checkbox-group v-model="checkList">
						<el-checkbox v-for="item in buttonList" :key="item.id" :label="item.id"
							@change="handleChange">{{item.buttonName}}</el-checkbox>
					</el-checkbox-group>
				</el-card>

				<el-card :body-style="cardBodyStyle" v-if="refreshMenuTree">
					<el-tree :data="dataTree" :props="defaultProps" ref="treeRef" node-key="id"
						@check-change="getCheckedNodes" show-checkbox @node-click="handleNodeClick" current-node-key
						accordion :default-expanded-keys="menuExpandedKeys">
					</el-tree>
				</el-card>
			</el-col>

			<el-col :span="6">
				<el-card :body-style="cardBodyStyle">
					<div v-if="role.id!=null">当前角色：{{role.roleName}}
					</div>
					<div v-else>未选择角色
					</div>

					<div v-if="menu.id!=null&&role.id!=null">当前菜单：{{menu.text}};配置该菜单数据权限
					</div>
					<div v-else-if="menu.id==null&&role.id!=null">未选择菜单,配置角色通用数据权限
					</div>
					<div v-else>未选择菜单
					</div>

					<div>
						<el-radio-group v-model="personalFlag" @change="personalFlagChange">
							<el-radio label="1">仅个人数据</el-radio>
							<el-radio label="2">本部门及以下</el-radio>
							<el-radio label="3">任意部门及以下</el-radio>
						</el-radio-group>
					</div>
					<div>
						<el-radio-group v-model="defaultFlag" @change="defaultFlagChange">
							<el-radio label="0">角色权限</el-radio>
							<el-radio label="1">菜单权限</el-radio>
						</el-radio-group>
					</div>
					<div v-if="refreshTree">
						<el-tree :data="departmentTree" :props="defaultPropsDepartment" node-key="id" show-checkbox
							accordion ref='departmentTreeRef' :expand-on-click-node="false"
							:default-expanded-keys="departmentExpandedKeys" check-strictly>
						</el-tree>
					</div>
				</el-card>
			</el-col>

			<el-col :span="8">
				<el-tabs v-model="activeName" type="border-card" @tab-click="handleTabsClick">
					<el-tab-pane label="权限" name="role">
						<el-card :body-style="cardBodyStyle">
							<el-table :data="tableDataRoleMenu" border>
								<el-table-column prop="menuOpenCs" label="权限类型" show-overflow-tooltip
									header-align="center" align="center">
								</el-table-column>
								<el-table-column prop="menuName" label="菜单名称" show-overflow-tooltip
									header-align="center" align="center">
								</el-table-column>
								<el-table-column prop="menuCode" label="菜单编码" show-overflow-tooltip
									header-align="center" align="center">
								</el-table-column>
								<el-table-column label="操作" width="100px" header-align="center" align="center">
									<template #default="scope">
										<el-button size="small" plain type="danger"
											@click="handleDeleteRoleMenu(scope.row)">删除</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-card>
					</el-tab-pane>
					<el-tab-pane label="人员" name="user">

						<el-card :body-style="cardBodyStyle">
							<el-button type="primary" plain @click="handleAddUserRole">添加</el-button>
						</el-card>
						<el-card :body-style="cardBodyStyle">
							<el-table :data="tableDataUserRole" border>
								<el-table-column prop="userName" label="用户名" show-overflow-tooltip header-align="center"
									align="center">
								</el-table-column>
								<el-table-column prop="userDesc" label="姓名" show-overflow-tooltip header-align="center"
									align="center">
								</el-table-column>
								<el-table-column label="操作" width="100px" header-align="center" align="center">
									<template #default="scope">
										<el-button size="small" plain type="danger"
											@click="handleDeleteUserRole(scope.row)">删除</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-card>
					</el-tab-pane>
				</el-tabs>
			</el-col>

			<el-col :span="4">

			</el-col>

		</el-row>





		<el-dialog :close-on-click-modal="false" v-dialogDrag v-model="dialogVisible" width="400px">
			<el-form :model="sysRole" label-position="right" label-width="80px">
				<!-- <el-form-item label="编码">
    			<el-input v-model="sysRole.id" placeholder=""></el-input>
    		</el-form-item> -->
				<el-form-item label="角色编码">
					<el-input v-model="sysRole.roleCode"></el-input>
				</el-form-item>
				<el-form-item label="角色名称">
					<el-input v-model="sysRole.roleName"></el-input>
				</el-form-item>

			</el-form>
			<span slot="footer">
				<el-button type="success" @click="handleSaveRole">保存</el-button>
				<el-button type="danger" @click="handleCancelSaveRole">取消</el-button>
			</span>

		</el-dialog>




		<el-dialog :close-on-click-modal="false" draggable title="编辑信息" v-model="dialogVisibleUser" width="500px">
			<el-card :body-style="cardBodyStyle">
				<el-input v-model="queryUserDesc" placeholder="请输入查询条件"
					style="width :200px; margin-right: 10px;"></el-input>
				<el-button type="primary" @click="searchUser">查询</el-button>
			</el-card>
			<el-card :body-style="cardBodyStyle">
				<el-table :data="tableDataUser" border>
					<el-table-column prop="userName" label="用户名" width="150" header-align="center" align="center"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column prop="userDesc" label="姓名" width="150" header-align="center" align="center"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column label="操作" header-align="center" align="center">
						<template #default="scope">
							<el-button size="small" type="primary" @click="handleAddUser(scope.row)">选择</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination @size-change="UserhandleSizeChange" @current-change="UserhandleCurrentChange"
					:current-page="UsercurrentPage" :page-sizes="UserpageSizes" :page-size="UserpageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="UsertotalRows">
				</el-pagination>
			</el-card>
		</el-dialog>


	</div>
</template>


<script setup>
	import {
		ref,
		reactive,
		onMounted,
		getCurrentInstance,
		nextTick
	} from 'vue'
	const {
		proxy
	} = getCurrentInstance()

	import style from '@/tools/style'
	const cardBodyStyle = ref(style.card)

	onMounted(() => {
		getTableData()
		// getDataTree()
		getDepartmentTree()
		getApplications()
	})

	const activeName = ref('role')
	const query = ref('')
	const isShow = ref(false)
	const loading = ref(false)
	const tableData = ref([])


	const currentPage = ref(1)
	const totalRows = ref(0)
	const pageSizes = ref([5, 10, 20, 50, 100])
	const pageSize = ref(10)
	//查询条件
	const queryRoleName = ref('')

	const sysRole = ref({})
	const dataTree = ref([])
	const menuExpandedKeys = ref([])
	const defaultProps = ref({
		children: 'children',
		label: 'text'
	})
	const defaultPropsDepartment = ref({
		children: 'children',
		label: 'deptName'
	})
	const checkedMenuIdLeaf = ref([])
	const checkedMenuId = ref([])
	const halfCheckMenuId = ref([])



	const role = ref({})
	const menu = ref({})
	const buttonList = ref([])
	const checkList = ref([])


	const departmentTree = ref([])
	const departmentExpandedKeys = ref([])

	const personalFlag = ref('0')
	const defaultFlag = ref('0')

	const dialogVisible = ref(false)
	const treeRef = ref()
	const departmentTreeRef = ref()
	// 获取table数据
	const getTableData = () => {
		//console.log("获取table数据getTableData")
		var url = 'framework/SysRole/query'
		var param = {
			page: currentPage.value,
			rows: pageSize.value,
			roleName: query.value
		}
		proxy.$axios.get(url, param).then(response => {
			tableData.value = response.data.data.records
			totalRows.value = response.data.data.total
			if (response) {
				loading.value = false
			} else {
				loading.value = true
			}
		});
	}
	// 修改每页条数事件
	const handleSizeChange = (val) => {
		pageSize.value = val
		getTableData()
	}
	// 修改当前页事件
	const handleCurrentChange = (val) => {
		currentPage.value = val
		getTableData()
	}
	const search = () => {
		getTableData()
	}
	const getDataTree = () => {
		var url = 'framework/SysParent/queryMenuByApplicationId'
		// var url = 'framework/SysParent/queryMenu'
		var param = {
			applicationId: application.value.id
		}
		proxy.$axios.get(url, param).then(response => {
			dataTree.value = response.data.data
			if (dataTree.value.length == 1) {
				for (var node of dataTree.value) {
					menuExpandedKeys.value.push(node.id)
				}
			}

		});
	}


	const refreshMenuTree = ref(true)
	const isDisabled = (data, node) => {
		return 'ture'
	}
	const handleCurrentRowChange = (val) => {
		role.value = val
		var url = 'framework/SysRoleMenu/queryByRoleIdOnlyLeaf'
		var param = {
			roleId: role.value.id
		}
		proxy.$axios.get(url, param).then(response => {
			var str = response.data.data
			var arr = str.split(",")
			treeRef.value.setCheckedKeys(arr)

			refreshMenuTree.value = true
			nextTick(() => {
				menuExpandedKeys.value = arr
			})
		});
		getMenuButton()
		getRoleMenuButton()
		getPermission()
		getRoleMenu()
		getUserRole()
	}

	const getCheckedNodes = (data, checked, indeterminate) => {
		checkedMenuIdLeaf.value = treeRef.value.getCheckedKeys('true')
		checkedMenuId.value = treeRef.value.getCheckedKeys()
		halfCheckMenuId.value = treeRef.value.getHalfCheckedKeys()
	}
	const handleSave = () => {
		if (role.value == null || role.value.id == null || role.value.id == '') {
			ElMessage({
				type: 'error',
				message: '请选择角色',
			});
			return
		}

		var checkDepartmentId = departmentTreeRef.value.getCheckedKeys()

		var url = 'framework/SysRoleMenu/saveForApplication'
		var param = {
			roleId: role.value.id,
			menuId: menu.value.id,

			checkedMenuIdLeaf: checkedMenuIdLeaf.value.join(','),
			checkedMenuId: checkedMenuId.value.join(','),
			halfCheckMenuId: halfCheckMenuId.value.join(','),

			checkedButton: checkList.value.join(','),
			checkedDepartment: checkDepartmentId.join(','),
			personalFlag: personalFlag.value,
			defaultFlag: defaultFlag.value,

			applicationId: application.value.id
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				ElMessage({
					type: 'success',
					message: '保存成功!',
				});
 getRoleMenu()
			} else {
				ElMessage({
					type: 'error',
					message: '保存失败' + response.data.msg,
				});
			}

		});
	}

	const getMenuButton = () => {
		var url = 'framework/SysMenu/queryMenuButton'
		var param = {
			menuId: menu.value.id
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				buttonList.value = response.data.data
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败' + response.data.msg,
				});
			}
		});
	}

	const getRoleMenuButton = () => {
		var url = 'framework/SysRoleMenu/queryRoleMenuButton'
		var param = {
			roleId: role.value.id,
			menuId: menu.value.id
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				checkList.value = response.data.data
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败' + response.data.msg,
				});
			}
		});
	}

	const handleNodeClick = (data) => {
		menu.value = data
		if (role.value.id != '' && menu.value.id != '' && data.children.length == 0) {
			getMenuButton()
			getRoleMenuButton()
			getPermission()
			// defaultFlag.value = '1'
		} else {
			buttonList.value = []
		}


	}
	const handleChange = () => {
		// console.log(checkList)
	}



	const getDepartmentTree = () => {
		var url = 'framework/SysDepartment/queryTree?fid=0'
		var param = {}
		proxy.$axios.get(url, param).then(response => {
			departmentTree.value = response.data.data
			if (dataTree.value.length == 1) {
				for (var node of departmentTree.value) {
					departmentExpandedKeys.value.push(node.id)
				}
			}
		});
	}
	const refreshTree = ref(true)
	const expandedKeys = ref([])
	const getPermission = () => {
		var url = 'framework/SysRoleMenu/queryPermission'
		var param = {
			roleId: role.value.id,
			menuId: menu.value.id
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				if (response.data.data != 'noPermission') {
					personalFlag.value = response.data.data
						.personalFlag
					defaultFlag.value = response.data.data
						.defaultFlag
					departmentTreeRef.value.setCheckedKeys(
						response.data.data
						.checkedDepartment) 

					//tree树形结构展开已选节点
					refreshTree.value = true
					nextTick(() => {
						departmentExpandedKeys.value = response.data.data.checkedDepartment
					})


				} else {
					personalFlag.value = '1'
					defaultFlag.value = '0'
					// if (menu.value.id == null || menu.value.id == '') {
						
					// } else {
					// 	defaultFlag.value = '1'
					// }
					departmentTreeRef.value.setCheckedKeys([])
				}
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败' + response.data
						.msg,
				});
			}
		});
	}
	const test = () => {
		var list = departmentTreeRef.value.getCheckedKeys()

	}

	const personalFlagChange = () => {

	}
	const defaultFlagChange = (value) => {
		if (value == '0') {
			menu.value = {}
			departmentTreeRef.value.setCheckedKeys([])
			buttonList.value = []
		} else if (value == '1') {

		}
	}

	const handleClear = () => {
		personalFlag.value = '2'
		defaultFlag.value = '2'
		role.value = {}
		menu.value = {}
		buttonList.value = []
		departmentTreeRef.value.setCheckedKeys([])
		treeRef.value.setCheckedKeys([])
	}




	const handleAdd = () => {
		dialogVisible.value = true
		sysRole.value = {
			id: '',
			roleCode: '',
			roleName: '',
		}

		var url = 'framework/SysRole/queryNewCode'
		var param = {}
		proxy.$axios.get(url, param).then(response => {
			sysRole.value.roleCode = response.data.data.code
			sysRole.value.roleName = response.data.data.code
		})
	}

	const handleEdit = (row) => {
		dialogVisible.value = true
		sysRole.value = row

	}

	const handleDelete = (id) => {

		ElMessageBox.confirm(
			'此操作将删除该数据, 是否继续?',
			'提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				draggable: true,
			}).then(() => {
			var url =
				'framework/SysRole/remove'
			var param = {
				id: id
			}
			proxy.$axios.post(url,
					param)
				.then(
					response => {
						if (response
							.data
							.code ==
							'0'
						) {
							ElMessage({
								type: 'success',
								message: '删除成功!',
							});
							getTableData()
						} else {
							ElMessage({
								type: 'error',
								message: '删除失败!' +
									response
									.data
									.msg
							});
						}

					});
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '已取消删除'
			});
		});
	}

	const handleCancelSaveRole = (row) => {
		dialogVisible.value = false
	}

	const handleSaveRole = (row) => {
		var url = 'framework/SysRole/save'
		var json = JSON.stringify(sysRole.value)
		var param = {
			json: json
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				ElMessage({
					type: 'success',
					message: '操作成功!',
				});
				getTableData()
				dialogVisible.value = false
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败!' + response.data.msg
				})
			}
		});
	}




	const application = ref({
		id: '',
		applicationName: ''
	})
	const options = ref([])
	const getApplications = () => {
		var url = 'framework/Application/queryByUserId'
		var param = {}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				options.value = response.data.data
				// console.log(JSON.stringify(options.value))
			} else {
				ElMessage.error('操作失败！' + response.data.msg)
			}
		});
	}


	const changeApplication = (value) => {
		application.value = value
		getDataTree()
	}

	const tableDataUserRole = ref([])
	const getUserRole = () => {
		var url = 'framework/SysUserRole/queryUsersByRoleId'
		var param = {
			roleId: role.value.id
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				tableDataUserRole.value = response.data.data
			} else {
				ElMessage.error('操作失败！' + response.data.msg)
			}
		});
	}


	const handleAddUserRole = () => {
		if (role.value.id == '') {
			ElMessage({
				type: 'error',
				message: '先选择部门！',
			})
			return
		}
		dialogVisibleUser.value = true

	}


	const dialogVisibleUser = ref(false)

	const queryUserDesc = ref('')
	const searchUser = () => {
		getTableDataUser()
	}
	const tableDataUser = ref([])
	const UsercurrentPage = ref(1)
	const UsertotalRows = ref(0)
	const UserpageSizes = ref([10, 20, 30, 40])
	const UserpageSize = ref(10)

	const UserhandleSizeChange = (val) => {
		UserpageSize.value = val
		getTableDataUser()
	}

	const UserhandleCurrentChange = (val) => {
		UsercurrentPage.value = val
		getTableDataUser()
	}

	const getTableDataUser = () => {
		var url = 'framework/SysUser/query'
		var param = {
			page: UsercurrentPage.value,
			rows: UserpageSize.value,
			userDesc: queryUserDesc.value
		}
		proxy.$axios.get(url, param).then(response => {
			tableDataUser.value = response.data.data.records
			UsertotalRows.value = response.data.data.total
		})
	}



	const handleAddUser = (row) => {
		var url = 'framework/SysUserRole/save'
		var param = {
			userId: row.id,
			roleId: role.value.id
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code === 0) {
				ElMessage({
					type: 'success',
					message: '添加成功!',
				});
				//getTableDataUser()
				getUserRole()
			} else {
				ElMessage({
					type: 'error',
					message: '修改失败' + response.data.msg,
				})
			}
		});
	}


	const handleDeleteUserRole = (row) => {
		ElMessageBox.confirm(
				'确定删除本条记录?',
				'提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
					draggable: true,
				}
			)
			.then(() => {


				var url = 'framework/SysUserRole/remove'
				var param = {
					userId: row.id,
					roleId: role.value.id
				}
				proxy.$axios.post(url, param).then(response => {
					if (response.data.code === 0) {
						ElMessage({
							type: 'success',
							message: '添加成功!',
						});
						getUserRole()
					} else {
						ElMessage({
							type: 'error',
							message: '修改失败' + response.data.msg,
						})
					}
				});

			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '已取消',
				})
			})
	}


	const tableDataRoleMenu = ref([])

	const getRoleMenu = () => {
		var url = 'framework/SysRoleMenu/queryMenuPermissionByRoleId'
		var param = {
			roleId: role.value.id
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code === 0) {
				tableDataRoleMenu.value = response.data.data
			} else {
				ElMessage({
					type: 'error',
					message: '修改失败' + response.data.msg,
				})
			}
		});
	}
	const handleDeleteRoleMenu = (row) => {

		ElMessageBox.confirm(
				'确定删除本条记录?',
				'提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
					draggable: true,
				}
			)
			.then(() => {

				var url = 'framework/SysRoleMenu/removeRoleMenuPermissionById'
				var param = {
					id: row.id
				}
				proxy.$axios.post(url, param).then(response => {
					if (response.data.code === 0) {
					 getRoleMenu()
					} else {
						ElMessage({
							type: 'error',
							message: '修改失败' + response.data.msg,
						})
					}
				});



			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '已取消',
				})
			})
	}
</script>

<style>
</style>