<template>
	<el-dialog
		:close-on-click-modal="false"
		:title="form.id ? (readonly ? '查看详情' : '编辑支付通道') : '新增支付通道'"
		draggable
		v-model="visible"
		width="920px"
	>
		<el-form :model="form" :rules="dataRules" label-width="140px" ref="dataFormRef" v-loading="loading">
			<!-- 基本信息 -->
			<el-divider content-position="left">基本信息</el-divider>
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item label="通道名称" prop="channelName">
						<el-input placeholder="请输入通道名称" v-model="form.channelName" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="通道编码" prop="channelCode">
						<el-input placeholder="请输入通道编码" v-model="form.channelCode" :disabled="readonly" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="基础费率(%)" prop="baseRechargeRate">
						<el-input-number
							placeholder="请输入基础费率"
							v-model="form.baseRechargeRate"
							: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="启用状态" prop="status">
						<el-radio-group v-model="form.status" :disabled="readonly || !!form.id">
							<el-radio :label="true">启用</el-radio>
							<el-radio :label="false">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="风控状态" prop="riskControlStatus">
						<el-radio-group v-model="form.riskControlStatus" :disabled="readonly">
							<el-radio :label="true">启用</el-radio>
							<el-radio :label="false">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="权重值" prop="roundVal">
						<el-input-number
							placeholder="请输入权重值"
							v-model="form.roundVal"
							:min="0"
							:max="100"
							:precision="0"
							:disabled="readonly"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col>
			</el-row>

			<!-- 金额配置 -->
			<el-divider content-position="left">金额配置</el-divider>
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item label="当天总金额" prop="todayTotalAmount">
						<el-input-number
							placeholder="请输入当天总金额"
							v-model="form.todayTotalAmount"
							:min="0"
							:max="9999999999.99"
							:precision="2"
							:disabled="readonly"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="单笔最小金额" prop="singleMinAmount">
						<el-input-number
							placeholder="请输入单笔最小金额"
							v-model="form.singleMinAmount"
							:min="0"
							:max="9999999999.99"
							:precision="2"
							:disabled="readonly"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="单笔最大金额" prop="singleMaxAmount">
						<el-input-number
							placeholder="请输入单笔最大金额"
							v-model="form.singleMaxAmount"
							:min="0"
							:max="9999999999.99"
							:precision="2"
							:disabled="readonly"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ readonly ? '关闭' : '取消' }}</el-button>
				<el-button @click="onSubmit" type="primary" :disabled="loading" v-if="!readonly">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" name="PaymentChannelDialog" setup>
// 定义子组件向父组件传值/事件
import { useMessage } from '/@/hooks/message';
import { addChannel, getChannel, putChannel } from '/@/api/payment';
import { rule } from '/@/utils/validate';

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

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

// 提交表单数据（严格按照接口文档字段）
const form = reactive({
	id: '',
	channelName: '',
	channelCode: '',
	baseRechargeRate: 0,
	todayTotalAmount: 0,
	singleMinAmount: 0,
	singleMaxAmount: 0,
	status: true,
	riskControlStatus: false,
	roundType: 'WEIGHT',
	roundVal: 1,
});

// 定义校验规则（根据接口文档，必填字段：channelName, channelCode）
const dataRules = ref({
	channelName: [
		{ required: true, message: '请输入通道名称', trigger: 'blur' },
		{ validator: rule.overLength, trigger: 'blur' },
	],
	channelCode: [
		{ required: true, message: '请输入通道编码', trigger: 'blur' },
		{ validator: rule.overLength, trigger: 'blur' },
	],
	baseRechargeRate: [{ required: false, message: '请输入基础费率', trigger: 'blur' }],
	singleMinAmount: [
		{
			validator: (rule: any, value: any, callback: any) => {
				if (value && form.singleMaxAmount && value > form.singleMaxAmount) {
					callback(new Error('单笔最小金额不能大于单笔最大金额'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
	singleMaxAmount: [
		{
			validator: (rule: any, value: any, callback: any) => {
				if (value && form.singleMinAmount && value < form.singleMinAmount) {
					callback(new Error('单笔最大金额不能小于单笔最小金额'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
	roundVal: [
		{ required: true, message: '请输入权重值', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				if (value !== undefined && value !== null && (value < 0 || value > 100)) {
					callback(new Error('权重值范围为0-100'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
});

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

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

	// 获取支付通道信息
	if (id) {
		form.id = id;
		getPaymentChannelData(id);
	}
};

// 获取支付通道数据
const getPaymentChannelData = (id: string) => {
	loading.value = true;
	getChannel(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.id) {
			await putChannel(form.id, form);
			useMessage().success('编辑成功');
		} else {
			await addChannel(form);
			useMessage().success('新增成功');
		}
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

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