<script setup lang="ts">
import ReportSchemeEdit                                  from '@/components/ReportSchemeEdit.vue';
import ReportSchemePreview                               from '@/components/ReportSchemePreview.vue';
import type { ReportSchemeItemModel, ReportSchemeModel } from '@/model';
import { deleteSchemeMethod }                            from '@/request/api/report.api';
import { withResolvers }                                 from '@/tools/promise';

import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';

import { useRequest }                                          from 'alova/client';
import { Button, Modal, notification as Notification, Result } from 'ant-design-vue';
import { h }                                                   from 'vue';
import { VxeUI }                                               from 'vxe-pc-ui';


const props = withDefaults(defineProps<{
  dataset: ReportSchemeModel;
  loading?: boolean;
  title?: string;

  editable?: boolean;
  hideTitle?: boolean;
}>(), {
  title: '调理方案',
  hideTitle: false,
});
const emits = defineEmits<{
  refresh: [ id?: string ];
}>();

const { send: deleteScheme } = useRequest(
  (item) => deleteSchemeMethod(props.dataset.id, item),
  { immediate: false },
).onSuccess(() => {
  Notification.success({
    message: '删除调理方案成功',
  });
  emits('refresh');
});


function deleteSchemeItemHandle(item: ReportSchemeItemModel, index?: number) {
  const { promise, resolve } = withResolvers();
  Modal.confirm({
    icon: h(ExclamationCircleOutlined),
    title: `是否删除调理方案？`,
    content: [ item.category, item.name ].filter(Boolean).join(': '),
    okType: 'danger',
    okText: '删除',
    zIndex: 9999,
    onOk: () => deleteScheme(item).then(resolve),
  });
  return promise;
}

const openMode = ref<'edit' | 'preview'>();
const openModel = shallowRef<ReportSchemeItemModel>();


function openSchemeHandle(mode: 'edit' | 'preview', item?: ReportSchemeItemModel, index?: number) {
  openMode.value = mode;
  openModel.value = item;
  const id = `drawer:scheme:edit`;
  const onDestroy = () => { VxeUI.drawer.close(id); };
  VxeUI.drawer.open({
    id,
    maskClosable: openMode.value === 'preview',
    escClosable: true,
    padding: false,
    slots: {
      title() {
        switch ( openMode.value ) {
          case 'preview':
            return h('div', {}, [ openModel.value?.category, openModel.value?.name ].filter(Boolean).join(' '));
          case 'edit':
            return h('div', {}, openModel.value?.id ? `编辑调理方案` : `添加调理方案`);
          default:
            return '';
        }
      },
      default() {
        switch ( openMode.value ) {
          case 'edit':
            return h(ReportSchemeEdit, {
              reportId: props.dataset.id,
              value: openModel.value,
              'onUpdate:value'(model) {
                openModel.value = model;
                openMode.value = 'preview';
                emits('refresh', model.id);
              },
              onDestroy,
            });
          case 'preview':
            return h(ReportSchemePreview, {
              value: openModel.value,
              onDestroy,
            });
          default:
            return h(Result, { status: '404' });
        }
      },
      corner() {
        return props.editable && openModel.value?.id && h('div', { class: `space-container` }, [
          h(
            Button,
            {
              size: 'small', type: 'dashed', danger: true,
              onClick: () => deleteSchemeItemHandle(item!, index).then(() => onDestroy()),
            },
            () => '删除',
          ),
          openMode.value !== 'edit' && h(
            Button,
            {
              size: 'small', type: 'default',
              onClick: () => openMode.value = 'edit',
            },
            () => '编辑',
          ),
          openMode.value !== 'preview' && h(
            Button,
            {
              size: 'small', type: 'default',
              onClick: () => openMode.value = 'preview',
            },
            () => '查看',
          ),
        ]) as any;
      },
    },
  });
}

const showDescriptions = (panel: ReportSchemeItemModel) => {
  return panel.descriptions?.length || (
    panel.type !== 'other' &&
    panel.content?.length
  );
};
</script>
<template>
  <div class="card report-card">
    <div v-if="!props.hideTitle" class="card__header sticky flex justify-between items-center">
      <div class="card__title">
        <span>{{ props.title }}</span>
        <a-spin v-if="props.loading" size="small" style="margin-left: 4px;" />
        <a-space style="margin-left: 8px;">
          <a-tooltip title="添加调理方案" v-if="props.editable">
            <a-button
              type="primary" shape="circle" size="small" :icon="h(PlusOutlined)"
              @click="openSchemeHandle('edit')"
            />
          </a-tooltip>
        </a-space>
      </div>
    </div>
    <div class="card__content flex-auto">
      <template v-for="(panel, index) in props.dataset.children" :key="panel.id">
        <div :id="'scrollable_scheme_' + panel.id" style="position: relative;top:-48px;"></div>
        <a-card class="card background descriptions-card" size="small">
          <template #title>
            <div @click="openSchemeHandle('preview', panel,index)">
              <span class="header">{{ panel.category }}</span>
              <span class="header" v-if="panel.name">{{ panel.name }}</span>
            </div>
          </template>
          <template #extra v-if="editable">
            <a-space>
              <a-button size="small" @click.stop="openSchemeHandle('edit',panel, index)">编辑</a-button>
              <a-button size="small" danger @click.stop="deleteSchemeItemHandle(panel, index)">删除</a-button>
            </a-space>
          </template>
          <a-descriptions :column="1" bordered size="small" v-if="showDescriptions(panel)">
            <a-descriptions-item v-if="panel.type === 'acupoint'" label="穴位">
              <template v-for="(item,index) in panel.content" :key="index">
                <a-tag>{{ item.name }}</a-tag>
              </template>
            </a-descriptions-item>
            <a-descriptions-item v-if="panel.type === 'medicine'" label="组成">
              <template v-for="(item,index) in panel.content" :key="index">
                <a-tag>{{ item.name }} {{ item.doase }}{{ item.unit }}</a-tag>
              </template>
            </a-descriptions-item>
            <a-descriptions-item v-for="row in panel.descriptions" :key="row.name" :label="row.name ">
              {{ row.description }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
      </template>
    </div>
    <div class="cart__footer flex-none sticky bottom-0">
      <slot name="footer"></slot>
    </div>
  </div>
</template>
<style scoped lang="scss">
@import "@/themes/report-card";

.report-card {
  min-height: var(--page-main-container);

  :deep(.ant-descriptions-item-label) {
    text-align: center;
  }
}

.card__content {
  > .card {
    transition: all 200ms ease;

    &:not(:last-of-type) {
      margin-bottom: 12px;
    }
  }

  .header {
    user-select: none;
    cursor: pointer;

    &:nth-of-type(2) {
      color: #4284fe;
      margin-left: 4px;
    }

    &:first-of-type {
      color: #333;
    }
  }
}

.descriptions-card {
  :deep(.ant-descriptions-item-label) {
    padding: 8px 12px;
    width: 120px;
    text-align: center;
  }

  :deep(.ant-descriptions-item-content) {
    background-color: #fff;
  }
}
</style>
