<template>
	<div class="table-page">
		<div class="search-part" v-show="isSearch">
			<div class="search-cell">
				<span class="label">用户名</span>
				<el-input v-model="queryParams.userName" placeholder="请输入用户名"></el-input>
			</div>
			<el-button type="primary" icon="Search" @click="searchData()">查询</el-button>
			<el-button icon="Refresh" @click="resetSearch()">重置</el-button>
		</div>
		<div class="button-part" style="justify-content: space-between;">
			<div>
				<el-button type="primary" icon="FirstAidKit" @click="addData">新增</el-button>
				<el-button icon="FirstAidKit" @click="importData">导入</el-button>
				<el-button icon="Delete" @click="removeData()">删除</el-button>
			</div>
			<TableAbility @searchBtn="isSearch = !isSearch" @refreshBtn="updateData()"
										@downloadBtn="exportData('医生数据', tableData)"></TableAbility>
		</div>
		<div class="table-part">
			<el-table ref="tableRef" v-loading="loading" :data="tableData" height="100%" border show-overflow-tooltip
								:row-class-name="({ row }: any) => row.lockFlag == 1 && 'disable'" @row-click="tableRowClick">
				<el-table-column type="selection" width="55"/>
				<el-table-column type="index" label="#" width="55" align="center"/>
				<el-table-column property="name" label="姓名" width="120" align="center"/>
				<el-table-column label="手机号" width="220" align="center">
					<template #default="scope">
                        <div v-if="scope.row.phone">
                            {{
                                scope.row.phone.slice(0, 3) + '****' + scope.row.phone.slice(7)
                            }}
                        </div>
					</template>
				</el-table-column>
				<el-table-column label="角色" width="220" align="center">
					<template #default="scope">
						<span v-for="(item, index) in scope.row.roleList" :key="index">
						{{ item.roleName }} {{ (scope.row.roleList.length - 1) == index ? '' : '，' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column label="锁定" width="120" align="center">
					<template #default="scope">
						<span><el-switch v-model="scope.row.lockFlag" @click="enableChange(scope.row)"/></span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center">
					<template #default="scope">
                        <span @click.stop>
                            <el-button link icon="RefreshLeft" @click="resetPassword(scope.row)"
																			 :disabled="scope.row.lockFlag == 1">密码</el-button>
                            <el-button link icon="EditPen" @click="editData(scope.row)"
																			 :disabled="scope.row.lockFlag == 1">修改</el-button>
													<el-button link icon="Delete" @click="removeData([scope.row])"
																		 :disabled="scope.row.lockFlag == 1">删除</el-button>
                        </span>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="pagination-part">
			<CommonPagination :total="total" @paginationChange="paginationChange"/>
		</div>
	</div>
	<el-dialog v-model="isFormDialog" :title="formDialogTitle" width="750px">
		<DoctorForm ref="doctorFormRef" :type="formDialogTitle === '添加' ? 'add' : 'edit'" @close="isFormDialog = false"
								@save="doctorFormSave"/>
	</el-dialog>
	<ImportDialog ref="importDialogRef" title="用户导入"
								templateUrl="/admin/sys-file/local/file/user.xlsx"
		importUrl="/admin/user/import"/>
</template>

<script lang='ts' setup>
import {ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {exportData, tableRemoveRow} from '@/utils/table-util'
import CommonPagination from '@/components/common-pagination.vue'
import DoctorForm from './form/doctor-form.vue'
import ImportDialog from '@/components/import-dialog.vue'
import {deleteU, modifyPw, updateUserInfo, userPage} from "@/api/user";

const tableRef = ref()
const doctorFormRef = ref()
const importDialogRef = ref()
const isSearch = ref(true)
const loading = ref(true)
const isFormDialog = ref(false)
const formDialogTitle = ref('')
const queryParams = ref({
	userName: ''
} as any)
const tableData = ref([] as any)
let current = 0
let size = 10
const total = ref(0)

queryData()

function searchData() {
	updateData()
}

function resetSearch() {
	queryParams.value.userName = ""
	updateData()
}

function queryData() {
	loading.value = true
	userPage({
		current,
		size,
		name: queryParams.value.userName
	}).then((res: any) => {
		loading.value = false
		total.value = res.data.total
		tableData.value = res.data.records
	}).catch(error => {
		loading.value = false
	})
}

function updateData() {
	current = 0
	total.value = 0
	tableData.value = []
	queryData()
}

const addData = () => {
	isFormDialog.value = true
	formDialogTitle.value = '添加'
	setTimeout(() => {
		doctorFormRef.value.resetData()
	}, 0)
}
const importData = () => {
	setTimeout(() => {
		importDialogRef.value.open()
	}, 0);
}
const removeData = (e?: any) => {
	const selectRow = e || tableRef.value.getSelectionRows()

	tableRemoveRow({data: selectRow}, (res: boolean) => {
		if (res) {
			const index = tableData.value.findIndex((item: any) => item === selectRow)
			tableData.value.splice(index, 1)
			const ids: any = [];
			selectRow.forEach((row: any) => {
				ids.push(row.userId)
			})
			deleteU(ids).then(res => {
				ElMessage.success("删除成功")
			}).catch(() => {
				ElMessage.error("删除失败")
			})
		}
	})
}
const enableChange = (e: any) => {
	updateUserInfo({
		username: e.username,
		lockFlag: e.lockFlag ? '1' : '0'
	}).then((res: any) => {
		if (res.code == 0) {
			ElMessage.success(e.lockFlag ? '锁定成功' : '解锁成功')
		}
	})
}
const resetPassword = (e: any) => {
	ElMessageBox.prompt('是否确定要重置密码？', '系统提醒', {
		type: 'warning',
		draggable: true,
		// inputPattern: /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{9,15}$/,
		inputErrorMessage: "密码至少包含字母、数字、特殊字符，不少于9位，最多15位"
	}).then((inputVal) => {
		modifyPw({
			username: e.username,
			password: inputVal.value
		}).then((res: any) => {
			if (res.code == 0) {
				ElMessage.success('重置成功！')
			} else {
				ElMessage.error(res.msg)
			}
		})
	})
}
const editData = (e: any) => {
	isFormDialog.value = true
	formDialogTitle.value = '修改'
	setTimeout(() => {
		doctorFormRef.value.resetData()
		const val = JSON.parse(JSON.stringify(e));
		val.role = []
		val.roleList.forEach((role: any) => {
			val.role.push(role.roleId)
		})
		doctorFormRef.value.formData = val
	}, 0)
}
const tableRowClick = (row: any) => {
	tableRef.value.toggleRowSelection(row)
}
const doctorFormSave = (data: any, type: string) => {
	updateData()
}
const paginationChange = (page: number, s: number) => {
	current = page
	size = s
	queryData()
}
</script>

<style lang='scss' scoped></style>
