<script setup lang="ts">
import EditInstitution from '@/service/EditSystemService.vue';
import ServicePackageDetail from '@/service/ServicePackageDetail.vue';
import type { SystemCwModel, SystemCwQuery } from '@/model/care.model';
// 接口数据
import { pageOrgCwMethod, deleteOrgCwMethod } from '@/request/api/care.api';
import { usePagination, useRequest } from 'alova/client';
import { notification } from 'ant-design-vue';
import { branchMethod } from '@/request/api/system.api';

import { type VxeFormListeners, type VxeFormProps, type VxeCardInstance, type VxeCardListeners, type VxeCardProps, VxeUI } from 'vxe-pc-ui';
const { data: branch, loading: branchLoading } = useRequest(branchMethod);
const model = shallowRef<SystemCwQuery>();
const searchFormProps = reactive<VxeFormProps<SystemCwQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    {
      field: 'name',
      title: '服务包名称',
      span: 5,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'diagnoseDiseaseName',
      title: '专病',
      span: 5,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'diagnoseSyndromeName',
      title: '证型',
      span: 5,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'constitutionGroupName',
      title: '体质',
      span: 5,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      span: 4,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { name: 'submits', type: 'submit', content: '查询', status: 'primary' },
          { name: 'reset', type: 'reset', content: '清空', status: 'warning' },
          { name: 'add', content: '新增', status: 'primary' },
        ],
        events: {
          click(slotParams, { name }) {
            if (name === 'add') {
              // 新增
              editInstitution();
            }
          },
        },
      },
    },
    {
      field: 'institutionId',
      title: '机构名称',
      span: 8,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          loading: computed(() => branchLoading.value),
          options: computed(() => branch.value),
          optionProps: { value: 'id' },
        },
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<SystemCwQuery> = {
  // 查询随访计划
  submit({ data }) {
    model.value = { ...data };
  },
  // 重置
  reset({ data }) {
    model.value = { ...data };
  },
};
const gridRef = ref<VxeGridInstance<SystemCwModel>>();
const gridOptions = reactive<VxeGridProps<SystemCwModel>>({
  id: 'tag-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: 'conditioningWrapPatientMatchRule.diagnoseDiseaseNames', title: '专病' },
    { field: 'conditioningWrapPatientMatchRule.diagnoseSyndromeNames', title: '证型' },
    { field: 'conditioningWrapPatientMatchRule.constitutionGroupNames', title: '体质' },
    { field: 'institutionName', title: '机构名称' },
    { field: 'createBy', title: '创建者' },
    { field: 'createTime', title: '创建时间' },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 150,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '详情', status: 'primary', name: 'seeInstitutionDetail' },
          { content: '编辑', status: 'primary', name: 'editInstitution' },
          { content: '删除', status: 'primary', name: 'deleteInstitution' },
        ],
        events: {
          click({ row, rowIndex }: any, { name }: any) {
            let method;
            if (name === 'editInstitution') {
              method = editInstitution;
            } else if (name === 'deleteInstitution') {
              method = deleteInstitution;
            } else if (name === 'seeInstitutionDetail') {
              method = seeInstitutionDetail;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

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

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

function seeInstitutionDetail(model: SystemCwModel, index: number) {
  const types = 'institution';
  VxeUI.modal.open({
    title: `机构服务包详情`,
    // height: 700,
    // width: 1000,
    height: '100vh',
    width: '100vw',
    fullscreen: true,
    escClosable: true,
    destroyOnClose: true,
    id: `servicePackageDetail-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(ServicePackageDetail, <any>{
          data: { ...model, types },
          onSubmit(data: SystemCwModel) {
            refresh(page.value);
            VxeUI.modal.close(`servicePackageDetail-modal`);
          },
        });
      },
    },
  });
}

function deleteInstitution(model: SystemCwModel, index: number) {
  const { name } = model;
  VxeUI.modal.confirm({
    title: `删除机构服务`,
    content: `确认要删除 ${name} 机构服务吗？`,
    showClose: false,
    onConfirm() {
      deleteOrgCwMethod(model).then(() => {
        notification.success({
          message: `删除机构服务: ${name}`,
          description: '操作成功',
        });
        refresh(page.value);
      });
    },
  });
}

function editInstitution(model?: SystemCwModel, index?: number) {
  const types = 'institution';
  VxeUI.modal.open({
    title: model?.id ? `修改机构服务` : `新增机构服务`,
    height: window.innerHeight,
    width: window.innerWidth,
    fullscreen: true,
    escClosable: true,
    destroyOnClose: true,
    id: `edit-system-service-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(EditInstitution, <any>{
          data: { ...model, types },
          onSubmit(data: SystemCwModel) {
            refresh(page.value);
            VxeUI.modal.close(`edit-system-service-modal`);
          },
        });
      },
    },
  });
}
</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none mt-4">
      <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 #cell="{ row }">{{ row.progress === 1 ? '已开始' : row.progress === 2 ? '已结束' : '未开始' }} </template>
        <template #patients="{ row }">
          <div :class="row.isFilter === 'Y' ? '' : 'text-red'">
            {{ row.isFilter === 'Y' ? '已筛选' : '未筛选' }}
          </div>
        </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>
