<template>
  <div class="flex doc">
    <div class="doc-nav">
      <div class="my-4 ml-4">
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          添加文书
        </a-button>
      </div>
      <List
        type="attachment"
        :data="listData"
        :selected="selected"
        :width="320"
        @itemClick="callItemClick"
        @edit="callEdit"
        @delete="callDelete"
      />
    </div>
    <div class="flex justify-center px-4 pt-4 grow">
      <div class="doc-cnt">
        <div class="my-2 text-right">
          <a-pagination
            v-model:current="page.current"
            :total="page.total"
            :pageSize="page.size"
            :hideOnSinglePage="true"
            @change="handlePageChange"
          />
        </div>
        <iframe
          v-if="fileIds.length && previewUrl"
          :id="fileIds[page.current - 1]"
          class="doc-iframe"
          :src="previewUrl"
        />
        <div class="doc-cnt doc-cnt--empty" v-else>
          <a-empty />
        </div>
      </div>
    </div>
    <FormModal @register="registerModal" @success="callSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { nextTick, onMounted, reactive, ref } from 'vue';
  import List from '/@/components/XTList/src/List.vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { listDictModel, getPreviewUrl } from '/@/api/common';
  import { formatDictValue } from '/@/utils';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';

  import {
    archivesMedicalDocumentsQueryList,
    archivesMedicalDocumentsRemove,
  } from '/@/api/biz/archives/medicalDocumentsApi';
  import FormModal from './FormModal.vue';

  import dayjs from 'dayjs';
  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });
  const bizDictOptions = reactive({
    type: [],
  });
  const { createConfirm, createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();

  onMounted(async () => {
    bizDictOptions.type = await listDictModel({ dictCode: 'md' });
    await getData();
  });
  const listData = ref([]);
  const selected = ref('');
  const fileIds = ref([]);
  const page = reactive({
    size: 1,
    total: 1,
    current: 1,
  });
  const isFirstLoad = ref(true);
  const previewUrl = ref('');
  async function getData() {
    const res = await archivesMedicalDocumentsQueryList(props.info?.id);
    listData.value = res.map(ele => {
      const obj = {
        id: ele.id,
        title: formatDictValue(bizDictOptions.type, ele.type),
        doctor: ele.updatorName,
        endTime: dayjs(ele.updateTime).format('YYYY-MM-DD'),
        attachment: ele.fileCount,
        patientBasicId: ele.patientBasicId,
        fileIds: ele.fileIds,
      };
      return obj;
    });
    if (isFirstLoad.value && listData.value.length) {
      selected.value = listData.value[0]['id'];
      page.total = listData.value[0]['attachment'] || 0;
      fileIds.value = listData.value[0]['fileIds'];
      if (fileIds.value.length) {
        await handlePreview(fileIds.value[0]);
      }
      isFirstLoad.value = false;
    }
  }

  function handleAdd() {
    const data = { patientBasicId: '' };
    data.patientBasicId = props.info?.id;
    openModal(true, {
      isUpdate: false,
      record: data,
    });
  }
  async function handlePageChange(page) {
    await handlePreview(fileIds.value[page - 1]);
  }
  // 预览文件地址
  async function handlePreview(id) {
    console.log('🚀 ~ file: index.vue:128 ~ handlePreview ~ id:', id);
    if (id == undefined) {
      previewUrl.value = '';
      return;
    }
    try {
      const res = await getPreviewUrl(id);
      previewUrl.value = res || '';
      await nextTick();
    } catch (error) {
      previewUrl.value = '';
    }
  }
  // 回调
  async function callItemClick(data) {
    console.log('🚀 ~ file: index.vue:141 ~ callItemClick ~ data:', data);
    selected.value = data.id;
    page.current = 1;
    page.total = data.attachment;
    fileIds.value = data.fileIds;
    await handlePreview(fileIds.value[0]);
  }
  async function callEdit(data) {
    data.patientBasicId = props.info?.id;
    openModal(true, {
      isUpdate: true,
      record: data,
    });
  }
  async function callDelete(data) {
    createConfirm({
      content: '你确定要删除?',
      iconType: 'warning',
      onOk: async () => {
        await archivesMedicalDocumentsRemove([data.id]);
        createMessage.success('删除成功');
        await getData();
        if (listData.value.length) {
          await callItemClick(listData.value[0]);
        } else {
          await handlePreview(undefined);
        }
      },
    });
  }
  async function callSuccess({ isUpdate, values }) {
    console.log('🚀 ~ file: index.vue:166 ~ callSuccess ~ values:', values);
    if (isUpdate) {
      selected.value = values.id;
      page.current = 1;
      page.total = values.fileIds.length;
      fileIds.value = values.fileIds;
      await handlePreview(fileIds.value[0]);
    } else {
      isFirstLoad.value = true;
    }
    await getData();
  }
</script>

<style lang="less" scoped>
  .doc {
    position: relative;
    top: -16px;

    &-nav {
      border-right: 1px solid #f6f8fa;
    }

    &-cnt {
      // flex: auto;
      width: 100%;
    }

    &-iframe {
      min-width: 500px;
      min-height: calc(100vh - 270px);
      width: 100%;
    }
  }
</style>
