<script setup lang="ts">
import DataBaseHead from '@/views/home/components/DataBaseHead.vue'
import {
  cateAdd,
  cateUpdate,
  treeDbList,
  cateInfo,
  cateDel,
  cateFileUpdate,
  cateFileDel,
  cateFileList,
  download,
  fetchdbAuthGetInfo
} from '@/api/daikin/base'
import { useUserStore } from '@/stores/modules/user'
import { useMessage, NModal, NPopover } from 'naive-ui'
import { isNotOneWeekAgo } from '@/utils'
// console.log('🚀 ~ isNotOneWeekAgo:', isNotOneWeekAgo('2024-1-16'))

const store: any = useUserStore()
const message = useMessage()
const userCode = ['admin', 'database_dandang'].some((item) => store.user.roleCode?.includes(item))
const isDbReview = store.user?.isDbReview === 1
const isDbUpload = store.user?.isDbUpload === 1
const user: any = store.user

const { push } = useRouter()
const title = ref('大金集团经营理念')

const prop = defineProps({
  cateId: Number,
  title: String
})
const pageInfo = reactive({
  currentPage: 1,
  pageSize: 13,
  total: 10
})
watchEffect(() => {
  prop.cateId
  prop.title
  title.value = prop.title
  getTree()
  // getAuth()
})
const tableData = ref()
async function getTree() {
  const { currentPage, pageSize } = pageInfo
  if (!prop.cateId) return
  const { rows, total } = await cateFileList({
    cateId: prop.cateId,
    pageNum: currentPage,
    pageSize
  })
  pageInfo.total = total
  tableData.value = rows
}
// async function downloads(row) {
//   console.log(row)
//   const {isSelect} = row
//   if(isSelect === 2) {
//     message.info("没有访问权限")
//     return
//   }
//   try {
//         const response = await download({ id: row.id })
//         console.log(response)
//          var blob = new Blob([response.data]);

//         const downloadUrl = URL.createObjectURL(blob);
//         const link = document.createElement('a');
//         link.href = downloadUrl;
//         link.download = row.title; // 替换为你要保存的文件名
//         link.click();
//         URL.revokeObjectURL(downloadUrl);
//     } catch (error) {
//         message.error(error)
//         // message.error('下载文件出错：', error);
//     }
// }
const arr = [1706, 1416, 1415, 1414, 1413, 1412, 1411, 1410, 1386, 1388, 1391]

async function downloads(row: any) {
  // console.log('xiazai', row)
  const { isSelect, filePath, id, fileCommon } = row
  if (isSelect === 2) {
    message.info('没有访问权限')
    return
  }
  if (arr.includes(id) || (fileCommon?.fileSize || 0) > 25 * 1024 * 1024) {
    try {
      message.info('正在下载中，请稍等～')
      downloadFile(filePath)
    } catch (error) {}
  }
  // window.open(
  // 	'https://view.officeapps.live.com/op/view.aspx?src=' +
  // 		encodeURIComponent(filePath)
  // )
  filePath && window.open(filePath)
}
const lazyState = computed(() => [pageInfo.currentPage])
watch(
  () => unref(lazyState),
  async (v) => {
    getTree()
  },
  { immediate: true, deep: true }
)

const handleSizeChange = (e) => {
  console.log(e)
}

const handleCurrentChange = (e) => {
  console.log(e)
}
// 预览
const srcType = ref()
const src = ref()
const pdfShow = ref(false)
const showModalRef2 = ref(false)
const openUrl = async (it) => {
  console.log(it, 2222)
  let { filePath, isSelect } = it
  if (isSelect === 2) {
    message.info('没有访问权限')
    return
  }
  if (!filePath) {
    message.info('没有可预览文件！')
    return
  }
  srcType.value = getLastSubstring(filePath)
  if (['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'pdf'].includes(srcType.value)) {
    // src.value = filePath
    // pdfShow.value = true
    filePath = 'https://view.xdocin.com/view?src=' + filePath
    const screenWidth = window.screen.width
    const screenHeight = window.screen.height
    window.open(
      filePath,
      '',
      'width=' + screenWidth + ',height=' + screenHeight + ',top=' + 0 + ',left=' + 0
    )
  } else {
    message.error("文件格式不是 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx','pdf'！")
  }
}
function getLastSubstring(str: string): string {
  const lastIndex = str.lastIndexOf('.')
  if (lastIndex !== -1) {
    return str.substring(lastIndex + 1)
  } else {
    return ''
  }
}
function downloadFile(url: any) {
  fetch(url)
    .then((response) => response.blob())
    .then((blob) => {
      const downloadUrl = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = getFileNameFromUrl(url)
      link.click()
    })
}
function getFileName(url: string) {
  let lastSplashIndex = url.lastIndexOf('/')
  let lastDotIndex = url.lastIndexOf('.')
  return url.slice(lastSplashIndex + 1, lastDotIndex)
}
function getFileNameFromUrl(url: string) {
  const lastSlashIndex = url.lastIndexOf('/')
  if (lastSlashIndex !== -1) {
    return url.substring(lastSlashIndex + 1)
  } else {
    return 'Invalid URL'
  }
}

// 获取该目录下是否设置过权限
const hasUpload = ref(false)
const hasReview = ref(false)
async function getAuth() {
  if (!prop.cateId) return
  const { data: uploadUser = [] } = await fetchdbAuthGetInfo({
    cateId: prop.cateId,
    type: 1
  })
  hasUpload.value = uploadUser.findIndex((x: any) => x.userId === user?.id) > -1
  const { data: reviewUser = [] } = await fetchdbAuthGetInfo({
    cateId: prop.cateId,
    type: 2
  })
  hasReview.value = reviewUser.findIndex((x: any) => x.userId === user?.id) > -1
}
</script>

<template>
  <DataBaseHead />
  <div class="w-full h-1px bg-#507FFD mt50px rd-b-20px"></div>
  <div class="w-full h-95%">
    <!-- <div class="px30px flex text-center py40px">
          <div class="bg-#6C93F8 text-#fff px20px pt18px pb-15px w-180px rd-10px mr-15px">
            <img src="@/assets/images/xinxi@2x.png" class="w30px mr-5px mt--3px" /><span>公司经营信息</span>
          </div>
          <div class="bg-#6C93F8 text-#fff px20px  pt18px pb-15px w-180px rd-10px mr-15px">
            <img src="@/assets/images/baogas@2x.png" class="w30px mr-5px mt--3px" /><span>相关报告</span>
          </div>
          <div class="bg-#6C93F8 text-#fff px20px pt18px pb-15pxw-180px rd-10px mr-15px">
            <img src="@/assets/images/kongj@2x.png" class="w30px mr-5px mt--3px" /><span>融合空间</span>
          </div>
          <div class="bg-#6C93F8 text-#fff px20px  pt18px pb-15px w-180px rd-10px mr-15px">
            <img src="@/assets/images/fuwck@2x.png" class="w30px mr-5px mt--3px" /><span>服务窗口</span>
          </div>
          <div class="bg-#6C93F8 text-#fff px20px  pt18px pb-15px w-180px rd-10px mr-15px" @click="push('/DataBase/Modify')">
            <span class="leading-23px">内容管理</span>
          </div>


        </div> -->
    <div class="bg-#fff rd-15px px30px pt30px w-full h930px">
      <div class="rd-15px w-full h870px" style="box-shadow: 1px 2px 26px -3px #cdcccc">
        <div class="h80px rd-t-15px bg-#4877FB leading-80px text-#fff text-20px">
          <img src="@/assets/images/Shape7@2x.png" class="w50px ml-30px mr10px mt--20px" />
          {{ title }}
          <div class="float-right top-0 right-30px">
            <el-button
              class="mr-30px"
              v-if="isDbReview || isDbUpload || userCode"
              type="warning"
              @click="push({ path: '/DataBase/review' })"
            >
              审批流程
            </el-button>
            <el-button
              v-if="isDbReview || isDbUpload || userCode"
              type="primary"
              @click="push('/DataBase/Modify')"
              >内容管理</el-button
            >
          </div>
        </div>
        <div class="p30px relative h790px">
          <!-- lujinli -->
          <!-- <table class="history w-full text-center   text-16px border-spacing-0  "> -->
          <table class="history w-full text-center text-18px border-spacing-0">
            <thead
              style="
                background-color: #e7edff;
                color: #000;
                height: 50px;
                width: 220px;
                border: 1px solid #417bef;
              "
            >
              <tr class="text-20px leading-50px">
                <th width="20%">
                  <img src="@/assets/images/baiot@2x.png" class="w35px mt--7px mr-5px" />标题
                </th>
                <th width="20%">
                  <img src="@/assets/images/scbmm@2x.png" class="w35px mt--7px mr-5px" />上传科室
                </th>
                <th width="20%">
                  <img src="@/assets/images/scbmm@2x.png" class="w35px mt--7px mr-5px" />上传部门
                </th>
                <th width="20%">
                  <img src="@/assets/images/riqii@2x.png" class="w35px mt--7px mr-5px" />上传日期
                </th>
                <th width="20% text-center">操作</th>
              </tr>
            </thead>
            <tbody class="h650px overflow-auto absolute w-full">
              <tr class="w-full flex leading-50px" v-for="it in tableData">
                <td
                  class="w20% h50px cursor-pointer overflow-hidden text-left pl25px truncate text-#000"
                >
                  <div class="flex items-center truncate">
                    <img
                      v-if="isNotOneWeekAgo(it.createTime)"
                      src="@/assets/images/NEW.gif"
                      class="!h-20px !w-auto mr-2"
                      alt=""
                    />
                    <span :title="it.title"> {{ it.title }}</span>
                  </div>
                </td>
                <td class="w20% h50px">{{ it.deptName }}</td>
                <td class="w20% h50px">{{ it.parentDeptName }}</td>
                <td class="w20% h50px">{{ it.createTime }}</td>
                <td class="w20% h50px">
                  <!-- <el-button style="color: #000;"  @click="openUrl(it)">预览</el-button> -->
                  <!-- <el-button style="color: #000;"  @click="downloads(it)">下载</el-button> -->
                  <n-popover
                    trigger="hover"
                    placement="top-start"
                    v-if="arr.includes(it.id) || (it.fileCommon?.fileSize || 0) > 25 * 1024 * 1024"
                  >
                    <template #trigger>
                      <el-button style="color: #000" @click="downloads(it)">查看</el-button>
                    </template>
                    <span>该文件超过25MB，无法进行预览，请点击 查看 进行下载！</span>
                  </n-popover>
                  <el-button v-else style="color: #000" @click="downloads(it)">查看</el-button>
                </td>
              </tr>
            </tbody>
          </table>
          <div class="float-right absolute bottom-20px right-30px">
            <el-pagination
              v-model:current-page="pageInfo.currentPage"
              v-model:page-size="pageInfo.pageSize"
              layout="prev, pager, next, jumper"
              :total="pageInfo.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
  <n-modal v-model:show="pdfShow">
    <div class="w100% h100%">
      <el-icon color="#fff" size="26px" @click="pdfShow = false" class="absolute left-92% bg-#F43"
        ><Close
      /></el-icon>
      <Amtion :data="src" :datas="srcType" />
    </div>
  </n-modal>
</template>
<style>
.truncate {
  display: block;
  /* max-width: 226px; */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
