<script setup lang="ts">
import OrganizationManagement from '@/components/OrganizationManagement.vue';
import type { OrganizationModel, OrganizationQuery } from '@/model/system.model';

import { organizationMethod, deleteOrganizationMethod } from '@/request/api/system.api';
import { usePagination } from 'alova/client';
import { notification } from 'ant-design-vue';
import PatientBelong from '@/components/PatientBelong.vue';
import { type VxeFormListeners, type VxeFormProps, type VxeGridInstance, type VxeGridListeners, type VxeGridProps, VxeUI } from 'vxe-pc-ui';
const organizationOptions = ref<{ label: string; value: string }[]>([
  { label: 'liuzhi', value: '1' },
  { label: 'alice', value: '2' },
]);
const model = shallowRef<OrganizationQuery>();
const searchFormProps = reactive<VxeFormProps<OrganizationQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {
    name: '',
  },
  items: [
    { field: 'name', title: '组织名称', span: 8, itemRender: { name: 'VxeSelect', props: { options: organizationOptions, optionProps: { value: 'value', label: 'label' } } } },

    {
      span: 16,
      itemRender: {
        name: 'VxeButtonGroup',
        props: {
          align: 'right',
        },
        options: [
          { type: 'submit', content: '查询', status: 'primary' },
          { type: 'reset', content: '清空' },
        ],
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<OrganizationQuery> = {
  submit({ data }) {
    model.value = { ...data };
  },
  reset({ data }) {
    model.value = { ...data };
  },
};

const gridRef = ref<VxeGridInstance<OrganizationModel>>();
const gridOptions = reactive<VxeGridProps<OrganizationModel>>({
  id: 'role-list',
  border: true,
  showOverflow: true,
  height: 'auto',
  autoResize: false,
  syncResize: true,
  scrollY: { enabled: true, gt: 0 },
  toolbarConfig: {
    custom: true,
    zoom: true,
    slots: {
      buttons: 'handle',
      tools: 'toolbar-extra',
    },
  },
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    storage: true,
  },
  columns: [
    { type: 'seq', width: 70, fixed: 'left' },
    { field: 'name', title: '组织名称' },
    { field: 'appId', title: '小程序ID' },
    { field: 'remark', title: '备注' },
    { field: 'insName', title: '机构名称' },
    { field: 'createTime', title: '创建时间' },
    { field: 'createBy', title: '创建者' },
    {
      title: '操作',
      align: 'center',
      width: 200,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '修改', status: 'warning', name: 'editOrganization' },
          { content: '删除', status: 'error', name: 'deleteOrganization' },
          { content: '患者归属设置', status: 'primary', name: 'setPatientBelong' },
        ],
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if (name === 'editOrganization') {
              method = editOrganization;
            } else if (name === 'deleteOrganization') {
              method = deleteOrganization;
            } else if (name === 'setPatientBelong') {
              method = setPatientBelong;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

const { loading, page, pageSize, total, onSuccess, replace, refresh, remove } = usePagination((page, size) => organizationMethod(page, size, model.value), {
  initialData: { data: [], total: 0 },
  initialPage: 1,
  initialPageSize: 100,
  watchingStates: [model],
  immediate: false,
});
onSuccess(({ data: { data } }) => {
  gridRef.value?.loadData(data);
});

onMounted(() => {
  model.value = toRaw(searchFormProps.data);
});

function deleteOrganization(model: OrganizationModel, index: number) {
  const { name } = model;
  VxeUI.modal.confirm({
    title: `删除组织`,
    content: `确认要删除 ${name} 组织吗？`,
    showClose: false,
    onConfirm() {
      deleteOrganizationMethod(model).then(() => {
        notification.success({
          message: `删除组织: ${name}`,
          description: '操作成功',
        });
        refresh(page.value);
      });
    },
  });
}

function editOrganization(model?: OrganizationModel, index?: number) {
  VxeUI.modal.open({
    title: model?.id ? `修改组织` : `新增组织`,
    escClosable: true,
    destroyOnClose: true,
    id: `organization-edit-modal`,
    remember: true,
    storage: true,
    position: {
      top: Math.min(100, window.innerHeight * 0.15),
    },
    width: 800,
    height: 600,
    slots: {
      default() {
        return h(OrganizationManagement, <any>{
          data: model,
          onSubmit(data: OrganizationModel) {
            refresh(page.value);
            VxeUI.modal.close(`organization-edit-modal`);
          },
        });
      },
    },
  });
}

function setPatientBelong(model: OrganizationModel, index: number) {
  VxeUI.modal.open({
    title: `患者归属设置`,
    escClosable: true,
    destroyOnClose: true,
    id: `patient-belong-modal`,
    remember: true,
    storage: true,
    width: 800,
    height: 600,
    slots: {
      default() {
        return h(PatientBelong, <any>{
          data: model,
          onSubmit(data: OrganizationModel) {
            refresh(page.value);
            VxeUI.modal.close(`patient-belong-modal`);
          },
        });
      },
    },
  });
}
</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none">
      <vxe-form v-bind="searchFormProps" v-on="searchFormEmits"></vxe-form>
    </header>
    <main class="flex-auto overflow-hidden">
      <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" :loading="loading">
        <template #handle>
          <vxe-button status="primary" permission-code="system:role:add" @click="editOrganization()">新增</vxe-button>
        </template>
        <template #toolbar-extra>
          <vxe-button style="margin-right: 12px" icon="vxe-icon-repeat" circle @click="refresh(page)"></vxe-button>
        </template>
      </vxe-grid>
    </main>
    <footer class="flex-none">
      <vxe-pager
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :layouts="['Home', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
      />
    </footer>
  </div>
</template>
<style scoped lang="scss">
.page-container {
  padding: 0 24px;
  max-height: var(--page-main-container);
}
</style>
