<template>
	<el-dialog :close-on-click-modal="false" title="配置代理商支付通道" draggable v-model="visible" width="700px">
		<el-form :model="formData" :rules="formRules" label-width="140px" ref="formRef" v-loading="formLoading">
			<!-- 基本信息（只读） -->
			<el-divider content-position="left">基本信息</el-divider>
			<el-row :gutter="24">
				<el-col :span="24" class="mb20">
					<el-form-item label="通道名称">
						<el-input v-model="formData.channelName" disabled />
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="支付类型名称">
						<el-input v-model="formData.paymentName" disabled />
					</el-form-item>
				</el-col>
			</el-row>

			<!-- 配置信息 -->
			<el-divider content-position="left">配置信息</el-divider>
			<el-row :gutter="24">
				<el-col :span="24" class="mb20">
					<el-form-item label="启用状态" prop="status">
						<el-radio-group v-model="formData.status">
							<el-radio :label="true">启用</el-radio>
							<el-radio :label="false">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>

				<!-- 代收：只显示费率，固定百分比类型 -->
				<el-col :span="24" class="mb20" v-if="formData.paymentType === 'HARVEST'">
					<el-form-item label="费率(%)" prop="feeRate">
						<el-input-number placeholder="请输入费率" v-model="formData.feeRate" :min="0" :max="100" :precision="2" style="width: 100%" />
					</el-form-item>
				</el-col>

				<!-- 代付：显示手续费类型选择 -->
				<template v-if="formData.paymentType === 'PAY'">
					<el-col :span="24" class="mb20">
						<el-form-item label="手续费类型" prop="feeType">
							<el-radio-group v-model="formData.feeType">
								<el-radio label="PERCENTAGE">百分比</el-radio>
								<el-radio label="FIXED">固定</el-radio>
								<el-radio label="MIXED">百分比+固定</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<!-- 代付：百分比、百分比+固定 显示手续费比例 -->
					<el-col :span="24" class="mb20" v-if="formData.feeType === 'PERCENTAGE' || formData.feeType === 'MIXED'">
						<el-form-item label="手续费比例(%)" prop="feeRate">
							<el-input-number placeholder="请输入手续费比例" v-model="formData.feeRate" :min="0" :max="100" :precision="2" style="width: 100%" />
						</el-form-item>
					</el-col>

					<!-- 代付：固定、百分比+固定 显示手续费固定金额 -->
					<el-col :span="24" class="mb20" v-if="formData.feeType === 'FIXED' || formData.feeType === 'MIXED'">
						<el-form-item label="手续费固定金额" prop="feeEvery">
							<el-input-number placeholder="请输入手续费固定金额" v-model="formData.feeEvery" :min="0" :precision="2" style="width: 100%" />
						</el-form-item>
					</el-col>
				</template>
			</el-row>
		</el-form>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button @click="handleSubmit" type="primary" :disabled="formLoading">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" name="AgentPaymentConfigDialog" setup>
import { editAgentPaymentType } from '/@/api/agent';
import { useMessage } from '/@/hooks/message';

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

// 定义变量
const visible = ref(false);
const formLoading = ref(false);
const formRef = ref();

// 表单数据
const formData = reactive({
	agentPaymentTypeId: '',
	paymentTypeId: '',
	agentUserId: '',
	paymentType: '',
	channelName: '',
	paymentName: '',
	status: true,
	feeType: '',
	feeRate: 0,
	feeEvery: 0,
});

// 表单验证规则
const formRules = ref({
	status: [{ required: true, message: '请选择启用状态', trigger: 'change' }],
	feeType: [
		{
			validator: (rule: any, value: any, callback: any) => {
				// 只有代付需要选择手续费类型
				if (formData.paymentType === 'PAY' && !value) {
					callback(new Error('请选择手续费类型'));
				} else {
					callback();
				}
			},
			trigger: 'change',
		},
	],
	feeRate: [
		{
			validator: (rule: any, value: any, callback: any) => {
				// 代收：必填费率
				// 代付：百分比、百分比+固定 需要手续费比例
				const needFeeRate =
					formData.paymentType === 'HARVEST' ||
					(formData.paymentType === 'PAY' && (formData.feeType === 'PERCENTAGE' || formData.feeType === 'MIXED'));

				if (needFeeRate && !value && value !== 0) {
					callback(new Error(formData.paymentType === 'HARVEST' ? '请输入费率' : '请输入手续费比例'));
				} else if (value !== undefined && value !== null && (value < 0 || value > 100)) {
					callback(new Error('费率范围为0-100'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
	feeEvery: [
		{
			validator: (rule: any, value: any, callback: any) => {
				// 代付：固定、百分比+固定 需要手续费固定金额
				const needFeeEvery = formData.paymentType === 'PAY' && (formData.feeType === 'FIXED' || formData.feeType === 'MIXED');

				if (needFeeEvery && !value && value !== 0) {
					callback(new Error('请输入手续费固定金额'));
				} else if (value !== undefined && value !== null && value < 0) {
					callback(new Error('手续费固定金额不能小于0'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
});

// 打开弹窗
const openDialog = (row: any, agentUserId: string, paymentType: 'PAY' | 'HARVEST') => {
	visible.value = true;

	// 填充数据
	formData.agentPaymentTypeId = row.agentPaymentTypeId;
	formData.paymentTypeId = row.paymentTypeId;
	formData.agentUserId = agentUserId;
	formData.paymentType = paymentType;
	formData.channelName = row.channelName;
	formData.paymentName = row.paymentName;
	formData.status = row.status ?? true;
	formData.feeType = row.feeType || 'PERCENTAGE';
	formData.feeRate = row.feeRate || 0;
	formData.feeEvery = row.feeEvery || 0;

	nextTick(() => {
		formRef.value?.clearValidate();
	});
};

// 提交表单
const handleSubmit = async () => {
	const valid = await formRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		formLoading.value = true;
		const submitData = {
			agentPaymentTypeId: formData.agentPaymentTypeId,
			paymentTypeId: formData.paymentTypeId,
			agentUserId: formData.agentUserId,
			paymentType: formData.paymentType,
			status: formData.status,
			feeType: formData.feeType,
			feeRate: formData.feeRate,
			feeEvery: formData.feeEvery,
		};
		await editAgentPaymentType(submitData);
		useMessage().success('配置成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		formLoading.value = false;
	}
};

// 暴露方法
defineExpose({
	openDialog,
});
</script>
