<template>
	<el-dialog :close-on-click-modal="false" :title="dialogTitle" draggable v-model="visible" width="1200px" @close="handleClose">
		<!-- 搜索表单 -->
		<el-row class="ml10">
			<el-form :inline="true" :model="queryForm" @keyup.enter="loadTypeList" ref="queryRef">
				<el-form-item label="支付类型名称/代码" prop="query">
					<el-input placeholder="请输入支付类型名称或代码" style="max-width: 180px" v-model="queryForm.query" clearable />
				</el-form-item>
				<el-form-item label="启用状态" prop="status">
					<el-select v-model="queryForm.status" placeholder="请选择状态" clearable style="width: 120px">
						<el-option label="启用" :value="true" />
						<el-option label="禁用" :value="false" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button @click="loadTypeList" icon="search" type="primary">查询</el-button>
					<el-button @click="resetQuery" icon="Refresh">重置</el-button>
				</el-form-item>
			</el-form>
		</el-row>
		<el-row>
			<div class="mb8" style="width: 100%">
				<el-button @click="handleAdd" class="ml10" icon="folder-add" type="primary" v-auth="'payment_type_save'">新增</el-button>
			</div>
		</el-row>

		<!-- 表格 -->
		<el-table
			:data="typeList"
			v-loading="loading"
			border
			:cell-style="tableStyle.cellStyle"
			:header-cell-style="tableStyle.headerCellStyle"
			style="width: 100%"
			max-height="500"
		>
			<el-table-column label="ID" prop="id" show-overflow-tooltip />
			<el-table-column label="支付类型名称" prop="paymentName" show-overflow-tooltip />
			<el-table-column label="支付类型代码" prop="paymentCode" show-overflow-tooltip />
			<el-table-column label="启用状态" prop="status" show-overflow-tooltip>
				<template #default="scope">
					<el-switch
						v-model="scope.row.status"
						@change="handleStatusChange(scope.row)"
						:active-value="true"
						:inactive-value="false"
						v-auth="'payment_type_edit'"
					/>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" width="100">
				<template #default="scope">
					<el-button icon="edit-pen" @click="handleEdit(scope.row)" text type="primary" v-auth="'payment_type_edit'">编辑</el-button>
				</template>
			</el-table-column>
		</el-table>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">关闭</el-button>
			</span>
		</template>
	</el-dialog>

	<!-- 新增/编辑表单弹窗 -->
	<el-dialog :close-on-click-modal="false" :title="formData.id ? '编辑支付类型' : '新增支付类型'" draggable v-model="formVisible" width="600px">
		<el-form :model="formData" :rules="formRules" label-width="140px" ref="formRef" v-loading="formLoading">
			<el-form-item label="支付类型名称" prop="paymentName">
				<el-input placeholder="请输入支付类型名称" v-model="formData.paymentName" />
			</el-form-item>

			<el-form-item label="支付类型代码" prop="paymentCode">
				<el-input placeholder="请输入支付类型代码" v-model="formData.paymentCode" />
			</el-form-item>

			<el-form-item label="启用状态" prop="status">
				<el-radio-group v-model="formData.status" :disabled="!!formData.id">
					<el-radio :label="true">启用</el-radio>
					<el-radio :label="false">禁用</el-radio>
				</el-radio-group>
			</el-form-item>
		</el-form>

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

<script lang="ts" name="PayTypeDialog" setup>
import { fetchTypeList, addType, getType, putType, changeTypeStatus } from '/@/api/payment';
import { useMessage } from '/@/hooks/message';
import { rule } from '/@/utils/validate';

// 定义表格样式
const tableStyle = {
	cellStyle: { textAlign: 'center' },
	headerCellStyle: { textAlign: 'center', background: '#f5f7fa' },
};

// 定义变量
const visible = ref(false);
const formVisible = ref(false);
const loading = ref(false);
const formLoading = ref(false);
const queryRef = ref();
const formRef = ref();
const channelId = ref('');
const paymentType = ref('');
const dialogTitle = ref('');
const typeList = ref<any[]>([]);

// 查询表单
const queryForm = reactive({
	query: '',
	status: undefined,
});

// 表单数据
const formData = reactive({
	id: '',
	channelId: '',
	paymentName: '',
	paymentCode: '',
	paymentType: '',
	status: true,
});

// 表单验证规则
const formRules = ref({
	paymentName: [
		{ required: true, message: '请输入支付类型名称', trigger: 'blur' },
		{ validator: rule.overLength, trigger: 'blur' },
	],
	paymentCode: [
		{ required: true, message: '请输入支付类型代码', trigger: 'blur' },
		{ validator: rule.overLength, trigger: 'blur' },
	],
	status: [{ required: true, message: '请选择启用状态', trigger: 'change' }],
});

// 打开弹窗
const openDialog = (id: string, type: 'HARVEST' | 'PAY') => {
	visible.value = true;
	channelId.value = id;
	paymentType.value = type;
	dialogTitle.value = type === 'HARVEST' ? '代收支付配置' : '代付支付配置';

	// 重置查询表单
	queryForm.query = '';
	queryForm.status = undefined;

	// 加载数据
	loadTypeList();
};

// 加载支付类型列表
const loadTypeList = async () => {
	try {
		loading.value = true;
		const params = {
			...queryForm,
			paymentType: paymentType.value,
		};
		const res = await fetchTypeList(channelId.value, params);
		typeList.value = res.data || [];
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 重置查询
const resetQuery = () => {
	queryRef.value?.resetFields();
	loadTypeList();
};

// 新增
const handleAdd = () => {
	formVisible.value = true;
	formData.id = '';
	formData.channelId = channelId.value;
	formData.paymentName = '';
	formData.paymentCode = '';
	formData.paymentType = paymentType.value;
	formData.status = true;

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

// 编辑
const handleEdit = async (row: any) => {
	try {
		formLoading.value = true;
		formVisible.value = true;
		const res = await getType(row.id);
		Object.assign(formData, res.data);
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		formLoading.value = false;
	}
};

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

	try {
		formLoading.value = true;
		if (formData.id) {
			await putType(formData.id, formData);
			useMessage().success('编辑成功');
		} else {
			await addType(formData);
			useMessage().success('新增成功');
		}
		formVisible.value = false;
		loadTypeList();
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		formLoading.value = false;
	}
};

// 状态切换
const handleStatusChange = async (row: any) => {
	try {
		await changeTypeStatus(row.id);
		useMessage().success('状态修改成功');
		loadTypeList();
	} catch (err: any) {
		useMessage().error(err.msg);
		// 恢复原状态
		row.status = !row.status;
	}
};

// 关闭弹窗
const handleClose = () => {
	typeList.value = [];
};

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