<template>
  <div :class="prefixCls" class="m-5 bg-white">
    <div class="flex flex-nowrap w-full h-full">
      <div class="w-1/4 border-gray-400 border h-full">
        <header class="p-2 flex justify-between items-center h-12">
          <div class="w-1/2"> </div>
          <div class="flex flex-row w-1/2 justify-end">
            <span class="flex align-middle cursor-pointer" @click="handleTreeOpreate('upSerial')">
              <Icon icon="mdi:arrow-up" :size="18" />
              上移
            </span>
            <span
              class="flex align-middle ml-1 cursor-pointer"
              @click="handleTreeOpreate('downSerial')"
            >
              <Icon icon="mdi:arrow-down" :size="18" />
              下移
            </span>
          </div>
        </header>
        <div class="tree">
          <Tree
            v-if="treeData && treeData[0] && treeData[0].children"
            :tree-data="treeData[0].children"
            :replace-fields="replaceFields"
            :show-line="true"
            :default-expand-all="true"
            @select="onSelect"
          />
        </div>
      </div>
      <div class="w-3/4 ml-4 flex flex-col">
        <header class="h-1/12 mt-2 flex justify-between items-center">
          <div class="flex">
            <span class="text-2xl font-bold">{{ detail.name }}</span>
            <span v-show="showUploadBtn" class="flex ml-3">
              <BasicUpload
                :max-size="20"
                :max-number="1"
                @change="handleChange"
                :api="uploadApi"
                :show-preview-number="false"
                :empty-hide-preview="true"
                :accept="['pdf', 'PDF']"
                btn-text="上传PDF"
              />

              <BasicUpload
                :max-size="20"
                :max-number="1"
                @change="handleChange"
                :api="uploadApi"
                :show-preview-number="false"
                :empty-hide-preview="true"
                :accept="['xlsx', 'xls']"
                btn-text="上传excel"
                class="ml-2"
                btn-type="success"
              />
            </span>
          </div>

          <span class="mr-4" v-show="showExcelDownload">
            <AButton v-if="detail.excelData.fid" type="primary" @click="uploadExecl"
              >下载Excel</AButton
            >
          </span>

          <!-- <AButton type="primary" size="small" class="mx-1">下载PDF</AButton> -->
          <!-- <AButton type="primary" size="small" class="mx-1">编辑</AButton> -->

          <!-- <AButton type="primary" class="mx-1 mr-4">下载</AButton> -->
        </header>
        <section class="h-11/12 border-gray-400 border">
          <!-- <PreviewPdf v-show="showPdf" :url="pdfUrl" type="canvas" pdfjs-dist-path="/pdfjs" /> -->
          <!-- <PreviewPdf v-show="showPdf" :url="pdfUrl" /> -->
          <iframe v-if="showPdf" :src="pdfUrl" frameborder="0" width="100%" height="100%"></iframe>
          <div
            v-if="detail.name && !detail.pdfData.fid"
            class="h-full flex justify-center items-center text-2xl"
            >暂未上传可供预览的pdf文件</div
          >
        </section>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, onActivated, ref, watch } from 'vue'
  import { saveSectionFileApi, sectionAllApi, treeDetailApi, treeResfulApi } from '/@/api/sys/tree'
  import { useDesign } from '/@/hooks/web/useDesign'
  import { message, Tree } from 'ant-design-vue'
  import { TreeResultModel } from '/@/api/model/tree'
  import { BasicUpload } from '/@/components/Upload'
  import { uploadApi } from '/@/api/sys/upload'
  import { TreeRow } from '/#/tree'
  import { downloadByUrl } from '/@/utils/file/download'
  // import PreviewPdf from './pdf.vue'
  // import PreviewPdf from '/@/components/Pdf/pdf'
  import { Icon } from '/@/components/Icon'
  interface ATreeRow extends TreeRow {
    showUpload: boolean
  }
  export default defineComponent({
    name: 'Catalog',
    components: { Icon, BasicUpload, Tree },
    setup() {
      const treeData = ref<TreeResultModel[]>([])
      const row = ref<ATreeRow>({
        id: '',
        parentId: '',
        name: '',
        depth: 0,
        serial: 0,
        attribution: '',
        code: '',
        code2: '',
        contractId: '',
        createTime: '',
        showUpload: false
      })
      const detail = ref({
        name: '',
        pdfData: { content: '', filepath: '', filename: '', ext: '', fid: '' },
        excelData: { content: '', filepath: '', filename: '', ext: '', fid: '' }
      })
      async function initData() {
        const result = await sectionAllApi()
        treeData.value = result
      }

      async function initSectionDetail(id: string) {
        const result = await treeDetailApi(id)
        detail.value = result
      }
      initData()

      const handleTreeOpreate = async (operation: 'upSerial' | 'downSerial') => {
        const id = row.value.id
        if (!id) {
          return message.error('请先选中节点')
        }
        await treeResfulApi({ id, type: 'serial', operation })
        await initData()
      }
      onActivated(() => initData())
      const { prefixCls } = useDesign('catalog')
      const replaceFields = { children: 'children', title: 'name', key: 'id' }

      const onSelect = (selectedKeys: Event, { selectedNodes }) => {
        if (selectedKeys && selectedNodes && selectedKeys!.length) {
          const {
            id,
            parentId,
            name,
            depth,
            serial,
            attribution,
            code,
            code2,
            contractId,
            children,
            createTime
          } = selectedNodes[0]?.props
          row.value = {
            showUpload: depth > 2 ? (children && children.length ? false : true) : false,
            id,
            parentId,
            name,
            depth,
            serial,
            attribution,
            code,
            code2,
            contractId,
            createTime
          }
        }
      }

      watch(row, (row, prevRow) => {
        if (row.id !== prevRow.id) {
          initSectionDetail(row.id)
        }
      })

      const handleChange = async (list: string[]) => {
        await saveSectionFileApi({ id: row.value.id, contractId: list[0] })
        await initSectionDetail(row.value.id)
      }

      const showUploadBtn = computed(() => row.value.showUpload)
      const showExcelDownload = computed(() => detail.value.excelData.fid)
      const showPdf = computed(() => {
        if (!detail.value.pdfData.fid) {
          return false
        }
        return true
      })
      const uploadExecl = () => {
        downloadByUrl({
          url: 'http://sj.6jlzf.cn/api/upload/file?id=' + detail.value.excelData.fid
          // url: 'http://localhost:7070/api/upload/file?id=' + detail.value.excelData.fid
        })
      }

      const pdfUrl = computed(
        // () => 'http://sj.6jlzf.cn/api/upload/file?id=' + detail.value.pdfData.fid
        () => 'http://sj.6jlzf.cn/static' + detail.value.pdfData.filepath
      )
      return {
        treeData,
        replaceFields,
        prefixCls,
        onSelect,
        handleTreeOpreate,
        detail,
        uploadApi,
        handleChange,
        row,
        showUploadBtn,
        showExcelDownload,
        uploadExecl,
        pdfUrl,
        showPdf
      }
    }
  })
</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-catalog';

  .@{prefix-cls} {
    width: calc(100% - 2.5rem);
    height: calc(100% - 2.5rem);
    overflow: hidden;
    .tree {
      height: calc(100% - 48px);
      max-height: 809px;
      overflow-x: scroll;
      overflow-y: scroll;
    }
  }
</style>
