<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="手续费类型">
						<el-input :value="getAgentFeeTypeLabel()" disabled />
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20" v-if="formData.agentFeeType === 'PERCENTAGE' || formData.agentFeeType === 'MIXED'">
					<el-form-item label="手续费比例(%)">
						<el-input :value="formData.agentFeeRate !== undefined && formData.agentFeeRate !== null ? formData.agentFeeRate : '未设置'" disabled />
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20" v-if="formData.agentFeeType === 'FIXED' || formData.agentFeeType === 'MIXED'">
					<el-form-item label="手续费固定金额">
						<el-input :value="formData.agentFeeEvery !== undefined && formData.agentFeeEvery !== null ? formData.agentFeeEvery : '未设置'" 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="merchantUserRate">
						<el-input-number
							placeholder="请输入商户费率"
							v-model="formData.merchantUserRate"
							: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="merchantUserFeeType">
							<el-radio-group v-model="formData.merchantUserFeeType">
								<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.merchantUserFeeType === 'PERCENTAGE' || formData.merchantUserFeeType === 'MIXED'">
						<el-form-item label="手续费比例(%)" prop="merchantUserRate">
							<el-input-number
								placeholder="请输入手续费比例"
								v-model="formData.merchantUserRate"
								:min="0"
								:max="100"
								:precision="2"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>

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

				<el-col :span="24" class="mb20">
					<el-form-item label="单笔最小金额" prop="singleMinAmount">
						<el-input-number placeholder="请输入单笔最小金额" v-model="formData.singleMinAmount" :min="0" :precision="2" style="width: 100%" />
						<div class="form-tip">通道限制：{{ formData.baseSingleMinAmount || 0 }}</div>
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="单笔最大金额" prop="singleMaxAmount">
						<el-input-number placeholder="请输入单笔最大金额" v-model="formData.singleMaxAmount" :min="0" :precision="2" style="width: 100%" />
						<div class="form-tip">通道限制：{{ formData.baseSingleMaxAmount || 0 }}</div>
					</el-form-item>
				</el-col>
			</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="MerchantPaymentConfigDialog" setup>
import { editMerchantPaymentType } from '/@/api/merchant';
import { useMessage } from '/@/hooks/message';

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

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

// 表单数据
const formData = reactive({
	merchantPaymentTypeId: '',
	paymentTypeId: '',
	merchantUserId: '',
	paymentType: '',
	channelName: '',
	paymentName: '',
	status: true,
	agentFeeType: '',
	agentFeeRate: 0,
	agentFeeEvery: 0,
	merchantUserRate: 0,
	merchantUserFeeType: '',
	merchantUserFeeEvery: 0,
	singleMinAmount: 0,
	singleMaxAmount: 0,
	baseSingleMinAmount: 0,
	baseSingleMaxAmount: 0,
});

// 获取代理商手续费类型标签
const getAgentFeeTypeLabel = () => {
	if (!formData.agentFeeType) return '未设置';
	const typeMap: Record<string, string> = {
		PERCENTAGE: '百分比',
		FIXED: '固定',
		MIXED: '百分比+固定',
	};
	return typeMap[formData.agentFeeType] || '未设置';
};

// 表单验证规则
const formRules = ref({
	status: [{ required: true, message: '请选择启用状态', trigger: 'change' }],
	merchantUserRate: [
		{
			validator: (rule: any, value: any, callback: any) => {
				// 代收：商户费率必填
				if (formData.paymentType === 'HARVEST' && !value && value !== 0) {
					callback(new Error('请输入商户费率'));
				}
				// 代付：百分比、百分比+固定 需要手续费比例
				else if (
					formData.paymentType === 'PAY' &&
					(formData.merchantUserFeeType === 'PERCENTAGE' || formData.merchantUserFeeType === 'MIXED') &&
					!value &&
					value !== 0
				) {
					callback(new Error('请输入手续费比例'));
				} else if (value !== undefined && value !== null && (value < 0 || value > 100)) {
					callback(new Error('费率比例范围为0-100'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
	merchantUserFeeType: [
		{
			validator: (rule: any, value: any, callback: any) => {
				// 代付：手续费类型必填
				if (formData.paymentType === 'PAY' && !value) {
					callback(new Error('请选择手续费类型'));
				} else {
					callback();
				}
			},
			trigger: 'change',
		},
	],
	merchantUserFeeEvery: [
		{
			validator: (rule: any, value: any, callback: any) => {
				// 代付：固定、百分比+固定 需要手续费固定金额
				const needFeeEvery = formData.paymentType === 'PAY' && (formData.merchantUserFeeType === 'FIXED' || formData.merchantUserFeeType === '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',
		},
	],
	singleMinAmount: [
		{
			validator: (rule: any, value: any, callback: any) => {
				if (value && formData.singleMaxAmount && value > formData.singleMaxAmount) {
					callback(new Error('单笔最小金额不能大于单笔最大金额'));
				} else if (value && formData.baseSingleMinAmount && value < formData.baseSingleMinAmount) {
					callback(new Error(`单笔最小金额不能小于通道限制(${formData.baseSingleMinAmount})`));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
	singleMaxAmount: [
		{
			validator: (rule: any, value: any, callback: any) => {
				if (value && formData.singleMinAmount && value < formData.singleMinAmount) {
					callback(new Error('单笔最大金额不能小于单笔最小金额'));
				} else if (value && formData.baseSingleMaxAmount && value > formData.baseSingleMaxAmount) {
					callback(new Error(`单笔最大金额不能大于通道限制(${formData.baseSingleMaxAmount})`));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
});

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

	// 填充数据
	formData.merchantPaymentTypeId = row.merchantPaymentTypeId;
	formData.paymentTypeId = row.paymentTypeId;
	formData.merchantUserId = merchantUserId;
	formData.paymentType = paymentType;
	formData.channelName = row.channelName;
	formData.paymentName = row.paymentName;
	formData.status = row.status ?? true;
	formData.agentFeeType = row.agentFeeType || '';
	formData.agentFeeRate = row.agentFeeRate || 0;
	formData.agentFeeEvery = row.agentFeeEvery || 0;
	formData.merchantUserRate = row.merchantUserRate || 0;
	// 代收固定为PERCENTAGE，代付根据实际值设置
	if (paymentType === 'HARVEST') {
		formData.merchantUserFeeType = 'PERCENTAGE';
		formData.merchantUserFeeEvery = 0;
	} else {
		formData.merchantUserFeeType = row.merchantUserFeeType || 'PERCENTAGE';
		formData.merchantUserFeeEvery = row.merchantUserFeeEvery || 0;
	}
	formData.baseSingleMinAmount = row.baseSingleMinAmount || 0;
	formData.baseSingleMaxAmount = row.baseSingleMaxAmount || 0;
	// 如果没有值，默认等于通道限制金额
	formData.singleMinAmount = row.singleMinAmount || formData.baseSingleMinAmount;
	formData.singleMaxAmount = row.singleMaxAmount || formData.baseSingleMaxAmount;

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

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

	try {
		formLoading.value = true;
		const submitData: any = {
			merchantPaymentTypeId: formData.merchantPaymentTypeId,
			paymentTypeId: formData.paymentTypeId,
			merchantUserId: formData.merchantUserId,
			paymentType: formData.paymentType,
			status: formData.status,
			singleMinAmount: formData.singleMinAmount,
			singleMaxAmount: formData.singleMaxAmount,
		};

		// 代收：提交商户费率，feeType固定为PERCENTAGE
		if (formData.paymentType === 'HARVEST') {
			submitData.merchantUserRate = formData.merchantUserRate;
			submitData.feeType = 'PERCENTAGE';
			submitData.feeRate = formData.merchantUserRate; // 代收的费率就是merchantUserRate
			submitData.feeEvery = 0;
		}

		// 代付：提交手续费类型和对应字段
		if (formData.paymentType === 'PAY') {
			submitData.feeType = formData.merchantUserFeeType;
			submitData.feeRate = formData.merchantUserRate;
			submitData.feeEvery = formData.merchantUserFeeEvery;
		}

		await editMerchantPaymentType(submitData);
		useMessage().success('配置成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		formLoading.value = false;
	}
};

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

<style scoped>
.form-tip {
	font-size: 12px;
	color: #909399;
	margin-top: 4px;
}
</style>
