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

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

import { watch } from 'vue';

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

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

import { useTableGridOptions, useVbenVxeGrid } from '#/adapter';
import { DictionaryApi } from '#/api';
import { SystemItemDelete } from '#/service/apis/System/DictionaryController';

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 SystemItemDelete({ id });
  message.success('数据删除成功');
  reload();
};

const handleEdit = (record: any, isUpdate: boolean) => {
  if (!isUpdate && !props.type) {
    alert({ content: '请先选择字典类型', icon: '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 @success="handelSuccess" />
    <Grid>
      <template #table-title>
        <span class="border-l-primary border-l-8 border-solid pl-2">
          字典项列表
        </span>
      </template>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'dict-detail:add'"
          @click="() => handleEdit({}, false)"
        >
          新增字典项
        </Button>
      </template>
    </Grid>
  </div>
</template>
