<template>
	<el-dialog
		:close-on-click-modal="false"
		:title="form.userId ? (readonly ? '查看详情' : $t('common.editBtn')) : $t('common.addBtn')"
		draggable
		v-model="visible"
		width="920px"
	>
		<el-alert v-if="!form.userId" :title="$t('agentUser.defaultPasswordTip')" type="warning" :closable="false" style="margin-bottom: 15px" />
		<el-form :model="form" :rules="dataRules" label-width="140px" ref="dataFormRef" v-loading="loading">
			<!-- 基本信息 -->
			<el-divider content-position="left">{{ $t('agentUser.basicInfo') }}</el-divider>
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.agentName')" prop="agentName">
						<el-input :placeholder="$t('agentUser.inputAgentNameTip')" v-model="form.agentName" :disabled="readonly || !!form.userId" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.username')" prop="username">
						<el-input :placeholder="$t('agentUser.inputUsernameTip')" v-model="form.username" :disabled="readonly || !!form.userId" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.realname')" prop="realname">
						<el-input :placeholder="$t('agentUser.inputRealnameTip')" v-model="form.realname" :disabled="readonly || !!form.userId" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.phone')" prop="phone">
						<el-input :placeholder="$t('agentUser.inputPhoneTip')" v-model="form.phone" :disabled="readonly || !!form.userId" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.email')" prop="email">
						<el-input :placeholder="$t('agentUser.inputEmailTip')" v-model="form.email" :disabled="readonly || !!form.userId" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.idcard')" prop="idcard">
						<el-input :placeholder="$t('agentUser.inputIdcardTip')" v-model="form.idcard" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.address')" prop="address">
						<el-input :placeholder="$t('agentUser.inputAddressTip')" v-model="form.address" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<!-- <el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.offlineRechargeRate')" prop="offlineRechargeRate">
						<el-input-number
							:placeholder="$t('agentUser.inputOfflineRechargeRateTip')"
							v-model="form.offlineRechargeRate"
							:min="0"
							:max="100"
							:precision="2"
							:disabled="readonly"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col> -->

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.status')" prop="status">
						<el-radio-group v-model="form.status" :disabled="readonly || !!form.userId">
							<el-radio :label="true">{{ $t('agentUser.statusEnable') }}</el-radio>
							<el-radio :label="false">{{ $t('agentUser.statusDisable') }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>

			<!-- 银行信息 -->
			<el-divider content-position="left">{{ $t('agentUser.bankInfo') }}</el-divider>
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.bankName')" prop="bankName">
						<el-input :placeholder="$t('agentUser.inputBankNameTip')" v-model="form.bankName" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.bankBranch')" prop="bankBranch">
						<el-input :placeholder="$t('agentUser.inputBankBranchTip')" v-model="form.bankBranch" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.bankProvince')" prop="bankProvince">
						<el-input :placeholder="$t('agentUser.inputBankProvinceTip')" v-model="form.bankProvince" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.bankCity')" prop="bankCity">
						<el-input :placeholder="$t('agentUser.inputBankCityTip')" v-model="form.bankCity" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.accountName')" prop="accountName">
						<el-input :placeholder="$t('agentUser.inputAccountNameTip')" v-model="form.accountName" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('agentUser.accountNum')" prop="accountNum">
						<el-input :placeholder="$t('agentUser.inputAccountNumTip')" v-model="form.accountNum" :disabled="readonly" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ readonly ? $t('common.closeBtn') : $t('common.cancelButtonText') }}</el-button>
				<el-button @click="onSubmit" type="primary" :disabled="loading" v-if="!readonly">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" name="AgentUserDialog" setup>
// 定义子组件向父组件传值/事件
import { useMessage } from '/@/hooks/message';
import { addObj, getObj, putObj } from '/@/api/agent';
import { useI18n } from 'vue-i18n';
import { rule } from '/@/utils/validate';

const emit = defineEmits(['refresh']);

const { t } = useI18n();
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const readonly = ref(false);

// 提交表单数据（严格按照接口文档字段）
const form = reactive({
	userId: '',
	username: '',
	agentName: '',
	realname: '',
	phone: '',
	idcard: '',
	address: '',
	email: '',
	offlineRechargeRate: 0,
	status: true,
	bankName: '',
	bankBranch: '',
	accountName: '',
	accountNum: '',
	bankProvince: '',
	bankCity: '',
});

// 定义校验规则（根据接口文档，必填字段：username, agentName, realname, phone, email）
const dataRules = ref({
	username: [
		{ required: true, message: t('agentUser.usernameRequired'), trigger: 'blur' },
		{ validator: rule.overLength, trigger: 'blur' },
	],
	agentName: [
		{ required: true, message: t('agentUser.agentNameRequired'), trigger: 'blur' },
		{ validator: rule.overLength, trigger: 'blur' },
	],
	realname: [
		{ required: true, message: t('agentUser.realnameRequired'), trigger: 'blur' },
		{ validator: rule.overLength, trigger: 'blur' },
	],
	phone: [
		{ required: true, message: t('agentUser.phoneRequired'), trigger: 'blur' },
		{ validator: rule.validatePhone, trigger: 'blur' },
	],
	email: [
		{ required: true, message: t('agentUser.emailRequired'), trigger: 'blur' },
		{ validator: rule.email, trigger: 'blur' },
	],
});

// 打开弹窗
const openDialog = (id: string, isReadonly = false) => {
	visible.value = true;
	readonly.value = isReadonly;
	form.userId = '';

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});

	// 获取代理用户信息
	if (id) {
		form.userId = id;
		getAgentUserData(id);
	}
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		if (form.userId) {
			await putObj(form.userId, form);
		} else {
			await addObj(form);
		}
		useMessage().success(t(form.userId ? 'common.editSuccessText' : 'common.addSuccessText'));
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

/**
 * 根据 ID 获取代理用户数据并初始化表单。
 * @param {string} id - 要查询的代理用户 ID。
 * @returns {Promise<void>} - 初始化表单的 Promise 实例。
 */
const getAgentUserData = async (id: string): Promise<void> => {
	loading.value = true; // 显示加载状态

	try {
		const res = await getObj(id); // 执行查询操作
		Object.assign(form, res.data); // 将查询到的数据合并到表单中
	} catch (err) {
		useMessage().error('操作失败'); // 如果查询失败，则显示错误提示信息
	} finally {
		loading.value = false; // 结束加载状态
	}
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
