<template>
    <ele-page>
        <div class="bg-white p-4">
            <div class="mb-4">
                <el-button type="success" :icon="Plus" @click="handleAdd"
                    >添加运费模板</el-button
                >
            </div>

            <div v-loading="loading">
                <div
                    v-if="templateList.length === 0"
                    class="text-center py-10 text-gray-400"
                >
                    暂无运费模板
                </div>

                <div
                    v-for="(tpl, index) in templateList"
                    :key="tpl.id"
                    class="mb-6 border border-gray-200 rounded-lg shadow-sm overflow-hidden bg-white"
                >
                    <!-- Template Header -->
                    <div
                        class="bg-green-50 px-4 py-3 flex justify-between items-center border-b border-gray-200"
                    >
                        <div class="flex items-center space-x-4">
                            <span class="font-bold text-gray-700">{{
                                tpl.templeteName
                            }}</span>
                            <el-tag
                                v-if="tpl.useStatus === 1"
                                type="success"
                                size="small"
                                >使用中</el-tag
                            >
                        </div>
                        <div class="space-x-4 text-sm flex items-center">
                            <span class="text-gray-400 text-xs"
                                >更新时间: {{ tpl.updateTime }}</span
                            >
                            <el-button
                                v-if="tpl.useStatus === 0"
                                type="success"
                                link
                                @click="handleEnable(tpl)"
                                >启用</el-button
                            >
                            <!-- <el-button type="primary" link @click="handleCopy(tpl)">复制模板</el-button> -->
                            <el-button
                                type="primary"
                                link
                                @click="handleEdit(tpl)"
                                >编辑</el-button
                            >
                            <!-- <el-button type="danger" link @click="handleDelete(index)">删除</el-button> -->
                        </div>
                    </div>

                    <!-- Rules Table -->
                    <el-table
                        :data="tpl.templeteList"
                        style="width: 100%"
                        :show-header="true"
                    >
                        <el-table-column
                            prop="shippingProvinceList"
                            label="运送范围"
                            min-width="300"
                        >
                            <template #default="{ row }">
                                <span
                                    v-if="
                                        !row.shippingProvinceList ||
                                        row.shippingProvinceList.length === 0
                                    "
                                    >未指定地区</span
                                >
                                <span v-else>{{
                                    row.shippingProvinceList
                                        .map((p) => p.provinceName)
                                        .join('、')
                                }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="计费规则"
                            width="200"
                            align="center"
                        >
                            <template #default="{ row }">
                                <span v-if="row.minMoney > 0"
                                    >满{{ row.minMoney }}元包邮</span
                                >
                                <span v-else>默认</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="shippingMoney"
                            label="基础运费"
                            width="150"
                            align="center"
                        />
                        <el-table-column
                            label="配送方式"
                            width="150"
                            align="center"
                        >
                            <template #default> 快递 </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <div class="flex justify-end mt-4">
                <el-pagination
                    v-model:current-page="pageParams.page"
                    v-model:page-size="pageParams.limit"
                    :total="total"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>

            <EditDialog ref="editDialogRef" @success="handleSaveSuccess" />
        </div>
    </ele-page>
</template>

<script setup>
    import { ref, reactive, onMounted } from 'vue';
    import { Plus } from '@element-plus/icons-vue';
    import { ElMessageBox, ElMessage } from 'element-plus';
    import request from '@/utils/request';
    import EditDialog from './components/edit-dialog.vue';

    const editDialogRef = ref(null);
    const loading = ref(false);
    const templateList = ref([]);
    const total = ref(0);
    const pageParams = reactive({
        page: 1,
        limit: 10
    });

    const getList = async () => {
        loading.value = true;
        try {
            const res = await request.get('/shipping/templete/pagelist', {
                params: pageParams
            });
            if (res.data.code === 200) {
                // Assuming standard structure based on description (rows, total) but usually wrapped in data
                // Check if response is directly the object or inside data
                // API desc says: Response -> { total: 0, rows: [...] }
                // Axios usually returns { data: { ...API_RESPONSE... } }
                // So res.data should be the object.
                const data = res.data;
                // However, sometimes it is res.data.data if wrapped.
                // The screenshot shows "返回响应 200 ... rows array". It looks like the root object has rows.
                // But standard practice in this project (based on previous files) often checks res.data.code.
                // If res.data has code, then rows might be in res.data.rows or res.data.data.rows.
                // The screenshot shows `code` and `rows` at the same level.
                // So res.data.rows.
                templateList.value = data.rows || [];
                total.value = data.total || 0;
            }
        } catch (error) {
            console.error(error);
            ElMessage.error('获取列表失败');
        } finally {
            loading.value = false;
        }
    };

    const handleAdd = () => {
        editDialogRef.value?.handleOpen();
    };

    const handleEdit = (tpl) => {
        editDialogRef.value?.handleOpen(tpl);
    };

    // Copy and Delete not implemented in API description provided
    // const handleCopy = (tpl) => { ... };
    // const handleDelete = (index) => { ... };

    const handleEnable = async (tpl) => {
        try {
            await ElMessageBox.confirm(
                `确定启用"${tpl.templeteName}"吗？`,
                '提示',
                {
                    type: 'warning'
                }
            );
            const res = await request.post(
                '/shipping/templete/enableShippingTemplete',
                { id: tpl.id }
            );
            if (res.data.code === 200) {
                ElMessage.success('启用成功');
                getList();
            } else {
                ElMessage.error(res.data.msg || '启用失败');
            }
        } catch (error) {
            if (error !== 'cancel') {
                console.error(error);
                // ElMessage.error('操作失败');
            }
        }
    };

    const handleSaveSuccess = () => {
        getList();
    };

    const handleSizeChange = (val) => {
        pageParams.limit = val;
        getList();
    };

    const handleCurrentChange = (val) => {
        pageParams.page = val;
        getList();
    };

    onMounted(() => {
        getList();
    });
</script>
