<template>
  <el-container>
    <el-main>
      <ListTable
        page
        border
        :data="tableData.rows"
        :props="propsWithSelection"
        :row-key="rowKey"
        :example="tableData.example"
        @query="tableData.query()"
      >
        <template v-for="{ code } in propsWithSlot" #[code]="{ row }">
          <slot :name="code" :row />
        </template>
        <template #ui_selection="{ row }">
          <el-checkbox
            :value="selection.get(row[rowKey])"
            @update:model-value="
              (val) => {
                if (val) {
                  selection.set(row[rowKey], row);
                } else {
                  selection.delete(row[rowKey]);
                }
              }
            "
          />
        </template>
      </ListTable>
    </el-main>
    <el-footer>
      <ConfirmCancel @confirm="handleConfirm" @cancel="handleCancel" />
    </el-footer>
  </el-container>
</template>

<script setup lang="ts">
import { ListTable, Element, AsyncHandler, useAsyncEmits, useListTable, useSysDict, ConfirmCancel } from "noob-mengyxu";
import { computed, onMounted, reactive, ref } from "vue";
import { useStore } from "vuex";
import { useI18n } from "vue3-i18n";
import { ListTableProps } from "../../../plugs/element/listTableDialog";
import { PageResponse } from "../../../plugs/http";
const { showMessage } = Element;
const { t } = useI18n();

defineOptions({ inheritAttrs: false });

type Row = Record<string, any>;

const p = defineProps<ListTableProps>();

type Emits = {
  query: [handler: AsyncHandler<PageResponse<Row>>, example: Record<string, any>];
  confirm: [handler: AsyncHandler<void>, rows: Row[]];
  close: [handler: AsyncHandler<void>];
};
const emits = defineEmits<Emits>();
const emitsAsync = useAsyncEmits<Emits>(emits);

const propsWithSelection = computed(() => [
  { code: "ui_selection", slot: true, i18n: "common.select", width: 80 },
  ...p.props,
]);
const propsWithSlot = computed(() => p.props.filter((col) => col.slot));

const store = useStore();

const { sysDict, updateDict } = useSysDict();

const tableData = useListTable({
  query: (example) => emitsAsync("query", example),
  initialPage: p.initialPage,
  initialPageSize: p.initialPageSize,
  initExample: p.initExample,
  disableAutoQuery: true,
});

const selection = reactive(new Map());

const handleConfirm = async () => {
  try {
    await emitsAsync("confirm", Array.from(selection.values()));
    await emitsAsync("close");
  } catch {
    showMessage("error", t("common.errors.submitError"));
  }
};

const handleCancel = async () => {
  await emitsAsync("close");
};

onMounted(async () => {
  if (p.useDicts) {
    await updateDict(p.useDicts);
  }

  await tableData.query();
});
</script>
