<template>
  <div>
    <!-- 表格区域 -->
    <BasicTable 
      @register="registerTable" 
      :rowSelection="rowSelection"
      :title="tableTitle"
    >
      <!-- 表格标题插槽 -->
      <template #tableTitle>
        <div class="table-title-actions">
          <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined">
            添加成员
          </a-button>
          
          <!-- 批量操作下拉菜单 -->
          <a-dropdown v-if="hasSelectedRows" class="batch-actions-dropdown">
            <template #overlay>
              <a-menu>
                <a-menu-item key="delete" @click="batchHandleDelete">
                  <Icon icon="ant-design:delete-outlined" />
                  删除
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>
              批量操作
              <Icon icon="mdi:chevron-down" />
            </a-button>
          </a-dropdown>
        </div>
      </template>
      
      <!-- 操作栏插槽 -->
      <template #action="{ record }">
        <TableAction 
          :actions="getTableAction(record)" 
          :dropDownActions="getDropDownAction(record)" 
        />
      </template>
    </BasicTable>
    
    <!-- 表单模态框 -->
    <BcsHandleOrgModal ref="modalRef" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns } from './BcsHandleOrg.data';
import { list, deleteOne, batchDelete } from './BcsHandleOrg.api';
import BcsHandleOrgModal from './components/BcsHandleOrgModal.vue';

// Props 定义
interface Props {
  eventId?: string;
}

const props = withDefaults(defineProps<Props>(), {
  eventId: '',
});

// 响应式数据
const queryParam = ref<Recordable>({});
const modalRef = ref<InstanceType<typeof BcsHandleOrgModal>>();
const isMounted = ref(false);
const lastEventId = ref<string>('');

// 计算属性
const hasSelectedRows = computed(() => selectedRowKeys.value.length > 0);
const tableTitle = computed(() => '应急组织');

// 表格配置
const { tableContext } = useListPage({
  tableProps: {
    title: tableTitle.value,
    api: list,
    columns,
    canResize: false,
    useSearchForm: false,
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    immediate: false,
    beforeFetch: (params) => {
      if (props.eventId) {
        queryParam.value.eventId = props.eventId;
      }
      return Object.assign(params, queryParam.value);
    },
  },
});

const [
  registerTable, 
  { reload }, 
  { rowSelection, selectedRowKeys }
] = tableContext;

// 生命周期
onMounted(() => {
  isMounted.value = true;
  initializeQueryParams();
  
  if (props.eventId) {
    lastEventId.value = props.eventId;
    nextTick(() => {
      reload();
    });
  }
});

watch(
  () => props.eventId,
  (newEventId, oldEventId) => {
    if (newEventId && newEventId !== oldEventId && newEventId !== lastEventId.value) {
      lastEventId.value = newEventId;
      queryParam.value.eventId = newEventId;
      
      if (isMounted.value) {
        reload();
      }
    }
  },
  { immediate: false }
);

function initializeQueryParams() {
  queryParam.value = {};
  if (props.eventId) {
    queryParam.value.eventId = props.eventId;
  }
}

/**
 * 新增组织成员
 */
function handleAdd() {
  if (!modalRef.value) return;
  
  modalRef.value.disableSubmit = false;
  modalRef.value.add(props.eventId);
}

/**
 * 编辑组织成员
 */
function handleEdit(record: Recordable) {
  if (!modalRef.value) return;
  
  modalRef.value.disableSubmit = false;
  modalRef.value.edit(record);
}

/**
 * 查看组织成员详情
 */
function handleDetail(record: Recordable) {
  if (!modalRef.value) return;
  
  modalRef.value.disableSubmit = true;
  modalRef.value.edit(record);
}

/**
 * 删除组织成员
 */
async function handleDelete(record: Recordable) {
  await deleteOne({ id: record.id }, handleSuccess);
}

/**
 * 批量删除组织成员
 */
async function batchHandleDelete() {
  if (!hasSelectedRows.value) return;
  
  await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
}

/**
 * 操作成功回调
 */
function handleSuccess() {
  selectedRowKeys.value = [];
  reload();
}

/**
 * 获取表格操作项
 */
function getTableAction(record: Recordable) {
  return [
    {
      label: '编辑',
      onClick: () => handleEdit(record),
    },
  ];
}


function getDropDownAction(record: Recordable) {
  return [
    {
      label: '详情',
      onClick: () => handleDetail(record),
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除？',
        confirm: () => handleDelete(record),
      },
    },
  ];
}

defineExpose({
  reload,
});
</script>

<style lang="less" scoped>
.table-title-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .batch-actions-dropdown {
    margin-left: auto;
  }
}

@media (max-width: 768px) {
  .table-title-actions {
    flex-direction: column;
    align-items: flex-start;
    
    .batch-actions-dropdown {
      margin-left: 0;
      margin-top: 8px;
    }
  }
}
</style>