<template>
	<el-dialog title="设置管理员" height="400px" v-model="visible" width="500px" append-to-body draggable>
		<div class="form-container">
			<!-- 主表 -->
			<el-form
				ref="formRef"
				class="master-container"
				v-loading="loading"
				:model="form"
				:rules="rules"
				label-width="64px"
			>
				<el-form-item label="公司名" prop="supplierName">
					<el-input v-model.trim="form.supplierName" readonly placeholder="公司名" />
				</el-form-item>
				<el-form-item label="用户名" prop="username">
					<el-input v-model.trim="form.username" placeholder="用户名" />
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model.trim="form.remark" placeholder="备注" />
				</el-form-item>
				<div style="font-size: 14px; color: #a00; font-weight: 700; height: 48px; text-align: center">
					外协商报工系统，初始密码为：123456
				</div>
			</el-form>
		</div>
		<template #footer>
			<el-button type="primary" icon="Check" @click="handleSave">确 定</el-button>
			<el-button type="warning" icon="Key" :disabled="!form.id" @click="handleInitPsw">初始化密码</el-button>
			<el-button type="danger" icon="Close" @click="handleCancel">取 消</el-button>
		</template>
	</el-dialog>
</template>
<script setup>
import { getAdminInfo, saveAdmin, initAdminPsw } from '@/api/business/supplier'
const { proxy } = getCurrentInstance()

/** 产品表单变量 */
const loading = ref(false)
const visible = ref(false)
const data = reactive({
	form: {},
	rules: {
		username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }]
	}
})
const { form, rules } = toRefs(data)

/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(data) {
	reset()
	visible.value = true
	loading.value = true
	form.value.supplierId = data.id
	form.value.supplierName = data.name
	getAdminInfo(form.value.supplierId).then((res) => {
		console.log(res.data)
		if (res.data) {
			form.value = res.data
		}
		loading.value = false
	})
}

/** 取消按钮 */
function handleCancel() {
	visible.value = false
	reset()
}

/** 表单重置 */
function reset() {
	form.value = {
		id: null,
		supplierId: '0',
		supplierName: '',
		username: '',
		isAdmin: '1',
		remark: ''
	}
	proxy.resetForm('formRef')
}

/** 提交按钮 */
function handleSave() {
	proxy.$refs['formRef'].validate((valid) => {
		if (valid) {
			saveAdmin(form.value).then((res) => {
				if (res.code === 200) {
					proxy.$modal.msgSuccess('操作成功')
				} else {
					proxy.$modal.msgWarn(res.msg)
				}
				visible.value = false
			})
		}
	})
}

/** 初始化密码 */
function handleInitPsw() {
	proxy.$refs['formRef'].validate((valid) => {
		if (valid) {
			initAdminPsw(form.value).then((res) => {
				if (res.code === 200) {
					proxy.$modal.msgSuccess('操作成功')
				} else {
					proxy.$modal.msgWarn(res.msg)
				}
				visible.value = false
			})
		}
	})
}

/** 暴露给父组件的方法 */
defineExpose({
	open
})
</script>
