<template>
  <div class="production-resource">
    <MenuPage cur-key="project" />

    <div class="production-resource-main">
      <div class="textbook-container">
        <MenuTree :id="select_node" :node-list="node_list" @selectNode="selectNode" />
      </div>
      <div class="textbook-chapter">
        <div class="textbook-chapter__header">
          <div class="courseware">
            <div class="operator flex">
              <span class="link" @click="handleAdd">上传</span>
              <span class="link" @click="handleDelete">删除</span>
              <span class="link" @click="handleSetInfo">设置信息</span>
              <span class="link" @click="handleChangeFile">更换文件</span>
              <span class="link" @click="handleMoveFile">移动文件</span>
              <span class="link" @click="handlePersonal">设置项目成员资源使用权限</span>
              <span class="link" @click="$router.push({ path: `/personal_workbench/project` })">返回项目列表</span>
            </div>
          </div>
        </div>
        <div class="search-box">
          <div class="search-left">
            <label
              class="label-btn"
              :class="[type_index === index ? 'active' : '']"
              v-for="(item, index) in type_list"
              :key="index"
              @click="changeType(index)"
              >{{ item.label }}</label
            >
            <el-input v-model="search_content"></el-input>
            <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-option
            ></el-select>
            <SvgIcon
              :icon-class="isDesc ? 'sort-down' : 'sort-up'"
              size="16"
              style="cursor: pointer"
              @click="changeSort"
            />
          </div>
        </div>
        <div class="sources-box" :style="{ height: height + 'px' }" v-if="height > 0" v-loading="boxLoading">
          <div
            v-for="(item, index) in list"
            :key="index"
            @click="selectSourceNode(item)"
            class="sources-item"
            :class="[select_sources_id === item.id ? 'active' : '']"
          >
            <template v-if="type_index === 0"> <el-image :src="item.file_url" fit="contain"></el-image></template>
            <template v-if="type_index === 1">
              <AudioLine
                ref="audioLine"
                :audio-id="'resource-audio-' + index"
                :mp3="item.file_url"
                :get-cur-time="getCurTime"
                :width="200"
              />
            </template>
            <template v-if="type_index === 2">
              <video controls :src="item.file_url" width="100%" height="140px"></video>
            </template>

            <p class="name">{{ item.name }}</p>
            <b class="label">{{ item.label }}</b>
          </div>
        </div>
        <PaginationPage ref="pagination" :total="total" @getList="queryList" />
      </div>
    </div>
    <!-- 上传 -->
    <el-dialog
      :visible.sync="sourceAddFlag"
      width="500px"
      append-to-body
      :show-close="true"
      title="上传资源"
      :close-on-click-modal="false"
      class="module-content"
    >
      <UploadFile
        key="upload_resources"
        :type="'upload_resources_manager'"
        :total-size="20000"
        :file-list="file_list"
        :file-id-list="file_id_list"
        :label-text="labelText"
        :accept-file-type="acceptFileType"
        :icon-class="iconClass"
        :limit="limit"
        :single-size="200"
        :uploadTip="uploadTip"
        @updateFileList="updateFileList"
      />
      <footer style="text-align: right">
        <el-button @click="handleCancle">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="submitAdd">确 定</el-button>
      </footer>
    </el-dialog>
    <!-- 更新信息 -->
    <el-dialog
      :visible.sync="sourceInfoFlag"
      width="500px"
      append-to-body
      :show-close="true"
      title="设置资源"
      :close-on-click-modal="false"
    >
      <el-form ref="form" label-width="80px" :model="sourceInfo">
        <el-form-item prop="name" label="名称">
          <el-input v-model="sourceInfo.name" />
        </el-form-item>
        <el-form-item prop="label" label="标签">
          <el-input v-model="sourceInfo.label" />
        </el-form-item>
        <el-form-item prop="intro" label="简介">
          <el-input v-model="sourceInfo.intro" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button @click="sourceInfoFlag = false">取 消</el-button>
          <el-button :loading="loading" type="primary" @click="submitSourceInfo">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import MenuPage from '../common/menu.vue';
import MenuTree from './components/MenuTree.vue';
import {
  ChapterGetBookChapterStruct,
  MangerAddResource,
  MangerDeleteResource,
  MangerUpdateResourceFile,
  MangerUpdateResourceInfo,
} from '@/api/book';
import { GetProjectBaseInfo } from '@/api/project';
import PaginationPage from '@/components/PaginationPage.vue';
import { PageQueryProjectResourceList } from '@/api/list';
import UploadFile from './components/UploadFile.vue';
import AudioLine from './components/AudioLine.vue';

export default {
  name: 'ProjectResourceManager',
  components: { MenuPage, MenuTree, PaginationPage, UploadFile, AudioLine },
  data() {
    return {
      book_id: this.$route.params.id,
      node_list: [],
      select_node: '',
      project_info: {}, // 项目基本信息
      type_list: [
        {
          value: 0,
          label: '图片',
        },
        {
          value: 1,
          label: '音频',
        },
        {
          value: 2,
          label: '视频',
        },
        {
          value: 3,
          label: 'H5 游戏',
        },
        {
          value: 4,
          label: '3D 模型',
        },
      ], // 类型分类
      type_index: 0, // 类型索引
      sort_list: [
        {
          value: 'name',
          label: '名称',
        },
        {
          value: 'label',
          label: '标签',
        },
        {
          value: 'last_modify_time',
          label: '修改时间',
        },
        {
          value: 'file_size',
          label: '文件大小',
        },
      ], // 排序分类
      sort_value: '', // 排序值
      isDesc: false, // 排序是否为倒序
      select_sources_id: '', // 选中的资源id
      list: [],
      total: 0,
      search_content: '', // 查询内容
      height: 0,
      page_capacity: 10,
      cur_page: 1,
      sourceAddFlag: false, // 新增flag
      labelText: '资源',
      acceptFileType: '.jpg,.png,.jpeg',
      iconClass: '',
      file_id_list: [],
      file_list: [],
      loading: false,
      acceptFileTypeList: ['.jpg,.png,.jpeg', '.mp3', '.mp4', '*', '*', '*'],
      limit: 10,
      uploadTip: '',
      boxLoading: false,
      sourceInfoFlag: false, // 设置信息
      sourceInfo: {
        name: '',
        label: '',
        intro: '',
      },
    };
  },
  created() {
    this.getProjectBaseInfo();
  },
  mounted() {
    this.height =
      document.getElementsByClassName('app-container')[0].clientHeight -
      document.getElementsByClassName('menu')[0].clientHeight -
      document.getElementsByClassName('textbook-chapter__header')[0].clientHeight -
      document.getElementsByClassName('search-box')[0].clientHeight -
      document.getElementsByClassName('el-pagination')[0].clientHeight -
      30;
  },
  methods: {
    selectNode(nodeId) {
      this.select_node = nodeId;
      this.queryList('');
    },
    /**
     * 获取项目基本信息
     * @param {string} id - 项目ID
     */
    getProjectBaseInfo() {
      GetProjectBaseInfo({ id: this.book_id }).then(({ project_info }) => {
        this.project_info = project_info;
        this.getBookChapterStructExpandList(project_info.name);
      });
    },
    /**
     * 得到教材章节结构展开列表
     */
    getBookChapterStructExpandList(name) {
      ChapterGetBookChapterStruct({
        book_id: this.book_id,
        node_deep_mode: 0,
        is_contain_producer: 'false',
        is_contain_auditor: 'false',
      }).then(({ nodes }) => {
        this.node_list = [
          {
            auditor_desc: '',
            deep: 1,
            id: '',
            is_courseware: 'false',
            is_leaf: 'false',
            is_leaf_chapter: 'false',
            level_index: '0',
            label: name,
            nodes: nodes,
            children: nodes,
          },
        ];
        this.handleData(this.node_list[0], 1);
      });
    },
    // 递归
    handleData(data, nodeIndex) {
      if (data.nodes) {
        data.nodes.forEach((item) => {
          item.label = item.name;
          item.pid = data.id;
          item.nodexIndex = nodeIndex;
          item.isLeaf = item.is_leaf === 'true';
          if (item.nodes) {
            item.children = item.nodes;
            item.lists = item.nodes;
            this.handleData(item, nodeIndex + 1);
          }
        });
      }
    },
    // 上传
    handleAdd() {
      this.limit = 10;
      this.uploadTip = '最多上传 10 个文件，多文件分批上传';
      this.sourceAddFlag = true;
    },
    // 删除
    handleDelete() {
      if (this.select_sources_id) {
        this.$confirm('确定要删除此条资源吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            MangerDeleteResource({ id: this.select_sources_id }).then(() => {
              this.$message.success('删除成功!');
              this.select_sources_id = '';
              this.queryList('');
            });
          })
          .catch(() => {});
      } else {
        this.$message.warning('请先选择文件');
      }
    },
    // 设置信息
    handleSetInfo() {
      if (this.select_sources_id) {
        this.sourceInfoFlag = true;
      } else {
        this.$message.warning('请先选择文件');
      }
    },
    // 更换文件
    handleChangeFile() {
      if (this.select_sources_id) {
        this.limit = 1;
        this.uploadTip = '只能上传 1 个文件';
        this.sourceAddFlag = true;
      } else {
        this.$message.warning('请先选择文件');
      }
    },

    // 设置项目成员资源使用权限
    handlePersonal() {},

    // 移动文件
    handleMoveFile() {},
    // 切换类型
    changeType(index) {
      this.type_index = index;
      this.select_sources_id = '';
      this.acceptFileType = this.acceptFileTypeList[index];
      this.queryList('');
    },
    // 查询列表
    queryList(data) {
      this.boxLoading = true;
      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];
      }
      let datas = {
        page_capacity: this.page_capacity,
        cur_page: this.cur_page,
        project_id: this.book_id,
        book_chapter_node_id: this.select_node,
        type: this.type_list[this.type_index].value,
        name_or_label: this.search_content,
        order_column_list: order_column_list,
      };
      PageQueryProjectResourceList(datas)
        .then(({ total_count, resource_list }) => {
          this.boxLoading = false;
          this.total = total_count;
          this.list = resource_list;
        })
        .catch(() => {
          this.boxLoading = false;
        });
    },

    // 切换排序升序降序
    changeSort() {
      this.isDesc = !this.isDesc;
    },
    updateFileList({ file_list, file_id_list }) {
      this.file_list = file_list;
      this.file_id_list = file_id_list;
    },
    handleCancle() {
      this.sourceAddFlag = false;
      this.file_list = [];
      this.file_id_list = [];
    },
    // 确定新增资源
    submitAdd() {
      this.loading = true;
      if (this.limit === 1) {
        // 更换文件
        let data = {
          id: this.select_sources_id,
          file_id: this.file_id_list[0],
        };
        MangerUpdateResourceFile(data)
          .then((res) => {
            this.loading = false;
            this.sourceAddFlag = false;
            if (res.status === 1) {
              this.$message.success('更换成功');
              this.queryList('');
            }
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        // 上传文件
        let data = {
          project_id: this.book_id,
          book_chapter_node_id: this.select_node,
          type: this.type_list[this.type_index].value,
          file_id_list: this.file_id_list,
        };
        MangerAddResource(data)
          .then((res) => {
            this.loading = false;
            this.sourceAddFlag = false;
            if (res.status === 1) {
              this.queryList('');
            }
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    // 点击资源
    selectSourceNode(item) {
      this.select_sources_id = item.id;
      this.sourceInfo = {
        name: item.name,
        label: item.label,
        intro: item.intro,
      };
    },
    getCurTime() {},
    // 更新信息确定按钮
    submitSourceInfo() {
      this.loading = true;
      MangerUpdateResourceInfo({
        id: this.select_sources_id,
        resource_info: this.sourceInfo,
      })
        .then((res) => {
          this.loading = false;
          this.sourceInfoFlag = false;
          if (res.status === 1) {
            this.$message.success('设置成功');
            this.queryList('');
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
@use '@/styles/mixin.scss' as *;

.production-resource {
  @include page-content(true);

  .production-resource-main {
    display: flex;
    flex: 1;
    width: 100%;
    height: 100%;
    background: #fff;
    border-top: $border;

    .textbook-container {
      display: flex;
      flex-direction: column;
      width: 320px;
      height: calc(100vh - 120px);
      overflow: auto;
      border-right: $border;
    }

    .textbook-chapter {
      display: flex;
      flex: 1;
      flex-direction: column;

      &__header {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        height: 40px;
        padding: 6px 4px;
        margin-bottom: 5px;
        background-color: #fff;
        border-bottom: 1px solid #e5e6eb;

        .operator {
          display: flex;
          flex: 1;
          justify-content: flex-end;

          .link {
            + .link {
              &::before {
                margin-right: 8px;
                color: #999;
                content: '|';
              }
            }
          }
        }
      }

      .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;
      padding: 5px;
      overflow: auto;

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

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

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

        :deep .audioLine {
          background: #f2f3f5;
        }

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

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