<template>
  <el-dialog
    custom-class="select-resource-dialog"
    title="选择资源"
    :visible="visible"
    :close-on-click-modal="false"
    @close="dialogClose"
    append-to-body
  >
    <div class="search-box">
      <div class="search-left">
        <el-input v-model="search_content" />
        <el-button type="primary" @click="queryList()">查询</el-button>
      </div>
      <div class="search-right">
        <label>排序：</label>
        <el-select v-model="sort_value" placeholder="请选择">
          <el-option v-for="item in sort_list" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <SvgIcon :icon-class="isDesc ? 'sort-down' : 'sort-up'" size="16" style="cursor: pointer" @click="changeSort" />
      </div>
    </div>

    <div v-loading="loading" class="sources-box">
      <div
        v-for="(item, index) in list"
        :key="index"
        class="sources-item"
        :class="[select_sources_id === item.id ? 'active' : '']"
        @click="selectSourceNode(item)"
      >
        <template v-if="type_index === 0"> <el-image :src="item.file_url" fit="contain" /></template>
        <template v-else-if="type_index === 1">
          <div class="sources-item-border sources-item-audio">
            <SvgIcon icon-class="mp3" size="16" />
            <span>{{ realFormatSecond(item.media_duration) }}</span>
            <SvgIcon icon-class="play-large-fill" size="16" @click="viewDialog(item)" />
          </div>
        </template>
        <template v-else-if="type_index === 2">
          <video
            class="sources-item-border"
            :src="item.file_url"
            width="100%"
            height="140px"
            :poster="item.video_preview_image_file_url"
            preload="none"
          ></video>
        </template>
        <template v-else-if="type_index === 3">
          <el-image style="height: 90px" :src="require('@/assets/h5-games.png')" fit="contain" />
        </template>
        <template v-else-if="type_index === 4">
          <el-image style="height: 90px" :src="require('@/assets/3d-model.png')" fit="contain" />
        </template>
        <template v-else-if="type_index === 5">
          <el-image style="height: 90px" :src="require('@/assets/txt.png')" fit="contain" />
        </template>

        <el-popover placement="bottom" width="300" trigger="hover">
          <div class="sources-info">
            <p class="name">名称：{{ item.name }}</p>
            <p class="label">标签：{{ item.label }}</p>
            <p class="name">简介：{{ item.intro }}</p>
            <p class="label">修改时间：{{ item.last_modify_time }}</p>
            <p class="label">文件大小：{{ item.file_size_desc }}</p>
          </div>
          <template #reference>
            <div class="sources-info">
              <p class="name">
                {{ item.name
                }}<SvgIcon v-show="item.file_id" icon-class="uploadPreview" size="16" @click="viewDialog(item)" />
              </p>
              <b class="label">{{ item.label }}</b>
            </div>
          </template>
        </el-popover>
      </div>
    </div>
    <PaginationPage ref="pagination" :total="total" @getList="queryList" />

    <div slot="footer">
      <el-button @click="dialogClose">取消</el-button>
      <el-button type="primary" @click="confirmSelect">选择</el-button>
    </div>
    <el-dialog
      v-if="visible_flag"
      :visible.sync="visible_flag"
      :show-close="true"
      :close-on-click-modal="true"
      :modal-append-to-body="true"
      :append-to-body="true"
      :lock-scroll="true"
      width="80%"
      top="0"
    >
      <iframe v-if="visible_flag" :src="newpath" width="100%" :height="iframeHeight" frameborder="0"></iframe>
    </el-dialog>
  </el-dialog>
</template>

<script>
import PaginationPage from '@/components/PaginationPage.vue';

import { PageQueryProjectResourceList } from '@/api/list';
import { H5StartupFile } from '@/api/app';

const Base64 = require('js-base64').Base64;
import { getConfig } from '@/utils/auth';

export default {
  name: 'SelectResource',
  components: {
    PaginationPage,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 教材 id
    projectId: {
      type: String,
      default: '',
    },
    // 课件 id
    coursewareId: {
      type: String,
      default: '',
    },
    // 允许的文件类型
    accept: {
      type: String,
      default: '*',
    },
  },
  data() {
    const type_list = [
      {
        value: 0,
        key: 'image',
        label: '图片',
      },
      {
        value: 1,
        key: 'audio',
        label: '音频',
      },
      {
        value: 2,
        key: 'video',
        label: '视频',
      },
      {
        value: 3,
        key: 'h5_game',
        label: 'H5 游戏',
      },
      {
        value: 4,
        key: '3d_model',
        label: '3D 模型',
      },
      {
        value: 5,
        key: 'text',
        label: '文本',
      },
    ];

    return {
      loading: false,
      list: [],
      total: 0,
      page_capacity: 10,
      cur_page: 1,
      type_list,
      type_index: type_list.findIndex((item) => item.key === this.accept) || 0,
      sort_list: [
        {
          value: 'name',
          label: '名称',
        },
        {
          value: 'label',
          label: '标签',
        },
        {
          value: 'last_modify_time',
          label: '修改时间',
        },
        {
          value: 'file_size',
          label: '文件大小',
        },
      ], // 排序分类
      sort_value: '', // 排序值
      isDesc: false, // 排序是否为倒序
      search_content: '',
      select_sources_id: '',
      visible_flag: false,
      newpath: '',
      iframeHeight: `${window.innerHeight - 100}px`,
      file_preview_url: getConfig() ? getConfig().doc_preview_service_address : '',
    };
  },
  created() {},
  methods: {
    dialogClose() {
      this.$emit('update:visible', false);
      this.$emit('close');
    },
    // 查询列表
    queryList(data) {
      this.loading = true;
      this.list = [];
      if (data) {
        this.page_capacity = data.page_capacity;
        this.cur_page = data.cur_page;
      } else {
        this.page_capacity = 10;
        this.cur_page = 1;
      }

      let order_column_list = [];
      if (this.sort_value) {
        order_column_list = [this.isDesc ? `${this.sort_value}:desc` : this.sort_value];
      }
      PageQueryProjectResourceList({
        page_capacity: this.page_capacity,
        cur_page: this.cur_page,
        project_id: this.projectId,
        book_chapter_node_id: this.coursewareId,
        is_search_parent_node_resource: 'true',
        type: this.type_list[this.type_index].value,
        name_or_label: this.search_content,
        order_column_list,
      })
        .then(({ total_count, resource_list }) => {
          this.total = total_count;
          // if (this.type_index === 5) {
          //   resource_list.forEach((item) => {
          //     item.new_path = `${this.file_preview_url}onlinePreview?url=${Base64.encode(item.file_url)}`;
          //   });
          //   this.loading = false;
          // }
          // else if (this.type_index === 3) {
          //   resource_list.forEach((item) => {
          //     H5StartupFile({ file_id: item.file_id, index_file_name: 'index.html' }).then((res) => {
          //       item.new_path = res.file_url;
          //       this.loading = false;
          //     });
          //   });
          // }
          // else {
          this.loading = false;
          // }
          this.list = resource_list;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    selectSourceNode(item) {
      this.select_sources_id = item.id;
    },
    // 切换排序升序降序
    changeSort() {
      this.isDesc = !this.isDesc;
    },
    // 将整数转换成 时：分：秒的格式
    realFormatSecond(value) {
      let theTime = parseInt(value); // 秒
      let theTime1 = 0; // 分
      let theTime2 = 0; // 小时
      if (theTime > 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (theTime1 > 60) {
          theTime2 = parseInt(theTime1 / 60);
          theTime1 = parseInt(theTime1 % 60);
        }
      }
      let result = String(parseInt(theTime));
      if (result < 10) {
        result = `0${result}`;
      }
      if (theTime1 > 0) {
        result = `${String(parseInt(theTime1))}:${result}`;
        if (theTime1 < 10) {
          result = `0${result}`;
        }
      } else {
        result = `00:${result}`;
      }
      if (theTime2 > 0) {
        result = `${String(parseInt(theTime2))}:${result}`;
        if (theTime2 < 10) {
          result = `0${result}`;
        }
      } else {
        // result = "00:" + result;
      }
      return result;
    },
    // 选择资源
    confirmSelect() {
      if (!this.select_sources_id) {
        this.$message.error('请选择资源');
        return;
      }
      const selectedResource = this.list.find((item) => item.id === this.select_sources_id);

      this.$emit('selectResource', {
        file_id: selectedResource.file_id,
        file_name: selectedResource.name,
        file_url: selectedResource.file_url,
        intro: selectedResource.intro,
      });
    },
    // 预览
    viewDialog(file) {
      this.newpath = '';
      if (this.type_index === 3) {
        const suffix = file.name.slice(file.name.lastIndexOf('.') + 1, file.name.length).toLowerCase();
        if (suffix === 'html') {
          this.newpath = file.file_url;
          this.visible_flag = true;
        } else {
          H5StartupFile({ file_id: file.file_id, index_file_name: 'index.html' }).then((res) => {
            this.newpath = res.file_url;
            this.visible_flag = true;
          });
        }
      } else {
        this.newpath = `${this.file_preview_url}onlinePreview?url=${Base64.encode(file.file_url)}`;
        this.visible_flag = true;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.select-resource-dialog {
  .search-box {
    display: flex;
    justify-content: space-between;
    padding: 5px;

    .search-left {
      display: flex;
      flex-flow: wrap;
      gap: 5px;
      align-items: center;
    }

    .label-btn {
      padding: 5px 10px;
      cursor: pointer;
      background: #ebebeb;
      border-radius: 4px;

      &.active {
        color: #f90;
        background: #ffefd6;
      }
    }

    .el-input,
    .el-select {
      width: 120px;
    }
  }

  .sources-box {
    display: flex;
    flex-flow: wrap;
    gap: 10px;
    place-content: start start;
    height: 400px;
    padding: 5px;
    overflow: auto;

    .sources-item {
      width: 200px;
      cursor: pointer;

      &-txt {
        width: 400px;
      }

      &-zip {
        width: 500px;
      }

      &-border {
        border: 1px solid #ccc;
      }

      &-audio {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 9px 5px;
      }

      .el-image {
        width: 100%;
        height: 140px;
        border: 1px solid #ccc;
      }

      .name,
      .label {
        margin: 5px 0;
        font-size: 14px;
        font-weight: normal;
        line-height: 1.3;
      }

      :deep .audioLine {
        background: #f2f3f5;
      }

      &.active {
        .el-image,
        .sources-item-border {
          border-color: #f90;
        }

        .name,
        .label {
          color: #f90;
        }
      }
    }
  }
}
</style>
