<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" />

		<!-- AppId 显示区域 -->
		<el-card v-if="form.userId && form.appId" shadow="never" style="margin-bottom: 20px; background: #f5f7fa">
			<div style="display: flex; align-items: center; justify-content: space-between">
				<div style="flex: 1">
					<div style="color: #909399; font-size: 13px; margin-bottom: 5px">{{ $t('merchantUser.appId') }}</div>
					<div style="color: #303133; font-size: 16px; font-weight: 600; font-family: 'Courier New', monospace">{{ form.appId }}</div>
				</div>
				<el-button @click="handleCopyAppId" icon="DocumentCopy" type="primary">{{ $t('merchantUser.copyBtn') }}</el-button>
			</div>
		</el-card>

		<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%" clearable>
							<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-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>

	<!-- 密钥显示 -->
	<key-dialog ref="keyDialogRef" />
</template>

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

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

// 引入密钥弹窗组件
const KeyDialog = defineAsyncComponent(() => import('./keyDialog.vue'));

const { t } = useI18n();
const { copy } = useClipboard();
// 定义变量内容
const dataFormRef = ref();
const keyDialogRef = 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;
		});
};

// 复制 AppId
const handleCopyAppId = async () => {
	try {
		await copy(form.appId);
		useMessage().success(t('merchantUser.copySuccess'));
	} catch (err) {
		useMessage().error(t('merchantUser.copyFailed'));
	}
};

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

	try {
		loading.value = true;
		let res: any;
		if (form.userId) {
			res = await putObj(form.userId, form);
			useMessage().success(t('common.editSuccessText'));
			visible.value = false;
			emit('refresh');
		} else {
			res = await addObj(form);
			useMessage().success(t('common.addSuccessText'));
			visible.value = false;
			emit('refresh');
			// 新增成功后显示密钥信息
			if (res.data && res.data.appId && res.data.md5Key) {
				keyDialogRef.value.openDialog(res.data);
			}
		}
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

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