<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="area">
                            <AreaCascader v-model:value="searchFormData.currentNode" @change="onAreaChange" />
                        </a-form-item>
                    </a-col>

                    <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="contactPerson">
                            <a-input :placeholder="'请输负责人'" v-model:value="searchFormData.contactPerson"></a-input>
                        </a-form-item>
                    </a-col>

                    <a-col v-bind="colSpan">
                        <a-form-item :label="'等级'" name="level">
                            <a-select v-model:value="searchFormData.level" @change="handleChange">
                                <a-select-option v-for="item in dicsStore.dictOptions.level" :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="wallet">
                            <a-select v-model:value="searchFormData.wallet" @change="handleChange">
                                <a-select-option value="jack">已结单</a-select-option>
                                <a-select-option value="lucy">已作废</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col> -->

                    <a-col v-bind="colSpan">
                        <a-form-item :label="'是否中标'" name="bidStatus">
                            <a-select v-model:value="searchFormData.bidStatus" @change="handleChange">
                                 <a-select-option v-for="item in dicsStore.dictOptions.WinTheBidding" :key="item.dval"
                                    :value="item.dval">
                                     {{ item.introduction }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="gutter" justify="end" style="margin-top: 20px;">
                    <a-col>
                        <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>

        <a-table rowKey="id" :loading="loading" :pagination="true" :columns="columns" :data-source="listData">
            <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-if="'statusType' === column.key">
                    <!--状态-->
                    <a-tag v-if="statusTypeEnum.is('enabled', record.status)" color="processing">
                        {{ statusTypeEnum.getDesc(record.status) }}
                    </a-tag>
                    <!--状态-->
                    <a-tag v-if="statusTypeEnum.is('disabled', record.status)" color="processing">
                        {{ statusTypeEnum.getDesc(record.status) }}
                    </a-tag>
                </template>

                <template v-if="'actions' === column.key">
                    <span class="action-buttons">
                        <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
                        <a-divider type="vertical" />
                        <a-button type="link" size="small" @click="handleDetail(record)">详情</a-button>
                        <a-divider type="vertical" />
                        <a-button type="link" size="small" @click="handleToggleStatus(record)">
                            {{ record.status === 'active' ? '停用' : '启用' }}
                        </a-button>
                        <a-divider type="vertical" />
                        <a-button type="link" size="small" @click="handleDeviceManagement(record)">设备管理</a-button>
                    </span>
                </template>
            </template>
        </a-table>
    </a-card>

    <edit-dialog @ok="onOk" ref="editDialogRef" />
    <!-- 设备管理弹框组件 -->
    <device-management-modal ref="deviceManagementModalRef" />
</template>

<script setup>
import { Modal, message, Divider } 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 DeviceManagementModal from './components/AddEquipments.vue'
import { useI18n } from 'vue-i18n'
import storage from '@/utils/storage'
import AreaCascader from '@/components/AreaCascader/index.vue'
 import { useDicsStore } from '@/store'

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

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

// 定义设备管理弹框的ref引用 - 这是修复错误的关键
const deviceManagementModalRef = ref(null)
// 编辑对话框的ref引用
const editDialogRef = ref(null)

const columns = ref([
    { title: '序号', dataIndex: 'serialNumber', key: 'serialNumber', fixed: true, width: 180 },
    { title: '机构编号', dataIndex: 'orgCode', key: 'orgCode', width: 240 },
    { title: '节点编号', dataIndex: 'nodeCode', key: 'nodeCode', width: 240 },
    { title: '机构名称', dataIndex: 'orgName', key: 'orgName', width: 240 },
    { title: '联系人', dataIndex: 'contactPerson', key: 'contactPerson', width: 240 },
    { title: '联系电话', dataIndex: 'contactPhone', key: 'contactPhone', width: 240 },
    { title: '机构类型', dataIndex: 'orgType', key: 'orgType', width: 240 },
    { title: '机构性质', dataIndex: 'orgNature', key: 'orgNature', width: 240 },
    { title: '状态', dataIndex: 'status', key: 'status', width: 240 },
    { title: '等级', dataIndex: 'level', key: 'level', width: 240 },
    { title: '营业执照注册号', dataIndex: 'businessLicenseNo', key: 'businessLicenseNo', width: 240 },
    { title: '所在区域', dataIndex: 'region', key: 'region', width: 240 },
    { title: '详细地址', dataIndex: 'addressDetail', key: 'addressDetail', width: 240 },
    { title: '操作', dataIndex: 'actions', key: 'actions', width: 320 },
])

const { listData, loading, showLoading, hideLoading, searchFormData, paginationState, resetPagination } =
    usePagination()
const { resetForm } = useForm()
const dicsStore = useDicsStore()

getMenuList()

/**
 * 获取菜单列表
 * @return {Promise<void>}
 */
async function getMenuList() {
    try {
        showLoading()
        const platform = storage.local.getItem('platform')
        const { data, success, total } = await apis.menu
            .getMenuList({
                ...searchFormData.value,
                platform
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === success) {
            data.forEach((item) => {
                item.name = t(item.code) || item.name
            })
            listData.value = data
            paginationState.total = total
        }
    } catch (error) {
        hideLoading()
    }
}

/**
 * 搜索
 */
function handleSearch() {
    resetPagination()
    getMenuList()
}

/**
 * 重置
 */
function handleResetSearch() {
    searchFormData.value = {}
    resetPagination()
    getMenuList()
}

/**
 * 删除
 * @param id
 */
function handleDelete({ id }) {
    Modal.confirm({
        title: t('pages.system.menu.delTip'),
        content: t('button.confirm'),
        okText: t('button.confirm'),
        onOk: () => {
            return new Promise((resolve, reject) => {
                ; (async () => {
                    try {
                        const { success } = await apis.menu.delMenu(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === success) {
                            resolve()
                            message.success(t('component.message.success.delete'))
                            await getMenuList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}

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

/**
 * 处理下载模板
 */
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() {
    // 可以添加选择框变化后的逻辑
}

// 新增操作方法
function handleEdit(record) {
    editDialogRef.value.open({ record, mode: 'edit' })
}

function handleDetail(record) {
    // 查看详情逻辑
    editDialogRef.value.open({ record, mode: 'view' })
}

function handleToggleStatus(record) {
    // 根据当前状态决定操作文本
    const isActivate = record.status !== 'active';
    const actionText = isActivate ? '启用' : '停用';
    const confirmText = isActivate ? '确定要启用该组织吗？' : '确定要停用该组织吗？';
    
    Modal.confirm({
        title: `${actionText}组织`,
        content: confirmText,
        okText: '确定',
        cancelText: '取消',
        okType: isActivate ? 'primary' : 'danger',
        onOk: async () => {
            try {
                // 模拟API调用
                console.log(`${actionText}操作执行`, record);
                
                // 这里应该调用实际的API
                // const { success } = await apis.org.toggleStatus({ id: record.id, status: isActivate ? 'active' : 'inactive' });
                
                // 模拟成功响应
                const success = true;
                
                if (success) {
                    message.success(`${actionText}成功`);
                    // 更新本地数据状态
                    record.status = isActivate ? 'active' : 'inactive';
                    // 刷新列表
                    await getMenuList();
                } else {
                    message.error(`${actionText}失败`);
                }
            } catch (error) {
                message.error(`${actionText}过程中发生错误: ${error.message}`);
            }
        },
        onCancel() {
            console.log('取消操作');
        },
    });
}

// 设备管理按钮点击事件
function handleDeviceManagement(record) {
    // 检查设备管理弹框引用是否存在
    if (deviceManagementModalRef.value) {
        // 调用弹框的open方法，并传递当前组织记录
        deviceManagementModalRef.value.open({ orgRecord: record });
    } else {
        console.error('设备管理弹框组件未正确初始化');
        message.error('设备管理功能加载失败，请刷新页面重试');
    }
}
</script>

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

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

// 操作按钮样式
.action-buttons {
    .ant-btn-link {
        padding: 0 4px;
        height: auto;
        line-height: inherit;
    }
    
    .ant-divider {
        margin: 0 2px;
    }
}
</style>
