<template>
  <div class="resourcesList">
    <div class="headCon">
      <div class="headLeft">
        <img class="tipImg" src="@/views/Editor/CanvasTool/imgs/zyk.png" alt="" />
        <div class="title">资源库</div>
      </div>
      <div class="headright">
        <img @click="emits('close')" class="closeBtn" src="../../cloudCoachElement/cloudCoachList/imgs/close.png" alt="" />
      </div>
    </div>
    <div class="content">
      <div class="tabTools">
        <div class="tabCon">
          <div
            class="tab"
            @click="handleTabChange(item.value)"
            :class="{ active: item.value === queryData.sourceType }"
            v-for="item in tabData"
            :key="item.value"
          >
            {{ item.label }}
          </div>
        </div>
        <div></div>
      </div>
      <div class="typeTools">
        <div class="typeTabCon">
          <div
            v-for="item in resourcesTypeOption"
            :key="item.value"
            @click="handleTypeChange(item.value)"
            :class="['queryTip', queryData.type === item.value && 'active']"
          >
            {{ item.text }}
          </div>
        </div>
        <div class="query">
          <Input :placeholder="'请输入搜索关键词'" clearable v-model:value="queryData.name" @enter="handleQuery" @clear="handleQuery">
            <template #prefix>
              <img class="img" src="../../cloudCoachElement/cloudCoachList/imgs/query.png" alt="" />
            </template>
            <template #suffix>
              <div class="queryBtn" @click="handleQuery">搜索</div>
            </template>
          </Input>
        </div>
      </div>
      <div class="musicListCon">
        <div class="queryFrom" :class="{ isExpandAct: !isExpand }">
          <div class="queryFromList">
            <div class="tit">乐器：</div>
            <div class="queryFromCon">
              <template v-for="item in subjectList">
                <div
                  :class="['queryTip', queryData.subject.id === item.instruments[0].id && 'active']"
                  @click="handleSubjectChange(item.instruments[0])"
                  v-if="item.instruments.length === 1"
                  :key="item.id"
                >
                  {{ item.instruments[0].name }}
                </div>
                <Popover v-model:value="item.isExpand" trigger="mouseenter" :placement="'bottom-start'" v-else :offset="-4" :key="item.id + '_'">
                  <template #content>
                    <PopoverMenuItem
                      @click="
                        () => {
                          item.isExpand = false
                          handleSubjectChange(row)
                        }
                      "
                      v-for="row in item.instruments"
                      :key="row.id"
                      :active="row.id === queryData.subject.id"
                      >{{ row.name }}</PopoverMenuItem
                    >
                  </template>
                  <div class="queryTip" :class="{ hoverActive: isActiveSubjectPop(item) }">
                    <div>{{ isActiveSubjectPop(item) ? queryData.subject.name : item.name }}</div>
                    <img src="../../cloudCoachElement/cloudCoachList/imgs/jt.png" alt="" />
                  </div>
                </Popover>
              </template>
            </div>
          </div>
          <div class="queryFromList">
            <div class="tit">标签：</div>
            <div class="queryFromCon">
              <div
                v-for="item in materialTagList"
                :key="item.id"
                @click="handleMaterialTagChange(item.id)"
                :class="['queryTip', queryData.materialTagId === item.id && 'active']"
              >
                {{ item.name }}
              </div>
            </div>
          </div>
        </div>
        <!-- <div v-show="queryData.sourceType === 2" @click="isExpand = !isExpand" class="isExpand" :class="{ active: isExpand }">
          <div>{{ isExpand ? "收起" : "展开" }}</div>
          <img src="../../cloudCoachElement/cloudCoachList/imgs/jiao.png" alt="" />
        </div> -->
        <div class="musicListConBox" v-loading="loading">
          <div class="musicList" :class="{ empty: !musicList.length && !loading }">
            <div class="musicListBox" v-if="musicList.length && !loading">
              <div class="musicCon" v-for="item in musicList" :key="item.id" @click="handlePreview(item)">
                <div class="coverImgCon">
                  <img v-if="item.sourceFrom === 'PLATFORM'" class="jxImg" src="./imgs/jxImg.png" alt="" />
                  <div class="addBtn" @click.stop="handleAddResources(item)">添加</div>
                  <img class="coverImg" :src="item.coverImg" />
                </div>
                <div class="musicDetails">
                  <div class="musLeft">
                    <img class="labelImg" :src="item.type === 'IMG' ? imgImg : item.type === 'SONG' ? audioImg : videoImg" />
                    <div class="musicTitCon">
                      <EllipsisScroll class="musicTit" :title="item.highName || ''" />
                    </div>
                  </div>
                  <div class="musRight">
                    <img
                      v-if="queryParams.fromType !== 'PLATFORM'"
                      class="sc"
                      @click.stop="handleFavorite(item)"
                      :src="item.favoriteFlag ? scActImg : scImg"
                      alt=""
                    />
                  </div>
                </div>
              </div>
            </div>
            <Empty v-if="!musicList.length && !loading" />
          </div>
          <div class="pagination" v-show="musicList.length">
            <el-pagination
              layout="prev, pager, next"
              :default-page-size="queryData.rows"
              :current-page="queryData.page"
              @current-change="handleCurrentChange"
              :total="queryData.total"
            />
          </div>
        </div>
      </div>
    </div>
    <Modal
      :contentStyle="{
        width: previewData.type === 'IMG' ? '900px' : '800px',
        height: previewData.type === 'IMG' ? '700px' : '500px',
        boxShadow: '0px 2px 10px 0px rgba(0,0,0,0.08)',
        borderRadius: '12px',
        padding: '0'
      }"
      v-model:visible="previewData.previewVisible"
    >
      <div class="previewContent">
        <div class="preHeadCon">
          <div class="headTitle">{{ previewData.name }}</div>
          <div class="headright">
            <img @click="previewData.previewVisible = false" class="closeBtn" src="../../cloudCoachElement/cloudCoachList/imgs/close.png" alt="" />
          </div>
        </div>
        <div class="preCon">
          <img v-if="previewData.type === 'IMG'" class="coverImg" :src="previewData.content" />
          <template v-else-if="previewData.type === 'SONG'">
            <img class="coverImg" :src="previewData.coverImg" />
            <div class="controller-mask"></div>
            <AudioPlayer class="audioPlayer" :src="previewData.content" :loop="false" />
          </template>
          <VideoPlayer v-else-if="previewData.type === 'VIDEO'" class="videoPlayer" :src="previewData.content" :width="100" :height="100" />
        </div>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ElLoading, ElPagination } from "element-plus"
import Input from "@/components/Input.vue"
import Popover from "@/components/Popover.vue"
import PopoverMenuItem from "@/components/PopoverMenuItem.vue"
import Empty from "@/components/Empty"
import EllipsisScroll from "@/components/ellipsisScroll"
import { reactive, ref } from "vue"
import { getMaterialQueryPage, getSubjectListApi, favoriteApi, getMaterialTagApi } from "@/api/pptOperate"
import { httpAjax } from "@/plugins/httpAjax"
import queryParams from "@/queryParams"
import scActImg from "../../cloudCoachElement/cloudCoachList/imgs/scAct.png"
import scImg from "../../cloudCoachElement/cloudCoachList/imgs/sc.png"
import audioImg from "./imgs/audio.png"
import imgImg from "./imgs/img.png"
import videoImg from "./imgs/video.png"
import { CODE_ERR_CANCELED } from "@/libs/auth"
import Modal from "@/components/Modal.vue"
import AudioPlayer from "../../AudioElement/AudioPlayer.vue"
import VideoPlayer from "../../VideoElement/VideoPlayer/index.vue"

const emits = defineEmits<{
  (event: "update", item: Record<string, any>): void
  (event: "close"): void
}>()

function handleAddResources(item: Record<string, any>) {
  emits("update", item)
}

const previewData = reactive({
  previewVisible: false,
  type: "",
  name: "",
  content: "",
  coverImg: ""
})

function handlePreview(item: Record<string, any>) {
  previewData.previewVisible = true
  previewData.type = item.type
  previewData.name = item.name
  previewData.content = item.content
  previewData.coverImg = item.coverImg
}

const tabData =
  queryParams.fromType === "PLATFORM"
    ? [
        {
          label: "共享资源",
          value: 1
        }
      ]
    : [
        {
          label: "相关资源",
          value: 5
        },
        {
          label: "共享资源",
          value: 2
        },
        {
          label: "我的资源",
          value: 3
        },
        {
          label: "我的收藏",
          value: 4
        }
      ]
// 资源类型
const resourcesTypeOption = [
  { text: "图片", value: "IMG" },
  { text: "音频", value: "SONG" },
  { text: "视频", value: "VIDEO" }
]
// 标签
const materialTagList = ref<any[]>([])
// 乐器
const subjectList = ref<any[]>([])

const queryData = reactive({
  page: 1,
  rows: 20,
  total: 0,
  type: "IMG",
  materialTagId: "",
  sourceType: tabData[0].value,
  name: "",
  subject: {
    id: "",
    name: ""
  }
})

const musicList = ref<any[]>([])
const loading = ref(true)
const vLoading = ElLoading.directive
const isExpand = ref(true)

getQueryList()
function getQueryList() {
  Promise.all([httpAjax(getSubjectListApi), httpAjax(getMaterialTagApi)]).then(res => {
    const [subjectListRes, materialTagRes] = res
    if (subjectListRes.code === 200) {
      subjectList.value = subjectListRes.data.map((item: any) => {
        return item.instruments.length > 1 ? Object.assign(item, { isExpand: ref(false) }) : item
      })
      // 赋默认值
      handleSubjectDefault()
    }
    if (materialTagRes.code === 200) {
      materialTagList.value = [{ id: "", name: "全部" }, ...(materialTagRes.data?.rows || [])]
    }
    handleQuery()
  })
}
function handleSubjectDefault() {
  if (subjectList.value.length > 0) {
    const instruments = subjectList.value.reduce((arr, item) => {
      arr.push(...item.instruments)
      return arr
    }, [])
    const instrumentId = queryParams.instrumentId
    // 有id 就用id，没有就默认第一个
    const instrumentObj = instrumentId
      ? instruments.find((i: any) => {
          return i.id === instrumentId
        })
      : instruments[0]
    if (instrumentObj) {
      queryData.subject.id = instrumentObj.id
      queryData.subject.name = instrumentObj.name
    }
  }
}
function clearQueryData() {
  queryData.page = 1
  queryData.rows = 20
  queryData.total = 0
  queryData.name = ""
  queryData.materialTagId = ""
  queryData.subject = {
    id: "",
    name: ""
  }
  handleSubjectDefault()
}
function handleTabChange(sourceType: number) {
  clearQueryData()
  isExpand.value = true
  queryData.sourceType = sourceType
  handleQuery()
}
function handleSubjectChange(item: any) {
  queryData.subject.id = item.id
  queryData.subject.name = item.name
  handleQuery()
}
function handleMaterialTagChange(id: string) {
  queryData.materialTagId = id
  handleQuery()
}
function handleTypeChange(type: string) {
  queryData.type = type
  handleQuery()
}
function isActiveSubjectPop(item: any) {
  return item.instruments.some((i: any) => {
    return i.id === queryData.subject.id
  })
}

function handleCurrentChange(e: number) {
  queryData.page = e
  handleGetQuery()
}
function handleQuery() {
  queryData.page = 1
  queryData.rows = 20
  handleGetQuery()
}

let controller: AbortController
function handleGetQuery() {
  loading.value = true
  let { sourceType, subject, type, materialTagId, name, page, rows } = queryData
  let musicalInstrumentId = subject.id
  const params = {
    name,
    type,
    sourceType,
    musicalInstrumentId,
    enableFlag: true,
    page,
    rows,
    materialTagId,
    lessonCoursewareKnowledgeId: [2, 5].includes(sourceType) ? queryParams.lessonCoursewareKnowledgeId : "" // 相关资源和共享资源需要这个
  }
  if (controller) {
    controller.abort()
  }
  controller = new AbortController()
  httpAjax(getMaterialQueryPage, params, controller).then(res => {
    // 自己关闭的时候不取消加载
    if (res.code === CODE_ERR_CANCELED) {
      return
    }
    if (res.code === 200) {
      musicList.value = res.data.rows.map((item: any) => {
        item.highName = highlightedText(item.name, queryData.name)
        return item
      })
      queryData.total = res.data.total
    }
    loading.value = false
  })
}

function handleFavorite(item: any) {
  httpAjax(favoriteApi, {
    favoriteFlag: item.favoriteFlag ? 0 : 1,
    materialId: item.id,
    type: item.type
  }).then(res => {
    if (res.code === 200) {
      item.favoriteFlag = !item.favoriteFlag
    }
  })
}
const highlightedText = (text: string, query: string) => {
  if (!text) {
    return ""
  }
  if (!query) {
    return text
  }
  const regex = new RegExp(`(${query})`, "gi")
  return text.replace(regex, '<span class="highlighted">$1</span>')
}
</script>

<style lang="scss" scoped>
.resourcesList {
  width: 100%;
  height: 100%;
  .headCon {
    width: 100%;
    height: 64px;
    border-bottom: 1px solid #eaeaea;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .headLeft {
      margin-left: 30px;
      display: flex;
      align-items: center;
      .tipImg {
        width: 24px;
        height: 24px;
      }
      .title {
        font-weight: 600;
        font-size: 18px;
        color: #131415;
        margin-left: 8px;
      }
    }
    .headright {
      margin-right: 30px;
      display: flex;
      align-items: center;
      .closeBtn {
        width: 24px;
        height: 24px;
        cursor: pointer;
        &:hover {
          opacity: 0.8;
        }
      }
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 64px);
    display: flex;
    flex-direction: column;
    .tabTools {
      flex-shrink: 0;
      width: 100%;
      padding: 24px 30px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .tabCon {
        display: flex;
        .tab {
          margin-right: 32px;
          font-weight: 400;
          font-size: 16px;
          color: #8b8d98;
          line-height: 22px;
          cursor: pointer;
          &:hover {
            opacity: 0.8;
          }
          &:last-child {
            margin-right: 0;
          }
          &.active {
            font-weight: 600;
            color: #131415;
            position: relative;
            &::after {
              content: "";
              position: absolute;
              width: 100%;
              height: 10px;
              background: linear-gradient(90deg, #77bbff 0%, rgba(163, 231, 255, 0.22) 100%);
              bottom: 0;
              left: 0;
              z-index: -1;
            }
          }
        }
      }
    }
    .typeTools {
      flex-shrink: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0 30px;
      padding-bottom: 16px;
      border-bottom: 1px solid #eaeaea;
      .typeTabCon {
        display: flex;
        align-items: center;
        .queryTip {
          margin-right: 16px;
          font-weight: 400;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.6);
          line-height: 20px;
          padding: 6px 20px;
          background: #f5f6fa;
          border-radius: 16px;
          cursor: pointer;
          &:hover {
            background: #e8e9ed;
            color: #5d5d5e;
          }
          &.active {
            background: #198cfe;
            color: #ffffff;
          }
        }
      }
      .query {
        width: 400px;
        height: 36px;
        &::v-deep(.input) {
          align-items: center;
          padding: 0 3px 0 12px;
          border-radius: 18px;
          height: 100%;
          &:not(.disabled):hover,
          &.focused {
            .img {
              opacity: 1;
            }
            .queryBtn {
              opacity: 1;
            }
          }
          input {
            font-size: 14px;
          }
          .img {
            width: 16px;
            height: 16px;
            opacity: 0.4;
          }
          .queryBtn {
            width: 60px;
            height: 30px;
            background: #198cfe;
            border-radius: 16px;
            font-weight: 500;
            font-size: 14px;
            color: #ffffff;
            line-height: 30px;
            text-align: center;
            opacity: 0.4;
            cursor: pointer;
            &:hover {
              opacity: 0.8 !important;
            }
          }
        }
      }
    }
    .musicListCon {
      padding-top: 16px;
      width: 100%;
      flex-grow: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      .queryFrom {
        &.isExpandAct {
          height: 42px;
          overflow: hidden;
        }
        flex-shrink: 0;
        padding: 0 30px;
        .queryFromList {
          display: flex;
          margin-bottom: 4px;
          .tit {
            flex-shrink: 0;
            font-weight: 500;
            font-size: 14px;
            color: #131415;
            line-height: 32px;
            margin-right: 16px;
          }
          .queryFromCon {
            display: flex;
            flex-wrap: wrap;
            .queryTip {
              margin: 0 16px 12px 0;
              font-weight: 400;
              font-size: 14px;
              color: rgba(0, 0, 0, 0.6);
              line-height: 20px;
              padding: 6px 16px;
              background: #f5f6fa;
              border-radius: 6px;
              cursor: pointer;
              display: flex;
              align-items: center;
              & > img {
                width: 7px;
                height: 4px;
                margin-left: 6px;
              }
              &:hover {
                background: #e8e9ed;
                color: #5d5d5e;
                > img {
                  transform: rotate(180deg);
                }
              }
              &.active {
                background: #d2ecff;
                color: rgba(0, 0, 0, 1);
              }
              &.hoverActive {
                background: #d2ecff;
                color: rgba(0, 0, 0, 1);
              }
            }
          }
        }
      }
      .isExpand {
        flex-shrink: 0;
        margin-bottom: 12px;
        cursor: pointer;
        display: flex;
        justify-content: center;
        font-weight: 400;
        font-size: 14px;
        color: #198cfe;
        line-height: 20px;
        align-items: center;
        &:hover {
          opacity: 0.8;
        }
        &.active > img {
          transform: rotate(0deg);
        }
        & > img {
          transform: rotate(180deg);
          margin-left: 4px;
          width: 10px;
          height: 10px;
        }
      }
      .musicListConBox {
        flex-grow: 1;
        overflow: hidden;
        .musicList {
          padding: 4px 0;
          height: calc(100% - 60px);
          overflow: auto;
          &.empty {
            display: flex;
            justify-content: center;
            align-items: center;
          }
          .musicListBox {
            width: calc(100% + 24px);
            margin-left: -24px;
            display: flex;
            flex-wrap: wrap;
            padding: 0 30px;
            .musicCon {
              margin-bottom: 24px;
              width: calc(25% - 24px);
              margin-left: 24px;
              border-radius: 12px;
              background: linear-gradient(0, #dbf1ff 0%, #e7f9ff 100%);
              outline: 1.5px solid #d3eef1;
              height: 213px;
              display: flex;
              flex-direction: column;
              overflow: hidden;
              cursor: pointer;
              &:nth-last-child(-n + 4) {
                margin-bottom: 0;
              }
              &:hover {
                outline: 2px solid #198cfe;
              }
              .coverImgCon {
                flex-shrink: 0;
                width: 100%;
                height: 170px;
                position: relative;
                .coverImg {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                  object-position: top;
                }
                .jxImg {
                  position: absolute;
                  left: 0px;
                  top: 0px;
                  width: 50px;
                  height: 27px;
                }
                .addBtn {
                  position: absolute;
                  top: 8px;
                  right: 12px;
                  width: 54px;
                  height: 26px;
                  background: #198cfe;
                  border-radius: 4px;
                  font-weight: 600;
                  font-size: 13px;
                  color: #ffffff;
                  line-height: 26px;
                  text-align: center;
                  cursor: pointer;
                  &:hover {
                    opacity: 0.8;
                  }
                }
              }
              .musicDetails {
                flex-grow: 1;
                padding: 0 12px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                .musLeft {
                  display: flex;
                  align-items: center;
                  margin-right: 14px;
                  overflow: hidden;
                  .labelImg {
                    flex-shrink: 0;
                    width: 16px;
                    height: 16px;
                  }
                  .musicTitCon {
                    margin-left: 6px;
                    overflow: hidden;
                    .musicTit {
                      font-weight: 600;
                      font-size: 14px;
                      color: #131415;
                      line-height: 20px;
                      &::v-deep(.highlighted) {
                        color: $themeColor;
                      }
                    }
                  }
                }
                .musRight {
                  flex-shrink: 0;
                  .sc {
                    width: 26px;
                    height: 26px;
                    cursor: pointer;
                    &:hover {
                      opacity: 0.8;
                    }
                  }
                }
              }
            }
          }
        }
        .pagination {
          padding: 0 30px;
          display: flex;
          justify-content: flex-end;
          align-items: center;
          height: 60px;
        }
      }
    }
  }
}
.previewContent {
  width: 100%;
  height: 100%;
  .preHeadCon {
    display: flex;
    justify-content: flex-end;
    height: 50px;
    position: relative;
    .headTitle {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      font-weight: 600;
      font-size: 18px;
      color: #131415;
      width: 600px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: center;
    }
    .headright {
      display: flex;
      align-items: center;
      margin-right: 20px;
      .closeBtn {
        width: 24px;
        height: 24px;
        cursor: pointer;
        &:hover {
          opacity: 0.8;
        }
      }
    }
  }
  .preCon {
    width: 100%;
    height: calc(100% - 50px);
    position: relative;
    .coverImg {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
    .controller-mask {
      background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAADGCAYAAAAT+OqFAAAAdklEQVQoz42QQQ7AIAgEF/T/D+kbq/RWAlnQyyazA4aoAB4FsBSA/bFjuF1EOL7VbrIrBuusmrt4ZZORfb6ehbWdnRHEIiITaEUKa5EJqUakRSaEYBJSCY2dEstQY7AuxahwXFrvZmWl2rh4JZ07z9dLtesfNj5q0FU3A5ObbwAAAABJRU5ErkJggg==)
        repeat-x bottom;
      height: 98px;
      width: 100%;
      position: absolute;
      bottom: 0;
    }
    .audioPlayer {
      width: 100%;
      position: absolute;
      left: 0;
      bottom: 0;
      background: transparent;
    }
    .videoPlayer {
      width: 100% !important;
      height: 100% !important;
    }
  }
}
</style>
