<script setup lang="ts">
import Enabled from '@/components/Enabled.vue';
import { planStatus, enabledStatus } from '@/model/options';

import type { PlanModel, PlanQuery } from '@/model/system.model';

// 接口数据
import {
  planDeleteMethod,
  planMethod,
  planUpdateStatusMethod,
  allTagsSearchMethod,
} from '@/request/api/follow.api';
import { usePagination, useRequest } from 'alova/client';
import { notification } from 'ant-design-vue';

import {
  type VxeFormListeners,
  type VxeFormProps,
  type VxeGridInstance,
  type VxeGridListeners,
  type VxeGridProps,
  VxeUI,
} from 'vxe-pc-ui';
import { list2Groups } from '@/tools/data';

const { data: tags, loading: tagsLoading } = useRequest(planMethod, {
  initialData: { total: 0, data: [] },
});
// 获取患者标签
const { data: tagData, loading: tagDataLoading } = useRequest(allTagsSearchMethod, {
  initialData: { total: 0, data: [] },
});

const model = shallowRef<PlanQuery>();
const searchFormProps = reactive<VxeFormProps<PlanQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    {
      field: 'progress',
      title: '计划状态',
      span: 4,
      itemRender: {
        name: 'VxeSelect',
        options: planStatus,
        props: { placeholder: '状态' },
      },
    },
    {
      field: 'name',
      title: '计划名称',
      span: 4,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入计划名称' } },
    },
    {
      field: 'tagIds',
      title: '患者标签',
      span: 4,
      itemRender: {
        name: 'VxeSelect',
        props: {
          placeholder: '患者标签',
          loading: tagDataLoading,
          optionGroups: computed(() =>
            list2Groups(
              tagData.value.data.filter((tag) => !tag.disabled),
              'category',
              (key) => ({ 1: '系统标签', 2: '个人标签' })[key]!
            )
          ),
          optionProps: { value: 'id', label: 'name' },
          optionGroupProps: { options: 'groups' },
          clearable: true,
          multiple: true,
          filterable: true,
        },
      },
    },
    {
      field: 'status',
      title: '启用状态',
      span: 4,
      itemRender: {
        name: 'VxeSelect',
        options: enabledStatus,
        props: { placeholder: '状态' },
      },
    },
    {
      span: 8,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { name: 'submits', type: 'submit', content: '查询', status: 'primary' },
          { name: 'reset', type: 'reset', content: '重置' },
          { name: 'add', content: '新增', status: 'primary' },
        ],
        events: {
          click(slotParams, { name }) {
            if (name === 'add') {
              // 新增
              editPlan();
            }
          },
        },
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<PlanQuery> = {
  // 查询随访计划
  submit({ data }) {
    model.value = { ...data };
  },
  // 重置
  reset({ data }) {
    model.value = { ...data };
  },
};
const gridRef = ref<VxeGridInstance<PlanModel>>();
const gridOptions = reactive<VxeGridProps<PlanModel>>({
  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: 'filter.tagNames', title: '患者标签' },
    { field: 'filter.departments', title: '就诊科室' },
    { field: 'frequency', title: '随访次数' },
    { field: 'institutionName', title: '机构' },
    { field: 'createBy', title: '创建人' },
    { field: 'createTime', title: '创建时间' },
    { field: 'patient', title: '筛选病人', slots: { default: 'patients' } },
    {
      field: 'progress',
      title: '计划状态',
      slots: { default: 'cell' },
    },
    {
      field: 'status',
      title: '启用状态',
      align: 'center',
      minWidth: 90,
      cellRender: {
        name: 'VxeSwitch',
        props: {
          openLabel: '启用',
          openValue: '0',
          closeLabel: '停用',
          closeValue: '1',
        },
        events: {
          change({ row, rowIndex }, { value }) {
            row.status = { '1': '0', '0': '1' }[value as string] as any;
            updatePlanStatus(row, rowIndex, value);
          },
        },
      },
    },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 120,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '编辑', status: 'warning', name: 'editPlan' },
          { content: '删除', status: 'error', name: 'deletePlan' },
        ],
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if (name === 'editPlan') {
              method = editPlan;
            } else if (name === 'deletePlan') {
              method = deletePlan;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

const { loading, page, pageSize, total, onSuccess, replace, refresh, remove } = usePagination(
  (page, size) => planMethod(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 updatePlanStatus(model: PlanModel, index: number, status: PlanModel['status']) {
  const { id, name } = model;
  const label = { '1': '停用', '0': '启用' }[status];
  VxeUI.modal.confirm({
    title: `启用状态`,
    content: `确认要 ${label} ${name} 计划吗？`,
    showClose: false,
    onConfirm() {
      planUpdateStatusMethod({ id, status }).then(() => {
        notification.success({
          message: `${label}计划: ${name}`,
          description: '操作成功',
        });
        model.status = status;
        replace(model, index);
      });
    },
  });
}

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

function editPlan(model?: PlanModel, index?: number) {
  VxeUI.modal.open({
    title: model?.id ? `修改随访计划` : `新增随访计划`,
    height: 800,
    width: 850,
    // position: {
    //   top: Math.min(100, window.innerHeight * 0.1),
    // },
    escClosable: true,
    destroyOnClose: true,
    id: `plan-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(Enabled, <any>{
          data: model,
          onSubmit(data: PlanModel) {
            refresh(page.value);
            VxeUI.modal.close(`plan-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' ? '已结束' : row.progress === '0' ? '未开始' : '' }}
        </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>
