<template>
	<div>
		<div class="head">
			<el-row>
				<el-form-item>
					<el-input v-model="searchInfo.cname" placeholder="请输入用户名" style="margin-left: 10px;" />
				</el-form-item>
				<el-form-item>
					<el-select :filterable="true" clearable v-model="searchInfo.status" placeholder="所有状态"
						style="margin-left: 10px;">
						<el-option label="正常" :value="1" />
						<el-option label="禁用" :value="0" />
					</el-select>
				</el-form-item>

				<el-button @click="GetUserList()" style="margin-left: 10px;">查询</el-button>
				<el-button type="primary" @click="add()" style="margin-left: 10px;">新建用户</el-button>
			</el-row>
		</div>

		<el-table :data="tableData" style="width: 100%;" row-key="id">
			<el-table-column prop="id" label="Id" width="100" />
			<el-table-column prop="cname" label="名称" />
			<el-table-column prop="uname" label="用户名" />
			<el-table-column prop="group_name" label="分组" />
			<el-table-column prop="department_name" label="科室" />
			<el-table-column prop="ward" label="病区" />
			<el-table-column prop="status" label="状态">
				<template #default="scope">
					<el-tag v-if="scope.row.status==1" class="ml-2" type="success">正常</el-tag>
					<el-tag v-if="scope.row.status==0" class="ml-2" type="danger">关闭</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="created_at" label="创建时间" />
			<el-table-column label="操作" width="100">
				<template #default="scope">
					<el-button type="primary" @click="add(scope.row.id)" :icon="Edit" circle />
				</template>
			</el-table-column>
		</el-table>

		<div class="page">
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
				:page-sizes="[15, 50, 100, 200]" layout="total,sizes, prev, pager, next" :total="total"
				@size-change="PageSizeChange" @current-change="PageCurrentChange" />
		</div>

		<el-dialog v-model="dialogVisible" title="用户" width="35%">
			<el-form :model="UserInfo" label-width="100px" v-loading="loading">

				<el-form-item label="角色">
					<el-select v-model="UserInfo.groupId" placeholder="请选择角色">
						<el-option v-for="(item,index) in groupList" :key="index" :label="item.group_name"
							:value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="特殊权限">
					<el-checkbox-group v-model="UserInfo.special_privileges">
					<el-checkbox 
					      v-for="(item, index) in special_privileges_list" 
					      :key="index" 
					      :label="item.key"
					    >
					      {{ item.name }}
					    </el-checkbox>
						 </el-checkbox-group>
				</el-form-item>
				
				<el-form-item label="名称">
					<el-input v-model="UserInfo.cname" />
				</el-form-item>
				<el-form-item label="账号">
					<el-input v-model="UserInfo.uname" :disabled="usernameDisabled" />
				</el-form-item>
				<el-form-item label="状态">
					<el-switch v-model="UserInfo.status" size="large" active-text="正常" inactive-text="关闭"
						:active-value="1" :inactive-value="0" />
				</el-form-item>
				<el-form-item>
					<el-button @click="resetPwdClick()">重置密码</el-button>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="Save">
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="resetPwdDialogShow" title="重置密码" width="30%">
			<el-form :model="UserInfo" label-width="100px" v-loading="loading">
				<el-form-item label="重置密码">
					<div style="display: flex;">
						<el-input v-model="Password" />
						<el-button :icon="Refresh" @click="random()"></el-button>
					</div>

				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="resetPwdDialogShow = false">取消</el-button>
					<el-button type="primary" @click="resetPwdSave()">
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		watch,
	} from 'vue'
	import {
		ElMessage
	} from 'element-plus'
	import {
		getGroupList,
		getAdminUserList,
		SaveSystemUserInfo,
		GetSystemUserDetail,
		resetPwd
	} from '@/api/api.js'
	import {
		Edit,
		Refresh
	} from '@element-plus/icons-vue'

	import {
		useRoute,
		useRouter
	} from "vue-router"
	const route = useRoute()
	const router = useRouter()

	let loading = ref(false)
	let saveType = ref('save')
	let tableData = ref([])
	let currentPage = ref(1) //当前页码
	let pageSize = ref(15) //每页数量
	let total = 0 //总数量
	let dialogVisible = ref(false)
	let groupList = ref([])
	let UserInfo = ref({
		groupId: '',
		cname: '',
		uname: '',
		id: 0,
		status: 1,
		special_privileges:[]
	})
	let special_privileges_list=ref([]);

	let searchInfo = ref({
		status: null,
		cname: '',
		departmentid: null
	})




	let usernameDisabled = ref(false);
	const GetUserList = () => {
		getAdminUserList({
			...searchInfo.value,
			page: currentPage.value,
			pageSize: pageSize.value
		}).then(res => {
			tableData.value = res.list
			total = res.count
		})
	}
	const PageSizeChange = (e) => { // 修改每页数量
		pageSize.value = e
		GetUserList()
	}
	const PageCurrentChange = (e) => { //切换页码
		currentPage.value = e
		GetUserList()
	}
	const Save = () => { //保存用户信息
		SaveSystemUserInfo({
			userInfo: UserInfo.value
		}).then(res => {
			if (res.status == 'ok') {
				dialogVisible.value = false
				ElMessage({
					message: '保存成功',
					type: 'success',
				})
				GetUserList()
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	const GetGroupList = () => { //获取分组列表
		getGroupList({
			type: 'enable'
		}).then(res => {
			groupList.value = res.list
			special_privileges_list.value=res.special_privileges_list
		})
	}
	const add = (id1 = '') => {
		usernameDisabled.value = false
		dialogVisible.value = true
		UserInfo.value = {
			groupId: '',
			cname: '',
			uname: '',
			id: id1,
			status: 1,
			special_privileges: []
		}
		GetGroupList()
		if (id1 > 0) {
			usernameDisabled.value = true
			GetSystemUserDetail({
				id: id1
			}).then(res => {
				UserInfo.value.groupId = res.info[0].group
				UserInfo.value.cname = res.info[0].cn_name
				UserInfo.value.uname = res.info[0].username
				UserInfo.value.id = res.info[0].id
				UserInfo.value.status = res.info[0].status
				UserInfo.value.special_privileges=res.info[0].special_privileges

			})
		}

	}
	watch(
		() => route.query.departmentId,
		(newDepartmentId, oldDepartmentId) => {
			// 当departmentId变化时，这个函数会被调用
			console.log(`Department ID changed from ${oldDepartmentId} to ${newDepartmentId}`);
			if (route.query.departmentId) {
				searchInfo.value.departmentid = Number(route.query.departmentId)
			} else {
				searchInfo.value.departmentid = null
			}
			GetUserList() // 假设这是获取数据的函数，根据新的departmentId获取数据
		}, {
			immediate: true
		} // immediate: true 确保在初始渲染时也会触发回调
	);
	watch(
		() => route.query.ward,
		(newward, oldward) => { 
			if (route.query.ward) {
				searchInfo.value.ward = route.query.ward
			} else {
				searchInfo.value.ward = null
			}
			GetUserList() // 假设这是获取数据的函数，根据新的departmentId获取数据
		}, {
			immediate: true
		} // immediate: true 确保在初始渲染时也会触发回调
	);
	let resetPwdDialogShow = ref(false);
	let Password = ref('');
	const resetPwdClick = () => {
		resetPwdDialogShow.value = true
	}
	const random = () => {
		let password = '';
		for (let i = 0; i < 6; i++) {
			password += Math.floor(Math.random() * 10); // 生成0到9之间的随机数
		}
		Password.value = password
	}
	const resetPwdSave = () => {
		resetPwd({
			userid: UserInfo.value.id,
			password:Password.value,
		}).then(res => {
			if(res.status){
				ElMessage({
					message: '修改成功',
					type: 'success',
				})
				resetPwdDialogShow.value=false
				Password.value=''
			}else{
				ElMessage.error(res.msg)
			}
		})
	}
	onMounted(() => {

	})
</script>

<style scoped>
	.page {
		display: flex;
		justify-content: flex-end;
		margin-top: 10px;
	}
</style>