<template>
    <el-container>
        <el-main>
            <div class="amount-management">
                <!-- 统一金额区间配置 -->
                <div class="config-section">
                    <div class="section-header">
                        <h4>{{ t('modules.payment.amountRangeConfig') }}</h4>
                        <p class="section-desc my-10px text-gray">{{ t('modules.payment.amountRangeDesc', {
                            methodName:
                                paymentName
                        }) }}
                        </p>
                    </div>

                    <el-form ref="rangeFormRef" :model="rangeForm" :rules="rangeRules" label-width="140px"
                        class="range-form" inline>
                        <el-form-item :label="t('modules.payment.minAmount')" prop="miniPrice">
                            <el-input-number v-model="rangeForm.miniPrice" :min="0" :max="999999999" :precision="0"
                                style="width: 160px" :placeholder="t('modules.payment.enterMinAmount')" />
                        </el-form-item>
                        <el-form-item :label="t('modules.payment.maxAmount')" prop="maxPrice">
                            <el-input-number v-model="rangeForm.maxPrice" :min="0" :max="999999999" :precision="0"
                                style="width: 160px" :placeholder="t('modules.payment.enterMaxAmount')" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" :loading="rangeSubmitLoading" @click="handleRangeSubmit">
                                {{ t('common.save') }}
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <el-divider />

                <!-- 金额配置 -->
                <div class="goods-section">
                    <div class="section-header">
                        <h4>{{ t('modules.payment.amountConfig') }}</h4>
                        <div class="header-actions">
                            <el-button type="primary" @click="handleAddGoods">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                {{ t('common.add') }}
                            </el-button>
                        </div>
                    </div>

                    <!-- 商品列表 -->
                    <div class="sa-table-wrap" v-loading="tableLoading">
                        <el-table height="100%" class="sa-table" :data="tableData" stripe row-key="id">
                            <template #empty>
                                <sa-empty />
                            </template>
                            <el-table-column type="selection" width="48" align="center" />
                            <el-table-column prop="id" label="ID" min-width="100" />
                            <el-table-column prop="amount" :label="t('modules.payment.amount')" min-width="120"
                                align="center">
                                <template #default="{ row }">
                                    <span>৳{{ row.amount || 0 }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="status" :label="t('common.status')" min-width="100" align="center">
                                <template #default="{ row }">
                                    <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                                        {{ row.status === 1 ? t('common.enabled') : t('common.disabled') }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="sortNum" :label="t('form.sort')" min-width="80" align="center">
                                <template #default="{ row }">
                                    <span>{{ row.sortNum || 0 }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="createTime" :label="t('form.createTime')" min-width="160">
                                <template #default="{ row }">
                                    <span>{{ row.createTime || '--' }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column fixed="right" :label="t('common.actions')" min-width="140">
                                <template #default="{ row }">
                                    <el-button class="is-link" type="primary" @click="handleEditGoods(row)">
                                        {{ t('common.edit') }}
                                    </el-button>
                                    <el-popconfirm width="fit-content" :confirm-button-text="t('common.confirm')"
                                        :cancel-button-text="t('common.cancel')" :title="t('message.confirmDelete')"
                                        @confirm="handleDeleteGoods(row)">
                                        <template #reference>
                                            <el-button class="is-link" type="danger">{{ t('common.delete')
                                                }}</el-button>
                                        </template>
                                    </el-popconfirm>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </el-main>

        <el-footer class="sa-footer--submit">
            <el-button @click="handleCancel">{{ t('common.close') }}</el-button>
        </el-footer>
    </el-container>

    <!-- 移除商品编辑弹窗，使用独立组件 -->
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { Plus } from '@element-plus/icons-vue';
import { usePagination, useModal } from '@/sheep/hooks';
import api from '../../../api';
import GoodsEdit from './GoodsEdit.vue';

const { t } = useI18n();

const emit = defineEmits(['modalCallBack']);
const props = defineProps({
    modal: {
        type: Object,
        required: true,
    },
});

// 获取传入的参数
const paymentId = computed(() => props.modal.params.paymentId);
const paymentName = computed(() => props.modal.params.paymentName);

// 金额区间配置
const rangeFormRef = ref();
const rangeSubmitLoading = ref(false);
const rangeForm = reactive({
    miniPrice: 0,
    maxPrice: 0,
});

// 移除联动判断，允许用户随意输入

const rangeRules = reactive({
    miniPrice: [
        { required: true, message: t('modules.payment.minAmountRequired'), trigger: 'blur' },
        { type: 'number', min: 0, message: t('modules.payment.minAmountValidation'), trigger: 'blur' }
    ],
    maxPrice: [
        { required: true, message: t('modules.payment.maxAmountRequired'), trigger: 'blur' },
        { type: 'number', min: 0, message: t('modules.payment.maxAmountValidation'), trigger: 'blur' }
    ],
});

// 商品管理
const tableLoading = ref(false);
const tableData = ref([]);
const { pageData } = usePagination();

// 商品编辑弹窗
const goodsFormRef = ref();

// 获取当前支付限额配置
async function getCurrentLimit() {
    try {
        // 这里可以调用获取当前配置的接口
        // const { code, data } = await api.payment.getPaymentLimit(paymentId.value);
        // if (code == 200 && data) {
        //   rangeForm.miniPrice = data.miniPrice || 1;
        //   rangeForm.maxPrice = data.maxPrice || 100000;
        // }
    } catch (error) {
        console.error('获取支付限额配置失败:', error);
    }
}

// 获取商品列表
async function getGoodsList() {
    try {
        tableLoading.value = true;
        const { code, data } = await api.payment.goods.list({
            methodId: paymentId.value,
            page: pageData.page,
            size: pageData.size,
        });

        if (code == 200 && data) {
            // 根据真实数据结构处理
            if (Array.isArray(data.list)) {
                tableData.value = data.list;

                // 同时更新金额区间配置
                if (data.miniPrice !== undefined) {
                    rangeForm.miniPrice = data.miniPrice;
                }
                if (data.maxPrice !== undefined) {
                    rangeForm.maxPrice = data.maxPrice;
                }
            } else {
                tableData.value = [];
                pageData.total = 0;
            }
        } else {
            tableData.value = [];
            pageData.total = 0;
        }
    } catch (error) {
        console.error('获取商品列表失败:', error);
        ElMessage.error(t('modules.payment.getGoodsListFailed'));
        tableData.value = [];
        pageData.total = 0;
    } finally {
        tableLoading.value = false;
    }
}

// 保存金额区间配置
async function handleRangeSubmit() {
    try {
        await rangeFormRef.value.validate();

        // 保存时验证最大金额大于等于最小金额
        if (rangeForm.maxPrice < rangeForm.miniPrice) {
            ElMessage.error(t('modules.payment.maxGreaterThanMin'));
            return;
        }

        rangeSubmitLoading.value = true;

        const { code } = await api.payment.editPaymentLimit(paymentId.value, {
            miniPrice: rangeForm.miniPrice,
            maxPrice: rangeForm.maxPrice,
        });

        if (code == 200) {
            ElMessage.success(t('modules.payment.rangeConfigSuccess'));
        }
    } catch (error) {
        console.error('保存金额区间配置失败:', error);
        if (error.response?.data?.message) {
            ElMessage.error(error.response.data.message);
        } else {
            ElMessage.error(t('modules.payment.rangeConfigFailed'));
        }
    } finally {
        rangeSubmitLoading.value = false;
    }
}

// 新增
function handleAddGoods() {
    useModal(
        GoodsEdit,
        {
            title: t('common.add'),
            type: 'add',
            methodId: paymentId.value,
        },
        {
            confirm: () => {
                getGoodsList();
            },
        },
    );
}

// 编辑
function handleEditGoods(row) {
    useModal(
        GoodsEdit,
        {
            title: t('common.edit'),
            type: 'edit',
            id: row.id,
            methodId: paymentId.value,
        },
        {
            confirm: () => {
                getGoodsList();
            },
        },
    );
}

// 删除商品
async function handleDeleteGoods(row) {
    try {
        const { code } = await api.payment.goods.delete(row.id);

        if (code == 200) {
            ElMessage.success(t('modules.payment.deleteGoodsSuccess'));
            // 刷新列表
            getGoodsList();
        }
    } catch (error) {
        console.error('删除商品失败:', error);
        ElMessage.error(t('modules.payment.deleteGoodsFailed'));
    }
}



// 取消操作
function handleCancel() {
    emit('modalCallBack', { event: 'cancel' });
}

onMounted(() => {
    getCurrentLimit();
    getGoodsList();
});
</script>

<style lang="scss" scoped>
.amount-management {
    .config-section {
        margin-bottom: 20px;

        .section-header {
            margin-bottom: 16px;

            h4 {
                margin: 0 0 4px 0;
                font-size: 16px;
                font-weight: 600;
                color: var(--el-text-color-primary);
            }

            .section-desc {
                margin: 0;
                font-size: 13px;
                color: var(--el-text-color-regular);
            }
        }

        .range-form {
            background: var(--el-bg-color-page);
            padding: 16px 20px;
            border-radius: 6px;
            border: 1px solid var(--el-border-color-light);

            .unit-text {
                margin-left: 8px;
                color: var(--el-text-color-regular);
                font-size: 14px;
            }

            :deep(.el-form-item) {
                margin-right: 32px;
                margin-bottom: 0;
            }
        }
    }

    .goods-section {
        .section-header {
            margin-bottom: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            h4 {
                margin: 0;
                font-size: 16px;
                font-weight: 600;
                color: var(--el-text-color-primary);
            }
        }

        .sa-table-wrap {
            height: 400px;

            .sa-table {
                height: 100%;
            }
        }
    }

    .el-divider {
        margin: 24px 0;
    }
}

.sa-footer--submit {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 24px;
    border-top: 1px solid var(--el-border-color-light);
    background: var(--el-bg-color-page);
}

.dialog-footer {
    display: flex;
    gap: 12px;
}

// 弹窗样式优化
:deep(.el-dialog) {
    .el-dialog__header {
        padding: 20px 24px 16px;
        border-bottom: 1px solid var(--el-border-color-light);

        .el-dialog__title {
            font-weight: 600;
            color: var(--el-text-color-primary);
        }
    }

    .el-dialog__body {
        padding: 20px 24px;
    }

    .el-dialog__footer {
        padding: 16px 24px 20px;
        border-top: 1px solid var(--el-border-color-light);
    }
}

// 表单样式优化
:deep(.el-form-item) {
    .el-form-item__label {
        font-weight: 500;
        color: var(--el-text-color-regular);
    }

    .el-form-item__content {
        .el-input-number {
            .el-input__inner {
                text-align: left;
            }
        }
    }
}
</style>