<script lang="ts" setup>
import { checkPermission } from '@/utils/permission'

import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCharacter, delCharacter, getVideoDetails, dragChapterList, createCharacter, editCharacter } from '../api'
// 更改资源名称
import EditResourcesName from '../components/stepTwoComponents/EditResourcesName.vue'
import AddSectionDialog from '../components/stepTwoComponents/AddSectionDialog.vue'
import AddLiveDialog from '../components/stepTwoComponents/AddLiveDialog.vue'
import AddVideoDialog from '../components/stepTwoComponents/AddVideoDialog.vue'
import AddExamDialog from '../components/stepTwoComponents/AddExamDialog.vue'
import VideoPlayDialog from '../components/stepTwoComponents/VideoPlayDialog.vue'
import AddChapterDialog from '../components/stepTwoComponents/AddChapterDialog.vue'
import AddTextbookDialog from '../components/stepTwoComponents/AddTextbookDialog.vue'
import AddGraphbookDialog from '../components/stepTwoComponents/AddGraphbookDialog.vue'
import AddKnowledge from '../components/stepTwoComponents/AddKnowledge.vue'
import KnowledgeGraphPreview from '../components/stepTwoComponents/KnowledgeGraphPreview.vue'

import OpenRules from '../components/stepTwoComponents/OpenRules.vue'
const route = useRoute()
const router = useRouter()
const isEditCourse = route.query.isEditCourse as string
const id = route.query.id as string
const dataSource: any = ref([])
const isShowOpenRules = ref(false)
const isShowDialog = ref(false)
const isShowSectionDialog = ref(false)
// 修改资源名称弹窗
const isEditResourcesNameDialog = ref(false)
// 资源id
const isShowTextbookDialog = ref(false)
const isShowTextbookDialog2 = ref(false)
const resourceId = ref('')
const isShowLiveDialog = ref(false)
const isShowAddDialog = ref(false)
const isShowExamDialog = ref(false)
const isShowVideoPlayDialog = ref(false)
const chapterName = ref('')
const chapterID = ref('')
const parentID = ref('')
const btnInfo = ref({}) // 按钮信息
const isEdit = ref(false)
const videoUrl = ref('')
const sectionName = ref('')
const controlInfo = ref({})
const paper_use_list: any = ref([])
const defaultExpandedKeys: any = ref([])
const flag = ref(false)
const btnList = [
  {
    btn_name: '视频',
    resource_type: '2',
  },
  {
    btn_name: '课件',
    resource_type: '10',
  },
  {
    btn_name: '教案',
    resource_type: '11',
  },
  {
    btn_name: '资料',
    resource_type: '4',
  },
  {
    btn_name: '作业',
    resource_type: '3',
  },
  {
    btn_name: '考试',
    resource_type: '9',
  },
  {
    btn_name: '直播',
    resource_type: '6',
  },
  {
    btn_name: '知识点',
    resource_type: '999',
  },
  {
    btn_name: '关联数字教材',
    resource_type: '13',
  },
  // {
  //   btn_name: '关联知识图谱',
  //   resource_type: '14',
  // },
]
const defaultProps = {
  children: 'children',
  label: 'name',
}

// 获取章节列表
onMounted(() => {
  checkPermission('v1-course-chapters') && handleChapterList()
})
const handleChapterList = () => {
  getCharacter({ course_id: id, type: 'tree' }).then((res: any) => {
    dataSource.value = res.data[0]?.children
    if (flag.value === false) {
      defaultExpandedKeys.value = [dataSource.value[0]?.id]
    }
    dataSource.value?.forEach((item: any) => {
      if (item.children.length) {
        item.children.forEach((it: any) => {
          it.parent_id = item.id
        })
      }
    })
  })
}

// 新增章节
const handleAddChapter = () => {
  isShowDialog.value = true
  isEdit.value = false
}
// 页面刷新
const handleFresh = () => {
  handleChapterList()
}
// 添加小节
const handleAddSection = (node: any) => {
  chapterName.value = node.label
  chapterID.value = node.key
  isShowSectionDialog.value = true
  isEdit.value = false
  flag.value = true
  defaultExpandedKeys.value = [node.key]
}
//编辑章节
const handleEdit = (node: any, type: string) => {
  chapterID.value = node.key
  if (type !== '3') {
    isEdit.value = true
    if (node.level === 1) {
      isShowDialog.value = true
      chapterName.value = node.label
    } else {
      chapterName.value = node.data.parent_name
      sectionName.value = node.label
      isShowSectionDialog.value = true
    }
  } else {
    resourceId.value = node.data.resource.id
    isEditResourcesNameDialog.value = true
    sectionName.value = node.label
  }
}
// 删除章节
const handleDel = (node: any) => {
  ElMessageBox.confirm('确定要删除吗？', '提示').then(() => {
    const params = { id: node.key, course_id: id }
    delCharacter(params).then(() => {
      ElMessage.success('删除成功')
      handleFresh()
    })
  })
}

// 添加
const handleAddDialog = (node: any, item: any, data: any) => {
  console.log(data, 'data', dataSource)
  chapterID.value = node.key
  chapterName.value = node.label
  parentID.value = data.parent_id
  btnInfo.value = item
  flag.value = true
  defaultExpandedKeys.value = [node.key]
  if (item.resource_type === '6' && checkPermission('v1-course-search-live')) {
    isShowLiveDialog.value = true
  } else if (
    (item.resource_type === '2' && checkPermission('v1-course-search-video')) ||
    (item.resource_type === '10' && checkPermission('v1-course-search-courseware')) ||
    (item.resource_type === '11' && checkPermission('v1-course-search-lesson-plan')) ||
    (item.resource_type === '4' && checkPermission('v1-course-search-other-information'))
  ) {
    isShowAddDialog.value = true
  } else if (item.resource_type === '9') {
    isShowExamDialog.value = true
    paper_use_list.value = [1, 3]
  } else if (item.resource_type === '3') {
    isShowExamDialog.value = true
    paper_use_list.value = [2]
  } else if (item.resource_type === '13') {
    isShowTextbookDialog.value = true
  } else if (item.resource_type === '14') {
    isShowTextbookDialog2.value = true
  } else if (item.resource_type === '999') {
    isShowKnowledgeDialog.value = true
  }
}
//查阅
const handleConsult = (node: any) => {
  console.log(node, 'node')

  // 视频
  if (node.data.resource_type === '2') {
    getVideoDetails({ id: node.data.resource_id }).then((res) => {
      videoUrl.value = res.data.play_auth.play_info_list.filter((item: any) => item.Definition === 'SD')[0].PlayURL
      isShowVideoPlayDialog.value = true
    })
  }
  if (node.data.resource_type === '13') {
    window.open(
      `https://zijingebook.ezijing.com/student/book?book_id=${route.query.bid}&chapter_id=${node.data.resource_id}`
    )
  }
}
// 下载
const handleDownload = (node: any) => {
  window.open(node.data.resource.url)
}
//拖拽
const allowDrop = (draggingNode: any, dropNode: any, type: any) => {
  if (draggingNode.data.depth === dropNode.data.depth) {
    if (draggingNode.data.parentId === dropNode.data.parentId) {
      return type === 'prev' || type === 'next'
    } else {
      return false
    }
  } else {
    // 不同级进行处理
    return false
  }
}
//拖拽列表
const handleDrop = (startNode: any, endNode: any, position: any) => {
  if (checkPermission('v1-course-drag')) {
    const params = {
      course_id: id,
      id: startNode.data.id,
      brother_id: endNode.data.id,
      type: position,
    }
    dragChapterList(params).then(() => {
      handleChapterList()
    })
  }
}
const imgUrl = (node: any) => {
  if (node.data.resource_type === '1') {
    // 章节
    return '/center_resource/chapter_img.png'
  } else if (node.data.resource_type === '2') {
    // 视频
    return '/center_resource/mp4_img.png'
  } else if (node.data.resource_type === '3') {
    // 作业
    return '/center_resource/homework.png'
  } else if (node.data.resource_type === '4' || node.data.resource_type === '10' || node.data.resource_type === '11') {
    if (node.data.resource?.url.includes('pptx') || node.data.resource?.url.includes('ppt')) {
      // 其他资源
      return '/center_resource/pptx_img.png'
    } else if (node.data.resource?.url.includes('rar')) {
      // 其他资源
      return '/center_resource/rar_img.png'
    } else if (node.data.resource?.url.includes('zip')) {
      // 其他资源
      return '/center_resource/zip_img.png'
    } else if (node.data.resource?.url.includes('mp3')) {
      // 其他资源
      return '/center_resource/mp3_img.png'
    } else if (node.data.resource?.url.includes('mp4')) {
      // 其他资源
      return '/center_resource/mp4_img.png'
    } else if (node.data.resource?.url.includes('docx') || node.data.resource?.url.includes('doc')) {
      return '/center_resource/docx_img.png'
    } else if (node.data.resource?.url.includes('xls') || node.data.resource?.url.includes('xlsx')) {
      return '/center_resource/xls_img.png'
    } else if (
      node.data.resource?.url.includes('png') ||
      node.data.resource?.url.includes('jpeg') ||
      node.data.resource?.url.includes('jpg')
    ) {
      return '/center_resource/jpg_img.png'
    } else if (node.data.resource?.url.includes('pdf')) {
      return '/center_resource/pdf_img.png'
    }
  } else if (node.data.resource_type === '6') {
    // 直播
    return '/center_resource/live_img.png'
  } else if (node.data.resource_type === '9') {
    // 考试
    return '/center_resource/test_img.png'
  } else if (node.data.resource_type === '13') {
    // 考试
    return '/center_resource/docx_img.png'
  }
}
const nodeType = (node: any) => {
  if (node.data.resource_type === '2') {
    // 视频
    return '视频'
  } else if (node.data.resource_type === '3') {
    // 作业
    return '作业'
  } else if (node.data.resource_type === '4') {
    return '其他资源'
  } else if (node.data.resource_type === '6') {
    // 直播
    return '直播'
  } else if (node.data.resource_type === '9') {
    // 考试
    return '考试'
  } else if (node.data.resource_type === '10') {
    // 考试
    return '课件'
  } else if (node.data.resource_type === '11') {
    // 考试
    return '教案'
  } else if (node.data.resource_type === '13') {
    return '数字教材'
  } else if (node.data.resource_type === '14') {
    return '知识图谱'
  }
}
const handleNodeExpand = (data: any) => {
  flag.value = true
  defaultExpandedKeys.value = [data.id]
}
const handleNodeCollapse = () => {
  flag.value = false
  defaultExpandedKeys.value = []
}
// 设置开放规则
const handleOpenRules = (node: any, data: any) => {
  if (node.level === 1) {
    chapterName.value = node.label
    sectionName.value = '无'
    chapterID.value = node.key
    controlInfo.value = data.control
  } else {
    chapterName.value = data.parent_name
    chapterID.value = node.key
    sectionName.value = node.label
    controlInfo.value = data.control
  }
  isShowOpenRules.value = true
}
// 控制学生能否下载
const handleChangeStatus = (node: any, data: any) => {
  if (isEditCourse !== '1') {
    const params: any = {
      course_id: id,
      resource_type: node.data.resource_type,
      name: node.label,
      resource_id: node.data.resource_id,
      can_download: node.can_download,
    }
    createCharacter(params).then(() => {
      ElMessage.success('设置下载控制成功')
    })
  } else {
    const params: any = {
      course_id: id,
      id: data.id,
      name: node.label,
      resource_id: node.data.resource_id,
      can_download: node.data.can_download,
    }
    editCharacter(params).then(() => {
      ElMessage.success('设置下载控制成功')
    })
  }
}

const isShowKnowledgeDialog = ref(false)
const isShowKnowledgeGraphPreview = ref(false)
const knowledgeGraphTitle = ref('')
const currentChapterId = ref('')

// 显示知识图谱预览
const handleShowKnowledgeGraph = (node: any) => {
  knowledgeGraphTitle.value = `${node.label} - 知识点脑图预览`
  currentChapterId.value = node.key
  isShowKnowledgeGraphPreview.value = true
}

const handleShowCourseKnowledgeGraph = () => {
  knowledgeGraphTitle.value = '课程知识点脑图预览'
  currentChapterId.value = ''
  isShowKnowledgeGraphPreview.value = true
}
</script>
<template>
  <AppCard :title="isEditCourse === '1' ? '编辑课程' : '新建课程'">
    <el-row>
      <el-button
        type="primary"
        round
        style="margin-bottom: 20px; margin-right: 10px"
        @click="handleAddChapter"
        v-permission="'v1-course-create-chapter'"
        >添加章</el-button
      >
      <el-button type="primary" round style="margin-bottom: 20px" @click="handleShowCourseKnowledgeGraph"
        >知识点脑图</el-button
      >
      <div class="course_tip">
        温馨提示：先建"章"，后建"小节"；课程资源关联到小节；能够关联的资源包含：视频、作业、考试、直播、其他资料、教案、课件。
      </div>
    </el-row>
    <el-tree
      ref="treeRef"
      draggable
      :data="dataSource"
      node-key="id"
      :accordion="true"
      :props="defaultProps"
      :allow-drop="allowDrop"
      :default-expanded-keys="defaultExpandedKeys"
      :expand-on-click-node="false"
      @node-drop="handleDrop"
      style="min-width: 100%"
      @node-expand="handleNodeExpand"
      @node-collapse="handleNodeCollapse">
      <!--  -->
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>
            <img :src="imgUrl(node)" alt="" style="width: 13px; height: 100%; margin-right: 13px" />
            <span class="node_type" v-if="node.data.resource_type !== '1'">{{ nodeType(node) }}</span>
            <span class="node_title">{{ node.label.length > 20 ? node.label.slice(0, 20) + '...' : node.label }}</span>
            <el-link
              class="btn_edit"
              v-if="
                (data.depth === '3' && node.data.resource_type === '2') ||
                node.data.resource_type === '13' ||
                node.data.resource_type === '14'
              "
              @click="handleConsult(node)"
              :disabled="
                (node.data.resource?.can_view !== true && node.data.resource_type !== '13') ||
                node.data.resource_type === '14'
              "
              style="margin-left: 35px"
              >查阅</el-link
            >
            <el-link
              class="btn_edit"
              v-if="
                data.depth === '3' &&
                node.data.resource_type !== '2' &&
                node.data.resource_type !== '6' &&
                node.data.resource_type !== '3' &&
                node.data.resource_type !== '9' &&
                node.data.resource_type !== '13' &&
                node.data.resource_type !== '14'
              "
              @click="handleDownload(node)"
              :disabled="node.data.resource?.can_view !== true"
              style="margin-left: 35px"
              >下载</el-link
            >
            <!-- data.depth !== '3' 资源-->
            <el-link
              v-if="node.data.resource_type !== '13' || node.data.resource_type !== '14'"
              class="btn_edit"
              @click="handleEdit(node, data.depth)"
              style="margin-left: 35px"
              v-permission="'v1-course-update-chapter'"
              >编辑</el-link
            >
            <el-link
              type="info"
              @click="handleDel(node)"
              style="margin-left: 25px"
              v-permission="'v1-course-delete-chapter'"
              >删除</el-link
            ></span
          >

          <span>
            <el-button
              class="btn_operate"
              v-if="data.depth === '1' || data.depth === '2'"
              @click="handleOpenRules(node, data)"
              v-permission="'v1-course-set-chapter-rules'">
              <el-icon><Plus /></el-icon>
              &nbsp; 开放规则
            </el-button>
            <el-button class="btn_operate" v-if="data.depth === '1'" @click="handleAddSection(node)">
              <el-icon><Plus /></el-icon>
              &nbsp; 添加小节
            </el-button>
            <el-button class="btn_operate" v-if="data.depth === '1'" @click="handleShowKnowledgeGraph(node)">
              <el-icon><Plus /></el-icon>
              &nbsp; 知识点脑图
            </el-button>
            <template v-if="data.depth === '2'">
              <el-button
                class="btn_operate"
                v-for="(item, index) in btnList"
                :key="index"
                @click="handleAddDialog(node, item, data)">
                <el-icon><Plus /></el-icon>
                {{ item.btn_name }}
              </el-button>
            </template>
            <template
              v-if="
                data.depth === '3' &&
                node.data.resource_type !== '2' &&
                node.data.resource_type !== '6' &&
                node.data.resource_type !== '3' &&
                node.data.resource_type !== '9' &&
                node.data.resource_type !== '13' &&
                node.data.resource_type !== '14'
              ">
              <span class="btn_operate">学生下载控制：</span>
              <el-switch
                class="btn_edit"
                v-if="
                  data.depth === '3' &&
                  node.data.resource_type !== '2' &&
                  node.data.resource_type !== '6' &&
                  node.data.resource_type !== '3' &&
                  node.data.resource_type !== '9'
                "
                v-model="node.data.can_download"
                size="large"
                active-value="1"
                inactive-value="0"
                inline-prompt
                style="--el-switch-on-color: #aa1941"
                @change="handleChangeStatus(node, data)"></el-switch>
            </template>
          </span>
        </span>
      </template>
    </el-tree>
    <div class="btn-box" style="display: flex; justify-content: center">
      <el-button type="primary" @click="router.push({ path: '/course/update-course', query: { id: id } })"
        >上一步</el-button
      >
      <el-button type="primary" @click="router.push('/course/my')">保存</el-button>
      <el-button type="primary"><a :href="`/course/my/preview?id=${id}`" target="_blank">预览</a></el-button>
    </div>
  </AppCard>
  <!-- 更改资源名称 -->
  <EditResourcesName
    v-if="isEditResourcesNameDialog === true"
    v-model:isEditResourcesNameDialog="isEditResourcesNameDialog"
    @create="handleFresh"
    :chapterName="chapterName"
    :chapterID="chapterID"
    :course_id="id"
    :sectionName="sectionName"
    :resourceId="resourceId" />
  <!-- 添加章 -->
  <AddChapterDialog
    v-if="isShowDialog === true"
    v-model:isShowDialog="isShowDialog"
    @create="handleFresh"
    :course_id="id"
    :isEdit="isEdit"
    :chapterID="chapterID"
    :chapterName="chapterName" />
  <!-- 添加小节 -->
  <AddSectionDialog
    v-if="isShowSectionDialog === true"
    v-model:isShowSectionDialog="isShowSectionDialog"
    @create="handleFresh"
    :chapterName="chapterName"
    :chapterID="chapterID"
    :course_id="id"
    :isEdit="isEdit"
    :sectionName="sectionName" />
  <!-- 添加直播 -->
  <AddLiveDialog
    v-if="isShowLiveDialog === true"
    v-model:isShowLiveDialog="isShowLiveDialog"
    @create="handleFresh"
    :chapterName="chapterName"
    :chapterID="chapterID"
    :course_id="id"
    :btnInfo="btnInfo" />
  <!-- 添加资源 -->
  <AddVideoDialog
    v-if="isShowAddDialog === true"
    v-model:isShowAddDialog="isShowAddDialog"
    @create="handleFresh"
    :chapterName="chapterName"
    :chapterID="chapterID"
    :course_id="id"
    :btnInfo="btnInfo" />

  <!-- 添加考试 -->
  <AddExamDialog
    v-if="isShowExamDialog === true"
    v-model:isShowExamDialog="isShowExamDialog"
    @create="handleFresh"
    :chapterName="chapterName"
    :chapterID="chapterID"
    :course_id="id"
    :btnInfo="btnInfo"
    :paper_use_list="paper_use_list"
    :isMultiple="false" />
  <!-- 视频查阅弹框 -->
  <VideoPlayDialog
    v-if="isShowVideoPlayDialog === true"
    v-model:isShowVideoPlayDialog="isShowVideoPlayDialog"
    :videoOptions="videoUrl" />
  <OpenRules
    v-model:isShowOpenRules="isShowOpenRules"
    v-if="isShowOpenRules === true"
    :chapterName="chapterName"
    :sectionName="sectionName"
    :chapterID="chapterID"
    :course_id="id"
    :controlInfo="controlInfo"
    @create="handleFresh" />
  <AddTextbookDialog
    v-if="isShowTextbookDialog === true"
    v-model:isShowTextbookDialog="isShowTextbookDialog"
    @create="handleFresh"
    :chapterName="chapterName"
    :chapterID="chapterID"
    :course_id="id" />
  <AddGraphbookDialog
    v-if="isShowTextbookDialog2 === true"
    v-model:isShowTextbookDialog2="isShowTextbookDialog2"
    @create="handleFresh"
    :chapterName="chapterName"
    :chapterID="chapterID"
    :course_id="id" />
  <AddKnowledge
    v-model="isShowKnowledgeDialog"
    @create="handleFresh"
    :chapterName="chapterName"
    :chapterId="chapterID"
    :courseId="id"
    :parentId="parentID"
    v-if="isShowKnowledgeDialog === true" />
  <!-- 知识图谱预览 -->
  <KnowledgeGraphPreview
    v-if="isShowKnowledgeGraphPreview === true"
    v-model:isShowKnowledgeGraphPreview="isShowKnowledgeGraphPreview"
    :courseId="id"
    :chapterId="currentChapterId"
    :title="knowledgeGraphTitle" />
</template>

<style>
.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>
