<script setup lang="ts">
import { getTagList, addTag, updateTag, deleteTag, importTag } from '../api'
import ViewGraphCourse from '../components/ViewGraphCourse.vue'
import ViewGraphBook from '../components/ViewGraphBook.vue'
import { ElMessage } from 'element-plus'

const route = useRoute()

// 获取列表
const tableData = ref([])
const updateTagList = () => {
  getTagList({ type: '1', parent_id: route.query.cid as string }).then(res => {
    tableData.value = res.data
  })
}
updateTagList()

// 新增
const addTagRequest = () => {
  addTag({ name: pName.value, course_id: route.query?.cid as string, status: '1', parent_id: addTagId.value }).then(
    res => {
      updateTagList()
      ElMessage({
        message: '添加成功',
        type: 'success'
      })
    }
  )
}

// 更新
const updateTagRequest = () => {
  updateTag({ id: addTagId.value, name: pName.value, course_id: route.query?.cid as string, status: '1' }).then(res => {
    updateTagList()
    ElMessage({
      message: '修改成功',
      type: 'success'
    })
  })
}

const findParentIdById = (items: any, targetId: any) => {
  // 使用栈来模拟递归过程，存储当前遍历元素和父级id
  const stack = [...items] // 初始化栈为顶层元素
  // 使用栈遍历
  while (stack.length > 0) {
    const currentItem = stack.pop() // 取出栈顶元素
    // 检查当前元素是否是目标元素
    if (currentItem.id === targetId) {
      return currentItem.parentId // 找到目标元素，返回父级id
    }
    // 如果当前元素有children，继续遍历子元素
    if (currentItem.children) {
      for (const child of currentItem.children) {
        child.parentId = currentItem.id // 为子元素添加父级id
        stack.push(child) // 将子元素压入栈中
      }
    }
  }
  return undefined // 如果没有找到目标id，返回undefined
}

// 弹窗输入框
const pName: any = ref('')
const dialogVisible = ref(false)
const isUpdate = ref(false)
// 点击添加同级 子级的id
const addTagId = ref<any>('')
const handleAddTagSame = (scope: any) => {
  const id = findParentIdById(tableData.value, scope?.row?.id)
  addTagId.value = id || ''
  isUpdate.value = false
  dialogVisible.value = true
}
const handleAddTagChild = (scope: any) => {
  addTagId.value = scope?.row.id
  isUpdate.value = false
  dialogVisible.value = true
}
const handleUpdateTag = (scope: any) => {
  addTagId.value = scope?.row?.id
  pName.value = scope?.row?.name
  isUpdate.value = true
  dialogVisible.value = true
}

// 输入完名称点击输入框
const handleConfirm = () => {
  if (isUpdate) {
    updateTagRequest()
  } else {
    addTagRequest()
  }
  dialogVisible.value = false
}

const handleDelete = (scope: any) => {
  deleteTag({ id: scope.row?.id, course_id: route.query.cid as string }).then(res => {
    updateTagList()
    ElMessage({
      message: '删除成功',
      type: 'success'
    })
  })
}

const isShowGraphCourseDialog = ref(false)
const isShowGraphBookDialog = ref(false)

const handleCourseView = function (scope: any) {
  addTagId.value = scope.row?.id
  isShowGraphCourseDialog.value = true
}

const handleBookView = function (scope: any) {
  addTagId.value = scope.row?.id
  isShowGraphBookDialog.value = true
}

const formInline = reactive({
  user: ''
})

// 导出
const handleTagDownload = () => {
  // tagDownload({ course_id: route.query.cid as string }).then()
  window.open(`/api/resource/v1/course/course/tag-download?course_id=${route.query.cid}`)
}

const fetchFileUpload = (option: any) => {
  return new Promise(() => {
    importTag({ course_id: route.query.cid as string, file: option.file }).then(() => {
      updateTagList()
      ElMessage.success('导入数据成功')
    })
  })
}
</script>
<template>
  <AppCard title="知识图库">
    <div style="margin-bottom: 15px">课程名称：{{ route.query?.n }}</div>
    <!-- <div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="知识点">
          <el-input v-model="formInline.user" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary">搜索</el-button>
          <el-button type="primary">重置</el-button>
        </el-form-item>
      </el-form>
    </div> -->
    <div style="display: flex">
      <el-button type="primary" @click="handleAddTagSame">添加知识点</el-button>
      <el-upload :show-file-list="false" ref="upload" action="#" :limit="1" :http-request="fetchFileUpload">
        <el-button type="primary" style="margin: 0 15px">批量导入</el-button>
        <!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖至此处，点击上传</div> -->
      </el-upload>
      <el-button type="primary" @click="handleTagDownload">导出</el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%; margin: 20px 0"
      row-key="id"
      highlight-current-row
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      align="center"
    >
      <!-- <el-table-column type="index"></el-table-column> -->
      <el-table-column prop="name" label="知识点"> </el-table-column>
      <!-- <el-table-column prop="update" label="更新人" width="180"> </el-table-column>
      <el-table-column prop="time" label="更新时间" width="180"> </el-table-column> -->
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleAddTagSame(scope)"> 添加同级 </el-button>
          <el-button link type="primary" size="small" @click="handleAddTagChild(scope)">添加子级</el-button>
          <el-button link type="primary" size="small" @click="handleUpdateTag(scope)">编辑知识点</el-button>
          <el-button link type="primary" size="small" @click="handleDelete(scope)">删除</el-button>
          <el-button link type="primary" size="small" @click="handleCourseView(scope)">查看关联章节</el-button>
          <el-button link type="primary" size="small" @click="handleBookView(scope)">查看关联数字教材</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="提示" width="500px">
      <!-- <span>This is a message</span> -->
      <el-input v-model="pName" placeholder="请输入知识点名称" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <Operation :data="courseDetails" @update="handleFresh"></Operation>
    <div class="course-view">
      <ViewCourseInfoTop :data="courseDetails"></ViewCourseInfoTop>

      <div class="course-left_info">
        <ViewCourseInfo :data="courseDetails" class="info_bottom" :id="id"></ViewCourseInfo>
        <ViewCourseChapter
          v-if="Object.keys(courseDetails).length"
          :data="chapters"
          class="info_chapter"
        ></ViewCourseChapter>
      </div>
    </div> -->
  </AppCard>
  <ViewGraphCourse
    :id="addTagId"
    v-if="isShowGraphCourseDialog === true"
    v-model:isShowGraphCourseDialog="isShowGraphCourseDialog"
  />
  <ViewGraphBook
    :id="addTagId"
    v-if="isShowGraphBookDialog === true"
    v-model:isShowGraphBookDialog="isShowGraphBookDialog"
  />
</template>
<style lang="scss">
.course-view {
  border: 1px solid #bfbfbf;

  border-radius: 10px;
  display: flex;
  flex-direction: column;
  .course-left_info {
    display: flex;
    .info_bottom {
      width: 67%;
    }
    .info_chapter {
      width: 25%;
    }
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.course_tip {
  font-size: 12px;
  font-weight: 400;
  color: #999999;
  margin-left: 16px;
  line-height: 36px;
  height: 36px;
}
.el-tree-node__content {
  height: 42px;
  margin-bottom: 15px;
  background: #f4f4f4;
}
.btn_operate {
  background-color: rgba(248, 241, 229, 0.39);
  font-weight: 400;
  color: #b2833d;
  border: none;
  border-radius: 16px;
  margin: 3px;
}
.btn_control {
  font-weight: 400;
  color: #b2833d;
}
.btn_edit {
  color: #b2833d;
  margin-right: 10px;
}
.node_type {
  background: #bf9d6b;
  border-radius: 20px;
  line-height: 1;
  font-size: 12px;
  font-weight: 400;
  color: #ffffff;
  text-align: center;
  padding: 4px 8px;
  margin-right: 14px;
}
.node_title {
  font-size: 14px;
  font-weight: 400;
  color: #666666;
  line-height: 1;
  text-align: center;
}
</style>
