<script lang="ts" setup>
import type { PropType } from 'vue';

import type { OnActionClickParams, VxeTableGridOptions } from '#/adapter';

import { watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';

import { useTableGridOptions, useVbenVxeGrid } from '#/adapter';
import { DictionaryApi } from '#/api';

import { useColumns, useSearchSchema } from './data.config';
import FormEdit from './edit.vue';

defineOptions({
  name: 'DictionaryItem',
});

const props = defineProps({
  type: {
    type: String as PropType<string>,
    default: '',
  },
});

const [FormEditModal, formEditApi] = useVbenModal({
  connectedComponent: FormEdit,
});

const handelSuccess = () => {
  reload();
};

const handleDelete = async (id: number) => {
  await DictionaryApi.deleteItemDetail(id);
  message.success('数据删除成功');
  reload();
};

const handleEdit = (record: any, isUpdate: boolean) => {
  if (!isUpdate && !props.type) {
    message.warning('请先选择字典类型');
    return;
  }
  formEditApi
    .setData({
      isUpdate,
      baseData: { ...record, dictionaryCode: props.type },
    })
    .open();
};

const handleActionClick = async ({
  code,
  row,
}: OnActionClickParams<DictionaryApi.RecordItem>) => {
  switch (code) {
    case 'append': {
      handleEdit({ parentId: row.id }, false);
      break;
    }
    case 'delete': {
      await handleDelete(row.id);
      break;
    }
    case 'edit': {
      handleEdit({ id: row.id }, true);
      break;
    }
  }
};

const [Grid, { reload }] = useVbenVxeGrid(
  useTableGridOptions({
    formOptions: {
      schema: useSearchSchema(),
    },
    gridOptions: {
      pagerConfig: {
        enabled: false,
      },
      treeConfig: {
        rowField: 'id',
        childrenField: 'children',
      },
      columns: useColumns(handleActionClick),
      proxyConfig: {
        autoLoad: false,
        ajax: {
          query: async (_: any, formValues: any) => {
            const postData = { ...formValues };
            postData.type = props.type;
            return await DictionaryApi.getItemTree({
              ...postData,
            });
          },
        },
      },
    } as VxeTableGridOptions,
  }),
);

watch(
  () => props.type,
  () => {
    reload();
  },
  { deep: true },
);
</script>
<template>
  <div class="h-full">
    <FormEditModal :close-on-click-modal="false" @success="handelSuccess" />
    <Grid>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'dict-detail:add'"
          @click="() => handleEdit({}, false)"
        >
          新增字典项
        </Button>
      </template>
    </Grid>
  </div>
</template>
