<script setup lang="ts">
import Evaluation from '@/components/Evaluation.vue';
import {
  nextStatus,
  evaluateStatus,
} from '@/model/options';

import type { TagModel, TagQuery } from '@/model/system.model';
import type { EvaluateQuery, EvaluationModel } from '@/model/follow.model';
import {
  tagDeleteMethod,
  tagUpdateStatusMethod,
} from '@/request/api/system.api';
import { planMethod, EvaluateMethod } 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';

const { data: tags, loading: tagsLoading } = useRequest(EvaluateMethod, {
  initialData: { total: 0, data: [] },
});
// 获取随访计划
const { data: plans, loading: planLoading } = useRequest(planMethod, {
  initialData: { total: 0, data: [] },
});
const model = shallowRef<EvaluateQuery>();
const searchFormProps = reactive<VxeFormProps<EvaluateQuery>>({
  titleWidth: 110,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    {
      field: 'evaluateProgress',
      title: '评估状态',
      span: 6,
      itemRender: { name: 'VxeSelect', options: evaluateStatus },
    },
    {
      field: 'evaluate.evaluateDeal',
      title: '评估结果',
      span: 6,
      itemRender: { name: 'VxeSelect', options: nextStatus },
    },
    {
      field: 'followupPlanId',
      title: '随访计划',
      span: 4,
      itemRender: {
        name: 'VxeSelect',
        props: {
          placeholder: '随访计划',
          loading: planLoading,
          options: computed(() => plans.value.data),
          optionProps: { value: 'id', label: 'name' },
          clearable: true,
          multiple: false,
          filterable: true,
        },
      },
    },
    { field: 'patientName', title: '患者姓名', span: 6, itemRender: { name: 'VxeInput' } },
    { field: 'evaluateBy', title: '评估人', span: 6, itemRender: { name: 'VxeInput' } },
    { field: 'medicalDoctor', title: '接诊医生', span: 6, itemRender: { name: 'VxeInput' } },
    {
      span: 6,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { type: 'submit', content: '查询', status: 'primary' },
          { type: 'reset', content: '重置' },
        ],
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<TagQuery> = {
  submit({ data }) {
    model.value = { ...data };
  },
  reset({ data }) {
    model.value = { ...data };
  },
};

const gridRef = ref<VxeGridInstance<EvaluationModel>>();
const gridOptions = reactive<VxeGridProps<EvaluationModel>>({
  id: 'tag-list',
  border: true,
  showOverflow: true,
  height: 'auto',
  autoResize: false,
  syncResize: true,
  scrollY: { enabled: true, gt: 0 },
  toolbarConfig: {
    custom: true,
    zoom: true,
  },
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    storage: true,
  },
  columns: [
    { field: 'followupPlanName', title: '随访计划' },
    { field: 'patientName', title: '姓名' },
    { field: 'sex', title: '性别', slots: { default: 'sex' } },
    { field: 'age', title: '年龄' },
    { field: 'medicalTime', title: '就诊时间' },
    { field: 'medicalDoctor', title: '接诊医生' },
    { field: 'phone', title: '手机号码' },
    { field: 'tagNames', title: '标签' },
    { field: 'evaluateProgress', title: '评估状态', slots: { default: 'status' } },
    { field: 'result', title: '评估结果', slots: { default: 'result' } },
    { field: 'evaluateBy', title: '评估人' },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 120,
      showOverflow: false,
      slots: { default: 'btn' },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

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

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

function assessment(row, rowIndex) {
  VxeUI.modal.open({
    title: '随访评估详情',
    escClosable: true,
    destroyOnClose: true,
    id: `assess-modal`,
    remember: true,
    storage: true,
    showClose: true,
    showHeader: true,
    width: 1100,
    height:800,
    slots: {
      default() {
        return h(Evaluation, <any>{
          data: row,
          onSubmit(data: EvaluationModel) {
            refresh(page.value);
            VxeUI.modal.close(`assess-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 #btn="{ row, rowIndex }">
          <div v-if="row.evaluateProgress === '1'">
            <vxe-button @click="assessment(row, rowIndex)">查看</vxe-button>
          </div>
          <div v-else>
            <vxe-button @click="assessment(row, rowIndex)">评估</vxe-button>
          </div>
        </template>
        <template #result="{ row }"
          >{{ row.evaluate ? (row.evaluate?.evaluateDeal === '1' ? '复诊' : '中医调养') : '' }}
        </template>
        <template #sex="{ row }">{{ row.sex === '1' ? '女' : '男' }}</template>
        <template #status="{ row }"
          >{{ row.evaluateProgress === '1' ? '已完成' : '未完成' }}
        </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>
