<template>
  <div>
    <BasicTable @register="registerTable" />
  </div>
</template>

<script setup lang="ts">
  import { columnsEdit } from '../data';
  import { BasicTable, useTable } from '/@/components/Table';
  import { genConfigList, genConfigEditBatch } from '/@/api/infra/genApi';
  import { ref, nextTick } from 'vue';
  const [registerTable, { getDataSource, reload }] = useTable({
    api: genConfigList,
    rowKey: 'id',
    columns: columnsEdit,
    showIndexColumn: true,
    pagination: false,
    indexColumnProps: {
      fixed: 'left',
    },
    bordered: true,
    beforeFetch: handleBeforeFetch,
    afterFetch: handleAfterFetch,
  });

  const recordData = ref();
  const tableData = ref();

  const onOpen = record => {
    recordData.value = record;
    nextTick(async () => {
      await reload();
    });
  };

  function handleBeforeFetch(params) {
    return { ...params, basicId: recordData.value.id };
  }

  function handleAfterFetch(data) {
    tableData.value = data;
    tableData.value.forEach(item => {
      for (const key in item) {
        if (item[key] === 'Y') {
          item[key] = true;
        }
        if (item[key] === 'N') {
          item[key] = false;
        }
      }
      // 让默认的变成设置的
      // fieldJavaTypeChange(item);
    });
    tableData.value = tableData.value.filter(item => {
      return item.isTableKey == 'false' || item.isTableKey == false || item.isTableKey == 'N';
    });
    return tableData.value;
  }

  async function onSubmit() {
    console.log('生成', getDataSource());
    const sourceData = getDataSource();
    console.log('tableData.value', tableData.value);
    const submitData = sourceData.map(ele => {
      delete ele.cancelCbs;
      delete ele.editValueRefs;
      delete ele.onCancelEdit;
      delete ele.onEdit;
      delete ele.onSubmitEdit;
      delete ele.onValid;
      delete ele.submitCbs;
      delete ele.validCbs;
      ele.whetherAddUpdate = ele.whetherAddUpdate ? 'Y' : 'N';
      ele.whetherRequired = ele.whetherRequired ? 'Y' : 'N';
      ele.whetherRetract = ele.whetherRetract ? 'Y' : 'N';
      ele.whetherTable = ele.whetherTable ? 'Y' : 'N';
      ele.queryWhether = ele.queryWhether ? 'Y' : 'N';
      return ele;
    });
    console.log('🚀 ~ file: config.vue:80 ~ onSubmit ~ tableData:', submitData);
    const res = await genConfigEditBatch(submitData);
    console.log('🚀 ~ file: EditModal.vue ~ line 80 ~ genSubmit ~ res', res);
  }
  // 抛出钩子
  defineExpose({
    onOpen,
    onSubmit,
  });
</script>

<style lang="less" scoped></style>
