<template>
  <div class="p-2">
    <BasicTable ref="tableRef" @register="registerTable" :scroll="{ y: '56vh' }" :rowSelection="rowSelection" :rowClassName="getRowClassName"  @selection-change="handleSelectionChange" size="small">
      <template #tableTitle></template>
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" name="tq-electricity-sourceTable" setup>
import { ref, reactive, watch,computed } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { selectedSourceColumns,unselectedSourceColumns } from '../electricity.data';
import { sourceListApi } from '../electricity.api';

const props = defineProps({
  queryParams: {
    type: Object,
    default: () => ({})
  },
});

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

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

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

const tableColumns = computed(() => {
  return props.queryParams.viewType === 'selected' ? selectedSourceColumns : unselectedSourceColumns;
});

// 注册表格
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '设备源表',
    api: sourceListApi,
    columns:tableColumns,
    size: 'small',
    showTableSetting: false,
    canResize: false,
    useSearchForm: false,
    showIndexColumn: true,
    rowSelection: {type:'checkbox'},
    rowKey: 'id',
    actionColumn: {
      width: 100,
      fixed: 'right',
    },
    beforeFetch: async (params) => {
      Object.assign(params, props.queryParams);
      params.column = 'createTime'
      params.order = 'desc'
      params.selectedRowIds = Array.from(selectedRowIds.value)
      return params;
    },
  },
});

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

function getTableAction(record) {
  const actions = [];
  if (selectedRowIds.value.has(record.address)) {
    actions.push({
      label: '取消',
      color: 'error',
      onClick: () => {
        removeSelected(record);
      }
    });
  } else {
    let label = '添加';
    if(record.nuId){
      label = '变更';
    }
    actions.push({
      label: label,
      onClick: () => {
        toggleSelect(record);
      }
    });
  }
  return actions;
}

function handleSelectionChange(selectedRowSet) {
  // console.log('当前选中数据:', selectedRowSet);
  allSelectedRows.value = selectedRowSet.rows;
  selectedRowKeys.value = selectedRowSet.keys;
}

// 取消所有选中项
function clearSelected(){
  // console.log('取消选择数据');
  selectedRowKeys.value = [];
  allSelectedRows.value = [];
}

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

// 切换选择状态
const toggleSelect = (record) => {
  if (!selectedRowIds.value.has(record.address)) {
    selectedRowIds.value.add(record.address);
  }
  allSelectedRows.value = [];
  allSelectedRows.value.push(record);
  emit('addSelect');
};

// 移除选中项
const removeSelected = (record) => {
  selectedRowIds.value.delete(record.address);
  emit('removeSelect',record);
};

const updateSelection = (selectedRecords) => {
  selectedRowIds.value.clear();
  selectedRecords.forEach((value, key) => {
    selectedRowIds.value.add(key);
  });
  // 更新表格的选中状态
  if (registerTable) {
    registerTable.toggleRowSelection?.(Array.from(selectedRowIds.value), true);
  }
};

function reloadData(){
  reload();
}


// 暴露给父组件的方法
defineExpose({
  updateSelection,
  clearSelected,
  reloadData,
  allSelectedRows,
});

</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>
