<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧分类菜单 -->
      <el-col :span="6">
        <el-form>
          <el-form-item prop="userName">
            <el-input
              v-model="deptFilterText"
              placeholder="输入部门名称过滤"
              clearable
              size="small"
              prefix-icon="el-icon-search"
            >
              <template slot="append">
                <el-button
                  slot="append"
                  icon="el-icon-refresh-right"
                  @click="refreshMenu"
                />
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-menu :default-active="defaultActive" @select="handleSelect">
          <!-- 内置标签 -->
          <el-menu-item
            v-for="(dept, index) in builtInDepts"
            :key="`built-in-${index}`"
            :index="`built-in-${index}`"
            class="custom-item"
          >
            <div class="left">
              <i :class="getBuiltInIcon(index)" />
              <span>{{ dept.label }}</span>
            </div>
            <!-- 内置标签无操作按钮 -->
          </el-menu-item>
          <!-- 自定义标签 -->
          <el-menu-item
            v-for="(dept, index) in filteredCustomDeptList"
            :key="`custom-${index}`"
            :index="`custom-${index}`"
            class="custom-item"
          >
            <div class="left">
              <i class="el-icon-collection-tag" />
              <span>{{ dept.label }}</span>
            </div>
            <div class="right">
              <el-button
                type="text"
                icon="el-icon-edit"
                @click.stop="handleEditTag(dept)"
              />
              <el-button
                type="text"
                icon="el-icon-delete"
                @click.stop="handleDeleteTag(dept)"
              />
            </div>
          </el-menu-item>
          <el-menu-item>
            <div class="left" @click.stop="handleAddTag">
              <i class="el-icon-edit-outline" />
              <span>自定义标签</span>
            </div>
          </el-menu-item>
        </el-menu>
      </el-col>

      <!-- 右侧资源列表 -->
      <el-col :span="18">
        <!-- 搜索区域 -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="文件名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入文件名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
            >
              搜索
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">
              重置
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-upload2"
              size="mini"
              @click="openUploadTypeDialog"
            >
              上传
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 资源列表 -->
        <el-table v-loading="loading" :data="userList">
          <el-table-column
            label="缩略图"
            prop="thumbnail"
            align="center"
            v-if="columns.thumbnail.visible"
            width="250"
          >
            <template slot-scope="scope">
              <el-image
                class="resource-thumb"
                :src="
                  scope.row.thumbnail || defaultThumbnail(scope.row.fileType)
                "
                fit="contain"
                @click="handlePreview(scope.row)"
              >
                <i slot="load" :class="getFileIcon(scope.row.fileType)" />
              </el-image>
            </template>
          </el-table-column>
          <el-table-column
            label="文件名"
            align="center"
            prop="userName"
            v-if="columns.userName.visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="上传时间"
            align="center"
            prop="createTime"
            v-if="columns.createTime.visible"
            width="200"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}上传</span>
            </template>
          </el-table-column>
          <el-table-column
            label="文件大小"
            align="center"
            prop="fileSize"
            v-if="columns.fileSize.visible"
            width="120"
          >
            <template slot-scope="scope">
              <span>{{ formatFileSize(scope.row.fileSize) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="240"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-share"
                @click="handleShare(scope.row)"
              >
                分享
              </el-button>
              <el-button
                type="text"
                icon="el-icon-edit"
                @click="handleUpdateFileName(scope.row)"
              >
                修改
              </el-button>
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 自定义标签弹窗 -->
    <el-dialog
      title="自定义标签名称"
      :visible.sync="tagDialogVisible"
      width="400px"
      destroy-on-close
    >
      <el-form
        :model="tagForm"
        :rules="tagRules"
        ref="tagFormRef"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="label">
          <el-input
            v-model="tagForm.label"
            placeholder="请输入最多8个字符"
            maxlength="8"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTagForm">确认</el-button>
        <el-button @click="cancelTagForm">取消</el-button>
      </div>
    </el-dialog>

    <!-- 修改文件名弹窗 -->
    <el-dialog
      title="修改文件名称"
      :visible.sync="fileNameDialogVisible"
      width="400px"
      destroy-on-close
    >
      <el-form
        :model="fileNameForm"
        :rules="fileNameRules"
        ref="fileNameFormRef"
        label-width="80px"
      >
        <el-form-item label="文件名称" prop="userName">
          <el-input
            v-model="fileNameForm.userName"
            placeholder="请输入文件名称"
            show-word-limit
            maxlength="8"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileNameForm">确认</el-button>
        <el-button @click="cancelFileNameForm">取消</el-button>
      </div>
    </el-dialog>

    <!-- 选择上传类型弹窗 -->
    <el-dialog
      title="请选择上传文件类型"
      :visible.sync="uploadTypeDialogVisible"
      width="400px"
      :show-footer="false"
    >
      <div class="upload-type-box">
        <div class="type-item" @click="selectFileType('video')">
          <i class="el-icon-video-play" />
          <span>视频文件（MP4）</span>
        </div>
        <div class="type-item" @click="selectFileType('pdf')">
          <i class="el-icon-document" />
          <span>PDF 文件</span>
        </div>
      </div>
    </el-dialog>

    <!-- el-upload 组件（隐藏，只用于触发上传） -->
    <el-upload
      ref="upload"
      :action="uploadUrl"
      :headers="uploadHeaders"
      :data="uploadParams"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-progress="handleUploadProgress"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :limit="1"
      :on-exceed="handleExceed"
      :show-file-list="false"
      :accept="uploadAccept"
    />

    <!-- 上传进度弹窗 -->
    <el-dialog
      title="文件上传中"
      :visible.sync="uploadProgressDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :show-footer="false"
    >
      <div class="progress-box">
        <el-progress :percentage="uploadPercent" />
        <p style="margin-top: 15px">资源上传中，请稍候...</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, delUser, deptTreeSelect } from "@/api/system/user";
import { getToken } from "@/utils/auth";

export default {
  name: "Knowledge",
  data() {
    return {
      loading: true,
      total: 0,
      userList: [],
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        deptId: undefined,
      },
      columns: {
        thumbnail: { label: "缩略图", visible: true },
        userName: { label: "文件名", visible: true },
        createTime: { label: "上传时间", visible: true },
        fileSize: { label: "文件大小", visible: true },
      },
      deptFilterText: "",
      deptOptions: [],
      builtInDepts: [
        { label: "海信产品介绍", id: "built-in-0" },
        { label: "公共教学视频", id: "built-in-1" },
        { label: "个人收藏录像", id: "built-in-2" },
      ],
      currentTag: "",
      // 标签弹窗
      tagDialogVisible: false,
      tagForm: { id: null, label: "" },
      tagRules: {
        label: [
          { required: true, message: "标签名称不能为空", trigger: "blur" },
          { max: 8, message: "最多8个字符", trigger: "blur" },
        ],
      },
      // 文件名弹窗
      fileNameDialogVisible: false,
      fileNameForm: { userId: undefined, userName: "" },
      fileNameRules: {
        userName: [
          { required: true, message: "文件名不能为空", trigger: "blur" },
        ],
      },

      // ================== 上传相关 ==================
      uploadTypeDialogVisible: false, // 类型选择弹窗
      currentFileType: "", // 当前选择的文件类型 video/pdf
      uploadUrl: "/api/file/upload", // 后端上传接口
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      uploadParams: { deptId: "", fileType: "" },
      uploadAccept: "",
      fileList: [], // 只允许一个
      uploadProgressDialogVisible: false,
      uploadPercent: 0,
    };
  },
  computed: {
    filteredCustomDeptList() {
      if (!this.deptOptions) return [];
      let list = this.deptOptions[0]?.children[0]?.children || [];
      if (!this.deptFilterText) return list;
      return list.filter((item) =>
        item.label.includes(this.deptFilterText.trim())
      );
    },
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    refreshMenu() {
      this.deptFilterText = "";
      this.getDeptTree();
    },
    getDeptTree() {
      deptTreeSelect().then((res) => {
        this.deptOptions = res.data;
      });
    },
    getBuiltInIcon(idx) {
      return ["el-icon-coin", "el-icon-video-camera", "el-icon-user"][idx];
    },
    getFileIcon(t) {
      return t === "video" ? "el-icon-video-play" : "el-icon-document";
    },
    defaultThumbnail(t) {
      return t === "video"
        ? "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
        : "https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3794312f7670b85636.jpeg";
    },
    formatFileSize(bytes) {
      if (!bytes) return "0B";
      const u = ["B", "KB", "MB", "GB"];
      let s = bytes,
        i = 0;
      while (s >= 1024 && i < 3) {
        s /= 1024;
        i++;
      }
      return s.toFixed(2) + u[i];
    },
    handleSelect(key) {
      const [type, idx] = key.split("-");
      this.currentTag =
        type === "built-in"
          ? this.builtInDepts[idx].id
          : this.filteredCustomDeptList[idx]?.id;
      this.queryParams.deptId = this.currentTag;
      this.handleQuery();
    },
    handleAddTag() {
      this.tagForm = { id: null, label: "" };
      this.tagDialogVisible = true;
    },
    handleEditTag(t) {
      this.tagForm = { ...t };
      this.tagDialogVisible = true;
    },
    // 删除标签
    handleDeleteTag(tag) {
      this.$modal
        .confirm(
          `是否删除该自定义标签?若删除，该标签下资源将迁移至[个人收藏录像]标签下。`
        )
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getDeptTree();
          this.migrateResource(tag.id, this.builtInDepts[2].id);
        })
        .catch(() => {});
    },
    // 迁移资源
    migrateResource(oldDeptId, newDeptId) {
      this.getList();
    },
 submitTagForm() {
      this.$refs["tagFormRef"].validate((valid) => {
        if (valid) {
          if (this.tagForm.id) {
            this.$modal.msgSuccess("修改成功");
            this.tagDialogVisible = false;
            this.getDeptTree();
          } else {
            this.$modal.msgSuccess("新增成功");
            this.tagDialogVisible = false;
            this.getDeptTree();
          }
        }
      });
    },
    cancelTagForm() {
      this.tagDialogVisible = false;
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = null;
      this.currentTag = "";
      this.handleQuery();
    },
    getList() {
      this.loading = true;
      listUser(this.queryParams).then((res) => {
        this.userList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    handleShare() {
      this.$modal.msgSuccess("分享链接已复制");
    },
    handleUpdateFileName(row) {
      this.fileNameForm = { ...row };
      this.fileNameDialogVisible = true;
    },
    submitFileNameForm() {
      this.$refs.fileNameFormRef.validate((v) => {
        if (v) {
          this.$modal.msgSuccess("修改成功");
          this.fileNameDialogVisible = false;
          this.getList();
        }
      });
    },
    cancelFileNameForm() {
      this.fileNameDialogVisible = false;
    },
    handleDelete(row) {
      this.$modal.confirm("确认删除？").then(() => {
        delUser(row.userId).then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        });
      });
    },
    handlePreview() {
      this.$modal.msg("预览功能开发中");
    },

    // ====================== 上传核心逻辑 ======================
    // 打开类型选择
    openUploadTypeDialog() {
      this.uploadTypeDialogVisible = true;
    },
    // 选择文件类型
    selectFileType(type) {
      this.uploadTypeDialogVisible = false;
      this.currentFileType = type;
      this.uploadAccept = type === "video" ? "video/mp4" : "application/pdf";
      // 触发上传
      this.$nextTick(() => {
        this.$refs.upload.$children[0].$el.click();
      });
    },
    // 上传前校验
    beforeUpload(file) {
      this.uploadParams.deptId = this.currentTag || this.builtInDepts[2].id;
      this.uploadParams.fileType = this.currentFileType;
      this.uploadProgressDialogVisible = true;
      this.uploadPercent = 0;
      return true;
    },
    // 超过数量
    handleExceed() {
      this.$modal.msgError("每次只能上传一个文件！");
    },
    // 进度
    handleUploadProgress(e) {
      this.uploadPercent = Math.round(e.percent);
    },
    // 成功
    handleUploadSuccess() {
      this.uploadPercent = 100;
      setTimeout(() => {
        this.uploadProgressDialogVisible = false;
        this.$modal.msgSuccess("上传成功");
        this.getList(); // 刷新列表
        this.fileList = [];
      }, 500);
    },
    // 失败
    handleUploadError() {
      this.uploadProgressDialogVisible = false;
      this.$modal.msgError("上传失败");
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  height: 100%;
}

.custom-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.resource-thumb {
  width: 230px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
}

.upload-type-box {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
  .type-item {
    width: 120px;
    height: 120px;
    border: 1px dashed #ccc;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    i {
      font-size: 40px;
      color: #409eff;
      margin-bottom: 10px;
    }
    &:hover {
      border-color: #409eff;
      background: #f5f7fa;
    }
  }
}

.progress-box {
  padding: 20px;
  text-align: center;
}
</style>