<template>
  <div class="p-2">
    <BasicTable @register="registerTable" :scroll="{ y: '56vh' }" :rowClassName="getRowClassName" size="small">
      <template #tableTitle></template>

      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>

      <template v-slot:bodyCell="{ column, record, index, text }">
        <template v-if="column.dataIndex === 'previewFileMedia'">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <img v-else :src="testOrgInfo.url + text" style="max-height: 50px;max-width: 80px;">
        </template>
        <template v-if="column.dataIndex === 'immediateFileMedia'">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <img v-else :src="testOrgInfo.url + text" style="max-height: 50px;max-width: 80px;">
        </template>
      </template>
    </BasicTable>

    <ConfigServiceDirectiveModal ref="registerModal" :testOrgInfo="testOrgInfo" @success="handleSuccess"></ConfigServiceDirectiveModal>

    <a-modal v-model:visible="showVideoModal" title="视频播放" :footer="null" @cancel="closeVideoModal"
      :bodyStyle="{ padding: '0', maxHeight: '80vh', overflow: 'auto' }">
      <video controls style="width: 100%; max-height: 70vh; display: block; margin: 0 auto;">
        <source :src="videoUrl">
        您的浏览器不支持视频播放。
      </video>
    </a-modal>
  </div>
</template>

<script lang="ts" name="serviceDirective-configServiceDirective" setup>
import { ref, reactive, watch } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns, superQuerySchema } from './ConfigServiceDirective.data';
import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './ConfigServiceDirective.api';
import ConfigServiceDirectiveModal from './components/ConfigServiceDirectiveModal.vue'
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';

const props = defineProps({
  queryParams: {
    type: Object,
    default: () => ({})
  },
  initialDataIds: { // 初始化数据ID
    type: Array,
    default: () => []
  },
  testOrgInfo: {//试验田机构信息
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['select-change']);
const queryParam = reactive<any>({});
const registerModal = ref();
const selectedRowIds = ref<Set<string | number>>(new Set());
const allSelectedItems = ref<Map<string | number, any>>(new Map());

// 行类名函数
const getRowClassName = (record) => {
  return selectedRowIds.value.has(record.id) ? 'selected-row' : '';
};

// 切换选择状态
const toggleSelect = (record) => {
  if (selectedRowIds.value.has(record.id)) {
    selectedRowIds.value.delete(record.id);
    allSelectedItems.value.delete(record.id);
  } else {
    selectedRowIds.value.add(record.id);
    allSelectedItems.value.set(record.id, record);
  }
  updateSelectedItems();
};

// 移除选中项
const removeSelected = (record) => {
  if (props.initialDataIds.includes(record.id)) {
    return;
  }

  selectedRowIds.value.delete(record.id);
  allSelectedItems.value.delete(record.id);
  updateSelectedItems();
};

// 暴露给父组件的方法
const removeSelectedItem = (id: string | number) => {
  selectedRowIds.value.delete(id);
  allSelectedItems.value.delete(id);
  updateSelectedItems();
};

// 更新已选择项并通知父组件
const updateSelectedItems = () => {
  emit('select-change', new Map(allSelectedItems.value));
};

function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}

watch(() => props.queryParams, (newParams) => {
  reload();
}, { deep: true });

// 注册表格
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '服务指令',
    api: list,
    columns,
    size: 'small',
    showTableSetting: false,
    canResize: false,
    useSearchForm: false,
    showIndexColumn: true,
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    beforeFetch: async (params) => {
      Object.assign(params, props.queryParams);
      params.dataSourceCode = import.meta.env.VITE_SYTJGBM;
      params.column = 'createTime'
      params.order = 'desc'
      params.selectedRowIds = Array.from(selectedRowIds.value)
      return params;
    },
  },
  exportConfig: {
    name: "服务指令",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
});

const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;

function handleDetail(record: Recordable) {
  registerModal.value.disableSubmit = true;
  registerModal.value.edit(record);
}

function getTableAction(record) {
  const actions = [
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    }
  ];

  if (selectedRowIds.value.has(record.id)) {
    actions.push({
      label: '移除',
      color: 'error',
      disabled: props.initialDataIds.includes(record.id),
      onClick: () => {
        removeSelected(record);
      }
    });
  } else {
    actions.push({
      label: '选择',
      onClick: () => {
        toggleSelect(record);
      }
    });
  }

  return actions;
}

function getDropDownAction(record) {
  return [];
}

const showVideoModal = ref(false);
const videoUrl = ref('');

const openVideoModal = (url) => {
  videoUrl.value = getFileAccessHttpUrl(url);
  showVideoModal.value = true;
};

const closeVideoModal = () => {
  showVideoModal.value = false;
  videoUrl.value = '';
};

// 子组件中添加以下方法
const updateSelection = (selectedRecords: any[]) => {
  selectedRowIds.value.clear();
  allSelectedItems.value.clear();

  if (selectedRecords && selectedRecords.length > 0) {
    selectedRecords.forEach(record => {
      selectedRowIds.value.add(record.id);
      allSelectedItems.value.set(record.id, record);
    });
  }

  // 更新表格的选中状态
  if (registerTable) {
    registerTable.toggleRowSelection?.(Array.from(selectedRowIds.value), true);
  }
};

// 在子组件的script部分添加
const getAllData = async (queryParams) => {
  try {
    // 设置不分页参数
    const params = {
      ...queryParams,
      pageNo: 1,
      pageSize: -1,
      dataSourceCode: import.meta.env.VITE_SYTJGBM,
      column: 'createTime',
      order: 'desc'
    };

    const res = await list(params);
    return res.records || [];
  } catch (error) {
    console.error("获取全部数据失败:", error);
    return [];
  }
};

// 暴露给父组件的方法
defineExpose({
  removeSelectedItem,
  updateSelection,
  reload,
  getAllData // 新增方法
});

</script>

<style lang="less" scoped>
.jeecg-basic-table-form-container {
  padding: 0;

  .table-page-search-submitButtons {
    display: block;
    margin-bottom: 24px;
    white-space: nowrap;
  }

  .query-group-cust {
    min-width: 100px !important;
  }

  .query-group-split-cust {
    width: 30px;
    display: inline-block;
    text-align: center
  }

  .ant-form-item:not(.ant-form-item-with-help) {
    margin-bottom: 16px;
    height: 32px;
  }

  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
}

audio::-webkit-media-controls-timeline {
  display: none;
}

audio::-webkit-media-controls-current-time-display,
audio::-webkit-media-controls-time-remaining-display {
  display: none;
}

:deep(.ant-table-title) {
  display: none !important;
}

:deep(.selected-row) {
  background-color: #e6f7ff !important;

  &:hover td {
    background-color: #e6f7ff !important;
  }
}
</style>