<template>
    <x-search-bar class="mb-8-2">
        <template #default="{ gutter, colSpan }">
            <a-form :label-col="{ style: { width: '100px' } }" :model="searchFormData" layout="inline">
                <a-row :gutter="gutter">
                    <a-col v-bind="colSpan">
                        <a-form-item :label="'站点名称'" name="name">
                            <a-input :placeholder="'请输入站点名称'" v-model:value="searchFormData.name"></a-input>
                        </a-form-item>
                    </a-col>

                    <a-col v-bind="colSpan">
                        <a-form-item :label="'站点类型'" name="type">
                            <a-select v-model:value="searchFormData.stationType" placeholder="请选择站点类型" allow-clear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Station_Type" :key="item.dval"
                                    :value="item.dval">
                                    {{ item.introduction }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <a-col v-bind="colSpan">
                        <a-form-item :label="'所在区域'" name="area">
                            <AreaCascader v-model:value="searchFormData.areaCodes" @change="onAreaChange" />
                        </a-form-item>
                    </a-col>

                    <a-col v-bind="colSpan">
                       <a-form-item label="组织所在区域" name="areaLabels">
                          <NodeTree v-model:value="searchFormData.serviceNodeIds" />
                        </a-form-item>
                    </a-col>

                    <a-col v-bind="colSpan" style="text-align: right;">
                        <a-space>
                            <a-button @click="handleResetSearch">{{ $t('button.reset') }}</a-button>
                            <a-button ghost type="primary" @click="handleSearch">
                                {{ $t('button.search') }}
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>

            </a-form>
        </template>
    </x-search-bar>

    <a-card>
        <!-- 添加标题和横线 -->
        <div class="title-container">
            <h3>服务站点列表</h3>
            <div class="title-line"></div>
        </div>

        <x-action-bar class="mb-8-2">
            <!-- 增加按钮之间的间距 -->
            <a-space :size="12">
                <a-button v-action="'add'" type="primary" @click="$refs.editDialogRef.handleCreate()">
                    新建
                </a-button>

                <!-- 修改导入按钮的点击事件 -->
                <a-button v-action="'add'" type="primary" @click="showImportModal = true">
                    导入
                </a-button>

                <a-button v-action="'add'" type="primary" @click="showImportRecordModal = true">
                    <template #icon>
                        <UnorderedListOutlined />
                    </template>
                    导入记录
                </a-button>

                <a-button v-action="'add'" type="primary" @click="handleExport">
                    导出
                </a-button>

                <a-button v-action="'add'" type="primary" @click="handleShowExportRecords">
                    <template #icon>
                        <UnorderedListOutlined />
                    </template>
                    导出记录
                </a-button>
            </a-space>
        </x-action-bar>

        <a-table rowKey="id" :loading="loading" :pagination="true" :columns="columns" :data-source="listData" :scroll="{ x: 'max-content' }">
            <template #bodyCell="{ column, record }" >
                <template v-if="'menuType' === column.key">
                    <!--菜单-->
                    <a-tag v-if="menuTypeEnum.is('page', record.type)" color="processing">
                        {{ menuTypeEnum.getDesc(record.type) }}
                    </a-tag>
                    <!--按钮-->
                    <a-tag v-if="menuTypeEnum.is('button', record.type)" color="success">
                        {{ menuTypeEnum.getDesc(record.type) }}
                    </a-tag>
                </template>

                <template v-if="'createAt' === column.key">
                    {{ formatUtcDateTime(record.created_at) }}
                </template>

                <template v-else-if="column.key === 'status'">
                    <a-tag :color="record.status === '1' ? 'processing' : 'default'" v-if="record.status != '' ">
                        {{ record.status === '1' ? '启用' : '停用' }}
                    </a-tag>
                     <span v-else>
                       --
                    </span>
                </template>

                <template v-if="'action' === column.key">
                    <x-action-button @click="$refs.editDialogRef.handleEdit(record)">
                        <a-tooltip>
                            <template #title>编辑</template>
                            编辑
                        </a-tooltip>
                    </x-action-button>

                    <x-action-button @click="$refs.editDialogRef.handleView(record)">
                        <a-tooltip>
                            <template #title>查看详情</template>
                            详情
                        </a-tooltip>
                    </x-action-button>
                    <x-action-button @click="handleDelete(record)">
                        <a-tooltip>
                            <template #title>{{ $t('pages.system.delete') }}</template>
                            删除
                        </a-tooltip>
                    </x-action-button>
                    <x-action-button @click="handleStatusChange(record)">
                        <a-tooltip>
                            <template #title>{{ $t('pages.system.delete') }}</template>
                            {{ record.status === '1' ? '停用' : '启用' }}
                        </a-tooltip>
                    </x-action-button>
                </template>
            </template>

        </a-table>
    </a-card>

    <edit-dialog @ok="onOk" ref="editDialogRef" />

    <!-- 导入弹框组件 -->
    <import-modal v-model:visible="showImportModal" @download="handleDownloadTemplate" @upload="handleFileUpload" />

    <!-- 导入记录弹框组件 -->
    <ImportRecordsModal v-model:visible="showImportRecordModal" title="导入记录" :fetchData="fetchImportRecords"
        @close="handleImportRecordClose" @view-details="handleViewImportDetails"
        @download-result="handleDownloadImportResult" @retry-import="handleRetryImport" />

    <!-- 导出记录弹框组件 -->
    <ExportRecordsModal v-model="showExportRecordModal" title="导出记录" :fetchData="fetchExportRecords"
        @close="handleExportRecordClose" @view-details="handleViewExportDetails"
        @download-result="handleDownloadExportResult" @retry-export="handleRetryExport" />
</template>

<script setup>
import { Modal, message } from 'ant-design-vue'
import { ref } from 'vue'
import { UnorderedListOutlined, EditOutlined, PlusCircleOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import apis from '@/apis'
import { config } from '@/config'
import { menuTypeEnum, statusTypeEnum } from '@/enums/system'
import { usePagination, useForm } from '@/hooks'
import { formatUtcDateTime } from '@/utils/util'
import EditDialog from './components/EditDialog.vue'
// 引入导入组件
import ImportModal from '@/components/Import/index.vue'
// 引入导入记录组件
import ImportRecordsModal from '@/components/ImportRecord/index.vue'
import ExportRecordsModal from '@/components/ExportRecord/index.vue'
import { useI18n } from 'vue-i18n'
import storage from '@/utils/storage'
import AreaCascader from '@/components/AreaCascader/index.vue'
import NodeTree from '@/components/NodeTree/index.vue'

defineOptions({
    name: 'menu',
})
const { t } = useI18n() // 解构出t方法

// 控制导入弹框显示/隐藏的变量
const showImportModal = ref(false)

// 控制导入记录弹框显示/隐藏的变量
const showImportRecordModal = ref(false)
const showExportRecordModal = ref(false)

const columns = ref([
    {
        title: '站点名称',
        key: 'name',
        width: 150,
        ellipsis: true,
        customRender: ({ record }) => {
            return record?.name || '--'
        }
    },
    {
        title: '所在机构',
        key: 'orgName',
        width: 150,
        ellipsis: true,
        customRender: ({ record }) => {
            return record.organization?.name || '--'
        }
    },
    { title: '组织编码', dataIndex: 'orgCode', key: 'orgCode', width: 150 },
    { title: '站点类型', dataIndex: 'stationType', key: 'stationType', width: 120 },
    { title: '地址', dataIndex: 'address', key: 'address', width: 200, ellipsis: true },
    {
        title: '营业时间', key: 'businessHours', width: 150, customRender: ({ record }) => {
            return `${record.openAt || '--'} - ${record.closeAt || '--'}`;
        }
    },
    { title: '面积(㎡)', dataIndex: 'area', key: 'area', width: 100 },
    { title: '人员数量', dataIndex: 'memberNum', key: 'memberNum', width: 100 },
    {
        title: '创建时间', key: 'created_at', width: 180, customRender: ({ record }) => {
            return formatUtcDateTime(record.created_at);
        }
    },
    { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
    { title: '操作', key: 'action', width: 260, fixed: 'right' }
])
const { listData, loading, showLoading, hideLoading, searchFormData, paginationState, resetPagination } =
    usePagination()
const { resetForm } = useForm()
const editDialogRef = ref()
import { useDicsStore } from '@/store'
const dicsStore = useDicsStore()
const areaCodes = ref([])

getList()

/**
 * 获取菜单列表
 * @return {Promise<void>}
 */
async function getList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        console.log("=====searchFormData",searchFormData.value.areaCodes)

        const { success, data, total } = await apis.serviceMenu
            .getServiceSiteList({
                pageSize,
                current: current,
                // areaCodes:areaCodes,
                ...searchFormData.value,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === success) {
            //筛选type的值80对应about
            listData.value = data
            paginationState.total = total
        }
    } catch (error) {
        hideLoading()
    }
}

/**
 * 搜索
 */
function handleSearch() {
    resetPagination()
    getList()
}
/**
 * 重置
 */
function handleResetSearch() {
    searchFormData.value = {}
    resetPagination()
    getList()
}
/**
 * 删除
 * @param id
 */
function handleDelete({ id }) {
    Modal.confirm({
        title: '确认删除',
        content: '确认删除该服务站点？',
        okText: t('button.confirm'),
        onOk: () => {
            return new Promise((resolve, reject) => {
                ; (async () => {
                    try {
                        const { success } = await apis.serviceMenu.delServiceSite(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === success) {
                            resolve()
                            message.success(t('component.message.success.delete'))
                            await getList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}

// 停用启用
function handleStatusChange(record) {
    console.log(record.status);
    const isEnable = record.status == '1'; // 当前不是启用 → 要启用
    const actionText = isEnable ? '停用' : '启用';
    const confirmText = isEnable ? '确定要停用该站点吗？' : '确定要启用该站点吗？';

    Modal.confirm({
        title: `${actionText}站点`,
        content: confirmText,
        okText: '确定',
        cancelText: '取消',
        okType: isEnable ? 'danger' : 'primary',
        onOk: async () => {
            try {
                const { success } = await apis.serviceMenu.enableOrDisableServiceSite(
                    record.id,
                    { status: isEnable ? '2' : '1' }
                );

                if (success) {
                    message.success(`${actionText}成功`);
                    // 更新本地状态
                    getList()
                } else {
                    message.error(`${actionText}失败`);
                }
            } catch (error) {
                console.error('操作异常:', error);
                message.error('操作失败');
            }
        }
    });
}

/**
 * 编辑完成
 */
async function onOk() {
    await getList()
}

/**
 * 导出数据
 */
function handleExport() {
    Modal.confirm({
        title: '确认导出',
        content: '是否导出当前查询条件下的所有服务站点数据？',
        onOk: () => {
            // 调用导出API
            apis.exportServiceSite(searchFormData.value).then(() => {
                message.success('导出任务已提交，请在导出记录中查看进度');
                showExportRecordModal.value = true;
            }).catch(() => {
                message.error('导出任务提交失败');
            });
        }
    });
}

/**
 * 显示导出记录
 */
function handleShowExportRecords() {
    showExportRecordModal.value = true;
}

/**
 * 处理下载模板
 */
function handleDownloadTemplate() {
    // 调用API下载模板
    apis.downloadTemplate().then(() => {
        message.success('模板下载成功')
    }).catch(() => {
        message.error('模板下载失败')
    })
}

/**
 * 处理文件上传
 * @param file 选中的文件
 */
async function handleFileUpload(file) {
    try {
        showLoading()
        // 创建FormData对象
        const formData = new FormData()
        formData.append('file', file)

        // 调用上传API
        const { success } = await apis.uploadServiceSite(formData)

        hideLoading()
        if (config('http.code.success') === success) {
            message.success('文件上传成功')
            showImportModal.value = false
            // 重新获取列表数据
            await getMenuList()
        } else {
            message.error('文件上传失败')
        }
    } catch (error) {
        hideLoading()
        message.error('文件上传失败，请重试')
    }
}

// 处理选择框变化
function handleChange() {
    // 可以添加选择框变化后的逻辑
}

// 获取导入记录数据
const fetchImportRecords = async (params) => {
    // 模拟API调用 - 实际项目中需要替换为真实的API调用
    await new Promise(resolve => setTimeout(resolve, 800));

    // 模拟数据
    const mockData = [
        {
            taskId: 'BATCH_20231201_001',
            status: 'completed',
            alias: '服务站点数据导入',
            totalCount: 1500,
            successCount: 1480,
            failCount: 20,
            createTime: '2023-12-01 14:30:25',
            createByName: '张三',
            progress: 100
        },
        {
            taskId: 'BATCH_20231201_002',
            status: 'failed',
            alias: '服务站点信息导入',
            totalCount: 800,
            successCount: 750,
            failCount: 50,
            createTime: '2023-12-01 15:45:10',
            createByName: '李四',
            progress: 93.75
        },
        {
            taskId: 'BATCH_20231201_003',
            status: 'processing',
            alias: '服务站点数据导入',
            totalCount: 3200,
            successCount: 1200,
            failCount: 0,
            createTime: '2023-12-01 16:20:30',
            createByName: '王五',
            progress: 37.5
        },
        {
            taskId: 'BATCH_20231201_004',
            status: 'pending',
            alias: '服务站点批量导入',
            totalCount: 500,
            successCount: 0,
            failCount: 0,
            createTime: '2023-12-01 17:10:15',
            createByName: '赵六',
            progress: 0
        },
        {
            taskId: 'BATCH_20231201_005',
            status: 'completed',
            alias: '服务站点信息导入',
            totalCount: 2100,
            successCount: 2095,
            failCount: 5,
            createTime: '2023-12-01 18:05:40',
            createByName: '钱七',
            progress: 100
        }
    ];

    // 根据分页参数返回数据
    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;
    const list = mockData.slice(start, end);

    return {
        list,
        total: mockData.length
    };
};

// 获取导出记录数据
const fetchExportRecords = async (params) => {
    // 模拟API调用 - 实际项目中需要替换为真实的API调用
    await new Promise(resolve => setTimeout(resolve, 800));

    // 模拟数据
    const mockData = [
        {
            taskId: 'EXPORT_20231201_001',
            status: 'completed',
            alias: '服务站点数据导出',
            totalCount: 1500,
            successCount: 1500,
            failCount: 0,
            createTime: '2023-12-01 14:30:25',
            createByName: '张三',
            progress: 100
        },
        {
            taskId: 'EXPORT_20231201_002',
            status: 'completed',
            alias: '服务站点信息导出',
            totalCount: 800,
            successCount: 800,
            failCount: 0,
            createTime: '2023-12-01 15:45:10',
            createByName: '李四',
            progress: 100
        },
        {
            taskId: 'EXPORT_20231201_003',
            status: 'processing',
            alias: '服务站点数据导出',
            totalCount: 3200,
            successCount: 2500,
            failCount: 0,
            createTime: '2023-12-01 16:20:30',
            createByName: '王五',
            progress: 78.125
        },
        {
            taskId: 'EXPORT_20231201_004',
            status: 'pending',
            alias: '服务站点批量导出',
            totalCount: 500,
            successCount: 0,
            failCount: 0,
            createTime: '2023-12-01 17:10:15',
            createByName: '赵六',
            progress: 0
        },
        {
            taskId: 'EXPORT_20231201_005',
            status: 'completed',
            alias: '服务站点信息导出',
            totalCount: 2100,
            successCount: 2100,
            failCount: 0,
            createTime: '2023-12-01 18:05:40',
            createByName: '钱七',
            progress: 100
        }
    ];

    // 根据分页参数返回数据
    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;
    const list = mockData.slice(start, end);

    return {
        list,
        total: mockData.length
    };
};

// 关闭导入记录弹框
const handleImportRecordClose = () => {
    console.log('导入记录弹框已关闭');
};

// 查看导入详情
const handleViewImportDetails = (record) => {
    message.info(`查看批次 ${record.taskId} 的详情`);
    console.log('查看详情:', record);
};

// 下载导入结果
const handleDownloadImportResult = (record) => {
    message.success(`正在下载批次 ${record.taskId} 的结果文件`);
    console.log('下载结果:', record);
};

// 重新导入
const handleRetryImport = (record) => {
    message.info(`正在重新导入批次 ${record.taskId}`);
    console.log('重新导入:', record);
};

// 关闭导出记录弹框
const handleExportRecordClose = () => {
    console.log('导出记录弹框已关闭');
};

// 查看导出详情
const handleViewExportDetails = (record) => {
    message.info(`查看导出批次 ${record.taskId} 的详情`);
    console.log('查看导出详情:', record);
};

// 下载导出结果
const handleDownloadExportResult = (record) => {
    message.success(`正在下载导出批次 ${record.taskId} 的结果文件`);
    // 调用实际的下载API
    apis.downloadExportResult(record.taskId).then(() => {
        message.success('文件下载成功');
    }).catch(() => {
        message.error('文件下载失败');
    });
};

// 重新导出
const handleRetryExport = (record) => {
    message.info(`正在重新导出批次 ${record.taskId}`);
    // 调用重新导出的API
    apis.retryExport(record.taskId).then(() => {
        message.success('重新导出任务已提交');
    }).catch(() => {
        message.error('重新导出失败');
    });
};

// 选择区域后
// 如果你用 <script setup>
const onAreaChange = (value, selectedOptions) => {
    areaCodes.value = value;
  console.log('value:', value);
  console.log('selectedOptions:', selectedOptions); // ← 这就是你想要的节点对象数组
};
</script>

<style lang="less" scoped>
// 标题和横线样式
.title-container {
    margin-bottom: 16px;
}

.title-line {
    height: 1px;
    width: 100%;
    background-color: #e8e8e8; // 灰色横线
    margin-top: 8px;
}
</style>