<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('merchantUser.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('merchantUser.basicInfo') }}</el-divider>
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('merchantUser.merchantName')" prop="merchantName">
						<el-input :placeholder="$t('merchantUser.inputMerchantNameTip')" v-model="form.merchantName" :disabled="readonly || !!form.userId" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('merchantUser.username')" prop="username">
						<el-input :placeholder="$t('merchantUser.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('merchantUser.realname')" prop="realname">
						<el-input :placeholder="$t('merchantUser.inputRealnameTip')" v-model="form.realname" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('merchantUser.phone')" prop="phone">
						<el-input :placeholder="$t('merchantUser.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('merchantUser.email')" prop="email">
						<el-input :placeholder="$t('merchantUser.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('merchantUser.idcard')" prop="idcard">
						<el-input :placeholder="$t('merchantUser.inputIdcardTip')" v-model="form.idcard" :disabled="readonly" />
					</el-form-item>
				</el-col>

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

				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('merchantUser.agentId')" prop="agentId">
						<el-select v-model="form.agentId" :placeholder="$t('merchantUser.selectAgentTip')" :disabled="readonly" style="width: 100%">
							<el-option v-for="item in agentList" :key="item.userId" :label="item.agentName" :value="item.userId" />
						</el-select>
					</el-form-item>
				</el-col>

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

			<!-- 网站信息 -->
			<el-divider content-position="left">{{ $t('merchantUser.websiteInfo') }}</el-divider>
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item :label="$t('merchantUser.websiteName')" prop="websiteName">
						<el-input :placeholder="$t('merchantUser.inputWebsiteNameTip')" v-model="form.websiteName" :disabled="readonly" />
					</el-form-item>
				</el-col>

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

				<el-col :span="12" class="mb20" v-if="form.userId">
					<el-form-item :label="$t('merchantUser.appId')" prop="appId">
						<el-input :placeholder="'AppId'" v-model="form.appId" disabled />
					</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="MerchantUserDialog" setup>
// 定义子组件向父组件传值/事件
import { useMessage } from '/@/hooks/message';
import { addObj, getObj, putObj, getAgentList } from '/@/api/merchant/merchantUser';
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 agentList = ref<any[]>([]);

// 提交表单数据（严格按照接口文档字段）
const form = reactive({
	userId: '',
	username: '',
	merchantName: '',
	phone: '',
	email: '',
	websiteName: '',
	websiteAddress: '',
	appId: '',
	idcard: '',
	realname: '',
	contactAddress: '',
	offlineRechargeRate: 0,
	status: true,
	agentId: undefined as number | undefined,
});

// 定义校验规则（根据接口文档，必填字段：username, merchantName, phone, email）
const dataRules = ref({
	username: [
		{ required: true, message: t('merchantUser.usernameRequired'), trigger: 'blur' },
		{ validator: rule.overLength, trigger: 'blur' },
	],
	merchantName: [
		{ required: true, message: t('merchantUser.merchantNameRequired'), trigger: 'blur' },
		{ validator: rule.overLength, trigger: 'blur' },
	],
	phone: [
		{ required: true, message: t('merchantUser.phoneRequired'), trigger: 'blur' },
		{ validator: rule.validatePhone, trigger: 'blur' },
	],
	email: [
		{ required: true, message: t('merchantUser.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();
	});

	// 加载代理商列表
	loadAgentList();

	// 获取商户用户信息
	if (id) {
		form.userId = id;
		getMerchantUserData(id);
	}
};

// 加载代理商列表
const loadAgentList = async () => {
	try {
		const res = await getAgentList('0');
		agentList.value = res.data || [];
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

// 获取商户用户数据
const getMerchantUserData = (id: string) => {
	loading.value = true;
	getObj(id)
		.then((res: any) => {
			Object.assign(form, res.data);
		})
		.finally(() => {
			loading.value = false;
		});
};

// 提交
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;
	}
};

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