<template>
  <div class="knowledge-management">
    <header>
      <i class="back-icon" @click="goKBM"></i>
      <i class="folder-icon" style="height: 32px;width:32px;cursor: pointer;" @click="goKBM"></i>
    </header>
    <main>
      <div class="aside">
        <div class="name">{{ KBData.name }}</div>
        <div class="tags">{{ KBData.tags }}</div>
        <div class="description">{{ KBData.description }}</div>
        <!-- <div class="other">无关联应用ⓘ</div> -->
      </div>
      <div class="management-content">
        <div class="management-content-top">
          <div class="search">
            <el-input v-model="querySearch" size="large" placeholder="搜索" @keydown.enter="getFilesList"
              :prefix-icon="Search" />
          </div>

          <span @click="addFileVisible = true" class="add-file"><el-icon color="#fff">
              <Plus />
            </el-icon> <i class="text">添加文件</i></span>
          <span class="add-file" style="margin-right: 10px;" @click="handleBatchEditFiles"><i class="text"
              style="margin: 0px;">批量修改文件</i></span>
        </div>
        <div class="management-content-middle">
          <el-table :data="filesList" ref="fileTableRef" size="large" style="width: 99% ;">
            <el-table-column type="selection" width="35" />
            <el-table-column label="#" prop="index" width="60" />
            <el-table-column prop="file_name" min-width="150" label="标题">
              <template #default="{ row }">
                <div class="list-name">
                  <span class="icon-area">
                    <i :class="`${row.file_type}-icon file-icon`"></i>
                  </span>
                  <span @click="handleViewFile(row.minio_url, row.file_type)" class="text-area">
                    {{ row.file_name }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="knowledge_type" label="知识类型" />
            <el-table-column prop="version" label="版本" />
            <el-table-column prop="author" label="作者（主编）" />
            <el-table-column prop="year" label="年份" min-width="70" />
            <el-table-column prop="creator" label="上传人" />
            <el-table-column prop="created_at" label="上传时间" width="170" />
            <el-table-column prop="" label="状态">
              <template #default="{ row }">
                <div style="display:flex; align-items: center;gap: 10px;">
                  <span v-if="row.status">
                    <i class="circle" type="success"></i>
                    <el-text type="success">可用</el-text>
                  </span>
                  <!-- <span v-else>
                  <i class="circle" type="warning"></i>
                  <el-text type="warning">异常</el-text>
                </span> -->
                  <span v-else>
                    <i class="circle" type="danger"></i>
                    <el-text type="danger">禁用</el-text>
                  </span>
                  <el-switch v-model="row.status"></el-switch>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="下载" width="70">
              <template #default="{ row }">
                <i class="document-download-icon" :disabled="row.status ? true : false"
                  @click="handleDownloadFile(row.minio_url, row.file_name, row.status)"></i>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template #default="{ row }">
                <div class="operation">

                  <!-- <el-icon size="24">
                    <Operation />
                  </el-icon>
                  <el-icon size="24">
                    <MoreFilled />
                  </el-icon> -->
                  <el-button link type="primary" @click="handleEditFile(toRaw([row]))">修改</el-button>
                  <el-button link type="danger" @click="handleDeleteFile(row.id)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </main>
    <footer>
      <div class="pagination" v-if="totalPage > 1 || paginationData.defaultPageSize !== paginationData.currentPageSize">
        <el-pagination :current-page="paginationData.currentPage" :page-sizes="paginationData.pageSizes"
          :disabled="paginationData.disabled" :default-page-size="paginationData.defaultPageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="paginationData.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </footer>
    <CreateKBFileDialog v-model="addFileVisible" :knowledgeBase="KBData" @updateFiles="getFilesList()" />
    <FileViewer v-if="viewFileData.show" :fileType="viewFileData.type" :fileName="viewFileData.name"
      :fileUrl="viewFileData.url" :width="viewFileData.width" @closeViewer="() => viewFileData.show = false" />
    <EditKBFileDialog v-model="editKBFileData.show" :fileTable="editKBFileData.data"
      @updateFiles="() => { getFilesList() }" />
  </div>

</template>

<script setup>
import { saveAs } from 'file-saver'
import { ElMessage } from 'element-plus'
import { ref, getCurrentInstance, computed, watch, toRaw, onMounted } from 'vue'
import { Download, Search } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { api } from '@/utils/config';
import { confirmDelete } from "@/utils/confirmation"
import CreateKBFileDialog from '@/components/CreateKBFileDialog.vue';
import FileViewer from "@/components/FileViewer/FileViewer.vue"
import EditKBFileDialog from "@/components/EditKBFileDialog.vue"
const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
const kbId = route.params.kbId
let filesList = ref([])
let KBData = ref({})
let addFileVisible = ref(false)

let querySearch = ref("")
let editKBFileData = ref({
  show: false,
  data: []
})
let viewFileData = ref({
  url: "",
  name: "",
  type: "",
  show: false,
  width: 1000,
})
const paginationData = ref({
  currentPage: 1,
  pageSizes: [10, 50, 100, 200],
  disabled: false,
  total: 0,
  defaultPageSize: 10,
  currentPageSize: 10
})
const totalPage = computed(() => {
  return Math.ceil(paginationData.value.total / paginationData.value.currentPageSize)
})
const handleSizeChange = (pageSize) => {
  paginationData.value.currentPageSize = pageSize
  // console.log('handleSizeChange', pageSize)
}
async function checkLinkValidity(index, url) {
  try {
    const response = await axios.head(url);  // 使用 HEAD 请求，仅请求响应头
    if (response.status >= 200 && response.status < 300) {
      filesList.value[index].isValid = true
    } else {
      filesList.value[index].isValid = false  // 返回 false 表示链接无效
    }
  } catch (error) {
    filesList.value[index].isValid = false // 请求失败，返回 false
  }
}

function handleBatchEditFiles() {
  const fileTableRef = proxy.$refs['fileTableRef']
  const selectionRows = fileTableRef.getSelectionRows()
  if (selectionRows.length == 0) return;
  handleEditFile(toRaw(selectionRows))
}

function handleEditFile(data) {
  editKBFileData.value.show = true;
  editKBFileData.value.data = data;
}

const handleViewFile = (url, type) => {
  viewFileData.value.show = true;
  viewFileData.value.url = url;
  viewFileData.value.type = type
  // console.log(viewFileData.value)
}
function handleDownloadFile(file_url, file_name, status = true) {
  if (status) {
    saveAs(file_url, file_name)
  }
}
const handleCurrentChange = (page) => {
  paginationData.value.currentPage = page
  // console.log('handleCurrentChange', page)
}
const getKnowledgeBaseById = async () => {
  try {
    const data = await proxy.$http.get(api.knowledgeBase + `/${kbId}`)
    KBData.value = data
  } catch (e) {
    console.log(e)
  }
}

function goKBM() {
  router.push({ name: 'kbm' })
}

const getFilesList = async () => {
  try {
    const data = await proxy.$http.get(api.knowledgeBase + `/${kbId}/files/`, {
      params: {
        file_name: querySearch.value,
        pageSize: paginationData.value.currentPageSize,
        pageNo: paginationData.value.currentPage
      }
    })
    filesList.value = data.list
    paginationData.value.total = data.total
    for (let i = 0; i < filesList.value.length; i++) {
      filesList.value[i].index = (paginationData.value.currentPage - 1) * paginationData.value.currentPageSize + i + 1
      // filesList.value[i].isValid = true
      filesList.value[i].status = true
      // checkLinkValidity(i, filesList.value[i].minio_url)
    }
  } catch (e) {
    console.log(e)
  }
}
const handleDeleteFile = (id) => {
  confirmDelete({
    title: '',
    content: '确认要删除该知识文件吗？',
    type: 1,
  },
    async () => {
      try {
        const data = await proxy.$http.delete(api.files + `/${id}`)
        ElMessage({
          message: '知识文件删除成功',
          type: 'success',
        })
        getFilesList()
      } catch (e) {
        ElMessage({
          message: '知识文件删除失败',
          type: 'error',
        })
        console.log(e)
      }
    },
    () => {
      console.log("不删除")
    }
  )
}
watch(() => paginationData.value.currentPage, () => {
  getFilesList()
}, { immediate: true })

watch(() => paginationData.value.currentPageSize, () => {
  getFilesList()
})
getKnowledgeBaseById()

onMounted(() => {
  // const fileTableRef = proxy.$refs['fileTableRef']
})
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";

.knowledge-management {
  min-height: 100%;

  .file-icon {
    width: 20px;
    height: 20px;
  }

  .search {
    // padding: 10px 20px;
    margin: 5px;
    background: white;
    display: inline-block;

    /deep/ .el-input__wrapper {
      background-color: @bgColor;
      border-radius: 10px;
    }

    .el-input {
      width: 250px;
    }
  }

  main {
    display: flex;
    // flex-direction: column;
    flex-wrap: nowrap;

    .aside {

      width: 300px;
      flex: 0 0 auto;

      // &>div {
      //   margin-top: 20px;
      // }

      .name {
        font-weight: bold;
        font-size: 18px;
        margin-top: 20px;
      }

      .tags {
        color: #A8ACB8;
        font-size: 14px;
        line-height: 1.4;
        margin-top: 5px;
      }

      .description {
        color: #A8ACB8;
        font-size: 16px;
        margin-top: 10px;
        line-height: 1.5;
      }

      .other {
        color: #354052;
        margin-top: 20px;
      }
    }

    .management-content {
      flex: 1 1 auto;
      min-width: 0px; //让盒子可以压缩

      .management-content-top {
        clear: both;

        .add-file {
          color: white;
          background-color: #5780FC;
          margin-left: auto;
          padding: 10px 15px;
          border-radius: 9px;
          display: inline-block;
          cursor: pointer;
          float: right;
          display: flex;

          // .el-icon,
          .text {
            // vertical-align: middle;
            margin-left: 10px;
          }
        }
      }
    }

    &::v-deep .el-table {
      min-width: 0px;
      max-width: 100%;

      .document-download-icon {
        width: 28px;
        height: 28px;
        cursor: pointer;

        &:is([disabled='false']) {
          cursor: not-allowed;
          opacity: 0.5;
        }
      }

      .list-name {
        white-space: nowrap;
        text-overflow: ellipsis;
        display: inline;

        .text-area,
        .icon-area {
          vertical-align: bottom;
        }
      }

      .circle {
        border-radius: 50%;
        width: 10px;
        height: 10px;
        background-color: #8AD068;
        display: inline-block;
        margin-right: 10px;

        &:is([type='warning']) {
          background-color: #E6A23C;
        }

        &:is([type='danger']) {
          background-color: #F56C6C;
        }
      }

      .operation {
        display: flex;
        align-items: center;
        // justify-content: space-evenly;
        gap: 0px 10px;

        .el-button+.el-button {
          margin: 0px;
        }

        .el-switch {
          &:is(.is-checked) {
            .el-switch__core {
              background-color: #155AEF;
            }
          }

          .el-switch__core {
            border-radius: 5px;
            width: 35px;
            min-width: 0px;
            // background-color: #155AEF;
          }

          .el-switch__action {
            border-radius: 3px;
          }
        }
      }
    }
  }

  footer {
    margin-top: 20px;
    width: auto;

    .pagination {
      width: auto;

      .el-pagination {
        justify-content: end;
      }
    }

  }
}
</style>