<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="psDialogVisible" title="密码重置" width="500" draggable>
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="60">
            <el-form-item label="密码" prop="password" label-width="100">
                <el-input v-model="formData.password" type="password" show-password
                          placeholder="8~16位字母或数字（区分大小写）"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword" label-width="100">
                <el-input v-model="formData.confirmPassword" type="password" show-password
                          placeholder="确认密码"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="psDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="sbPs">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
	<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 {reactive, 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";
import {REGEXP} from "@/enum/log-enum";

const tableRef = ref()
const doctorFormRef = ref()
const importDialogRef = ref()
const isSearch = ref(true)
const loading = ref(true)
const isFormDialog = ref(false)
const psDialogVisible = 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)
const formRef = ref()
const formData = ref()

const validatePassword = (rule: any, value: any, callback: any) => {
    if (!(new RegExp(REGEXP.PASSWORD).test(value))) {
        callback("8~16位字母或数字（区分大小写）")
    } else {
        callback()
    }
}

const validateConsistent = (rule: any, value: any, callback: any) => {
    if (formData.value.password != formData.value.confirmPassword) {
        callback('两次密码不一致')
    } else {
        callback()
    }
}

const rules = ref({
    password: [
        {required: true, message: '请输入密码', trigger: ['blur', 'change']},
        {validator: validatePassword, trigger: ['blur', 'change']},
    ],
    confirmPassword: [
        {required: true, message: '请输入密码', trigger: ['blur', 'change']},
        {validator: validatePassword, trigger: ['blur', 'change']},
        {validator: validateConsistent, trigger: ['blur', 'change']}
    ]
})

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) => {
    formData.value = {
        password: '',
        confirmPassword: '',
        username: e.username
    }
    psDialogVisible.value = true
    formRef.value.resetFields()
}

const sbPs = () => {
    formRef.value.validate((valid: any, fields: any) => {
        if (valid) {
            modifyPw({
                username: formData.value.username,
                password: formData.value.password
            }).then((res: any) => {
                if (res.code == 0) {
                    ElMessage.success('重置成功！')
                    psDialogVisible.value = false
                } 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>
