<script setup lang="ts">
import type { PatientTagModel }                       from '@/model';
import { updatePatientTagsMethod }                    from '@/request/api/patient.api';
import { tagsSearchMethod }                           from '@/request/api/system.api';
import { CheckOutlined, CloseOutlined, EditOutlined } from '@ant-design/icons-vue';
import { useRequest }                                 from 'alova/client';
import { message as Message }                         from 'ant-design-vue';
import { h }                                          from 'vue';


const props = defineProps<{
  dataset: PatientTagModel;
  loading?: boolean;
  data?: any;
  editable?: boolean;
}>();

const emits = defineEmits<{
  refresh: [];
}>();
const { data: options, loading: optionsLoading, send: loadOptions } = useRequest(
  tagsSearchMethod,
  { initialData: { total: 0, data: [] }, immediate: false },
);
const { send: save, loading: submitting } = useRequest(
  () => updatePatientTagsMethod(props.dataset.id || props.data.patientId, selected.value),
  { immediate: false },
).onSuccess(() => {
  editing.value = false;
  emits('refresh');
  Message.success(`标签更新成功`);
});

const editing = ref(false);
const selected = ref<string[]>([]);

const selectRef = ref<HTMLSelectElement | null>(null);
const onSelectVisibleChange = (visible: boolean) => {
  if ( editing.value && !visible ) {
    setTimeout(() => editing.value = submitting.value, 300);
  }
};

async function edit(value = !editing.value) {
  if ( value && !options.value.total ) await loadOptions();
  if ( value ) {
    selected.value = props.dataset.tags?.map(item => item.id);
    setTimeout(() => { selectRef.value?.focus(); }, 20);
  }
  editing.value = value;
}
</script>
<template>
  <div class="card flex flex-col">
    <div class="card__header flex justify-between items-center">
      <div class="card__title">
        <span>标签</span>
        <a-spin v-if="props.loading" size="small" style="margin-left: 4px;" />
        <a-space style="margin-left: 8px">
          <a-tooltip v-if="props.editable" :title="editing ? '取消' : '编辑'">
            <a-button
              shape="circle" size="small" :icon="editing ? h(CloseOutlined) : h(EditOutlined)"
              @click="edit()"
            />
          </a-tooltip>
        </a-space>
      </div>
    </div>
    <div class="card__content overflow-auto">
      <a-space-compact v-if="editing" block size="small" class="tags-edit-select-wrapper">
        <a-select
          ref="selectRef" autofocus
          v-model:value="selected" mode="multiple"
          :options="options.data" :field-names="{ label: 'name', value: 'id'}"
          :disabled="submitting" :loading="optionsLoading"
          :open="!optionsLoading" @dropdownVisibleChange="onSelectVisibleChange"
        />
        <a-tooltip title="保存">
          <a-button type="primary" :icon="h(CheckOutlined)" :loading="submitting" @click="save()"></a-button>
        </a-tooltip>
      </a-space-compact>
      <a-space v-else wrap>
        <a-tag v-for="item in props.dataset.tags" :key="item.id" :closable="editing">{{ item.name }}</a-tag>
      </a-space>
    </div>
  </div>
</template>
<style scoped lang="scss">
@import "@/themes/report-card";

.ant-tag {
  margin-right: 0;
}

.tags-edit-select-wrapper {
  .ant-select {
    width: calc(100% - 24px);
    max-height: 48px;

    :deep(.ant-select-selector) {
      max-height: inherit;
      overflow-y: auto;
    }
  }

  button {
    height: inherit !important;
  }
}
</style>
