<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">{{ Array.isArray(KBData.tags) ? KBData.tags.join("、") : "" }}</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 v-if="operationPermissions['a-6']" @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;" v-if="operationPermissions['a-10']"
            @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="50" />
            <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>
                  <el-text line-clamp="1" class="text-area"
                    @click="operationPermissions['a-7'] ? handleViewFile(row) : null">
                    {{ row.file_name }}
                  </el-text>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="knowledge_type" label="知识类型">
              <template #default="{ row }">
                <el-text line-clamp="1" style="vertical-align: bottom;">{{ row.knowledge_type }}</el-text>
              </template>
            </el-table-column>
            <el-table-column prop="version" label="版本" />
            <el-table-column prop="author" label="作者（主编）" min-width="90" />
            <el-table-column prop="year" label="年份" min-width="60" />
            <el-table-column prop="creator" label="上传人">
              <template #default="{ row }">
                <el-text line-clamp="1" style="vertical-align: bottom;">{{ row.creator }}</el-text>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="上传时间" width="155" />
            <el-table-column prop="status" label="状态" width="107">
              <template #default="{ row, $index }">
                <div class="status">
                  <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-if="operationPermissions['a-8']" v-model="row.status"
                    @change="handleStatusChange(row.id, row.status)"></el-switch>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="operationPermissions['a-9']" prop="created_at" label="下载" width="50">
              <template #default="{ row }">
                <div style="text-align: center;">
                  <i class="document-download-icon" :disabled="row.status ? true : false"
                    @click="handleDownloadFile(row)"></i>
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="85">
              <template #default="{ row }">
                <div class="operation">
                  <el-button link type="primary" v-if="operationPermissions['a-10']"
                    @click="handleEditFile(toRaw([row]))">修改</el-button>
                  <el-button link type="danger" v-if="operationPermissions['a-11']"
                    @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="handleCloseViewer" />
    <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 { 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"
import { useMenuStore } from "@/stores/menu.js"
const { operationPermissions } = useMenuStore();
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)
}

// 定义处理关闭查看器的方法
const handleCloseViewer = () => {
  viewFileData.value.show = false;
};
// 修改状态
const handleStatusChange = async (id, status) => {
  // console.log('handleStatusChange', status)
  try {
    await proxy.$http.get(api.files + `${id}/changeStatus`, {
      params: {
        status: status
      }
    })
    ElMessage({
      message: '状态修改成功',
      type: 'success',
    })
  }
  catch (e) {
    console.log(e)
    ElMessage({
      message: '状态修改失败',
      type: 'error',
    })
    let index = filesList.value.findIndex(item => item.id === id)
    filesList.value[index].status = !status // 恢复原状态
  }
  // 这里可以添加逻辑来处理状态变化
  // 比如发送请求到后端更新状态
}

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

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

const handleViewFile = (fileData) => {
  const { minio_url, file_type, file_name, id } = fileData
  const url = `/open-platform/files/${id}/download`
  viewFileData.value.show = true;
  viewFileData.value.url = url;
  viewFileData.value.type = file_type
  viewFileData.value.name = file_name
  // console.log(viewFileData.value)
}
function handleDownloadFile(fileData) {
  const { minio_url, file_name, status, id } = fileData
  if (status) {
    const file_url = `/open-platform/files/${id}/download`
    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;
          }
        }
      }
    }

    :deep(.el-table) {
      min-width: 0px;
      max-width: auto;

      .cell {
        padding: 0px 8px;
      }

      .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: flex;
        align-items: center;

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

        .icon-area {
          flex: 0 0 auto;
        }

        .text-area {
          flex: 1 1 auto;
        }
      }

      .status {
        display: flex;
        align-items: center;
        gap: 10px;
        white-space: nowrap;
      }

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

        &: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;
        }


      }
    }
  }

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

    .pagination {
      width: auto;

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

  }

  .switch {
    :deep(.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;
      }
    }
  }
}
</style>