<script lang="ts" setup>
// 科室字典管理（yii_department，老库表不迁库，管理入口收敛到新后台）
// 树形展示一级/二级科室，支持新增、编辑、添加子科室、删除（后端校验医生绑定）
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { ref } from 'vue';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';

import { deleteDepartment } from './api';
import FormModalDemo from './components/modal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

defineOptions({ name: 'SystemDepartment' });

const hasTopTableDropDownActions = ref(false);

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: FormModalDemo,
});

/**
 * 打开新增/编辑弹窗
 * 「添加子科室」复用新增弹窗：只预填 pid，其余字段留空
 */
const showModal = (data: Record<string, any> = {}, isUpdate = false) => {
  formModalApi.setData({
    values: data,
    update: isUpdate,
    gridApi,
  });
  formModalApi.open();
};

/**
 * 删除科室（单个或勾选批量）
 * 物理删除，后端会拦截「有子科室 / 有医生绑定」的情况
 */
const deleteApi = (row: any) => {
  let ids = [];
  if (row) {
    ids.push(row.id);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  deleteDepartment({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};
</script>

<template>
  <Page auto-content-height title="科室管理">
    <FormModal />
    <Grid>
      <template #toolbar-actions>
        <TableAction
          :actions="[
            {
              label: '新增科室',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              onClick: showModal.bind(null, {}, false),
            },
          ]"
          :drop-down-actions="[
            {
              label: '批量删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              popConfirm: {
                title: '确定删除选中的科室吗？',
                confirm: deleteApi.bind(null, false),
              },
            },
          ]"
        />
      </template>
      <template #level="{ row }">
        <Tag :color="row.level === 1 ? 'blue' : 'cyan'">
          {{ row.level === 1 ? '一级科室' : '二级科室' }}
        </Tag>
      </template>
      <template #feature="{ row }">
        <Tag :color="row.feature === 1 ? 'gold' : 'default'">
          {{ row.feature === 1 ? '特色专科' : '普通' }}
        </Tag>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              onClick: showModal.bind(null, row, true),
            },
            {
              label: '添加子科室',
              type: 'link',
              icon: 'ant-design:apartment-outlined',
              size: 'small',
              ifShow: row.level === 1,
              onClick: showModal.bind(null, { pid: row.id }, false),
            },
          ]"
          :drop-down-actions="[
            {
              label: '删除',
              type: 'link',
              icon: 'ant-design:delete-outlined',
              size: 'small',
              popConfirm: {
                title: '确定删除该科室吗？',
                confirm: deleteApi.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
