<template>
  <div class="upload-page">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item>素材管理</el-breadcrumb-item>
      <el-breadcrumb-item v-for="item in breadcrumbItems" :key="item.id">
        {{ item.name }}
      </el-breadcrumb-item>
    </el-breadcrumb>

    <h2>文件上传</h2>
    <el-form ref="uploadForm" :model="uploadForm" label-width="120px">
      <el-form-item label="素材上传">
        <!-- 使用上传组件 -->
        <file-upload
          :upload-url="uploadUrl"
          :extra-data="extraData"
          :headers="headers"
          @update:files="handleFilesUpdate"
          @upload-success="handleUploadSuccess"
          @upload-error="handleUploadError"
          @upload-complete="handleUploadComplete"
          ref="uploadComponent"
        >
          <!-- 自定义上传按钮 -->
          <template #trigger>
            <el-button type="primary" icon="el-icon-upload">
              选择图片或视频
            </el-button>
          </template>
        </file-upload>
      </el-form-item>
      <el-form-item label="选择标签">
        <material-tag-select
          v-model="uploadForm.tags"
          placeholder="请选择标签..."
          @change="handleChange"
        />
      </el-form-item>

      <el-form-item label="设计师">
        <desigher-select v-model="uploadForm.designer"
        />

      </el-form-item>

      <el-form-item label="目录" prop="directoryId" :rules="[{ required: true, message: '请选择目录', trigger: 'change' }]">
        <el-cascader
          v-model="selectedDirectoryIds"
          :options="directories"
          :props="{ expandTrigger: 'hover', value:'id',label:'name', children:'children' }"
          clearable
          @change="handleDirectoryChange"
          placeholder="请选择目录"
          style="width: 30%;"
        ></el-cascader>
      </el-form-item>
      <el-button @click="saveMaterial" :loading="submit_loading">提交</el-button>
    </el-form>

    <!-- 显示上传成功的文件列表 -->
    <!--    <div class="success-files" v-if="uploadForm.successFiles.length > 0">-->
    <!--      <h3>已上传文件列表：</h3>-->
    <!--      <el-table :data="uploadForm.successFiles" style="width: 100%">-->
    <!--        <el-table-column prop="name" label="文件名"></el-table-column>-->
    <!--        <el-table-column prop="type" label="类型"></el-table-column>-->
    <!--        <el-table-column prop="size" label="大小">-->
    <!--          <template slot-scope="scope">-->
    <!--            {{ formatFileSize(scope.row.size) }}-->
    <!--          </template>-->
    <!--        </el-table-column>-->
    <!--        <el-table-column label="预览">-->
    <!--          <template slot-scope="scope">-->
    <!--            <el-button type="text" @click="previewFile(scope.row)">-->
    <!--              预览-->
    <!--            </el-button>-->
    <!--          </template>-->
    <!--        </el-table-column>-->
    <!--      </el-table>-->

    <!--      &lt;!&ndash; 清空按钮 &ndash;&gt;-->
    <!--      <el-button type="danger" @click="clearFiles" class="clear-btn">-->
    <!--        清空文件-->
    <!--      </el-button>-->
    <!--    </div>-->
  </div>
</template>

<script>
import FileUpload from '../../components/FileUpload/index.vue'
import MaterialTagSelect from '../../components/MaterialTagSelect/index.vue'
import DesigherSelect from '../../components/DesignerSelect/index.vue'
import {
  getMaterialDirectoriesTree,
  addMaterial,
} from '@/api/report';
export default {
  name: 'UploadPage',

  components: {
    FileUpload,
    MaterialTagSelect,
    DesigherSelect
  },

  data() {
    return {
      uploadUrl: process.env.PUTIN_API + '/material/business/youtube/uploadToCDN',

      extraData: {
      },
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      selectedDirectoryIds: [],
      directories: [],
      breadcrumbItems: [], // 面包屑数据
      uploadForm: { // 上传视频表单数据
        // file: null,
        successFiles: [],
        tags: [],
        designer: null,
        directoryId: null
      },
      submit_loading: false
    }
  },

  created() {
    this.fetchDirectories();
  },

  methods: {
    // 处理文件列表更新
    handleFilesUpdate(files) {
      this.uploadForm.successFiles = files
      console.log("parent receive upload success", files)
    },

    // 处理单个文件上传成功
    handleUploadSuccess(file) {
      // this.$message.success(`文件 ${file.name} 上传成功`)
    },

    // 处理上传错误
    handleUploadError({ file, error }) {
      // this.$message.error(`文件 ${file.name} 上传失败：${error.message}`)
    },

    // 处理所有文件上传完成
    handleUploadComplete(files) {
      // this.$message.success(`所有文件上传完成，共 ${files.length} 个文件`)
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 预览文件
    previewFile(file) {
      if (file.type.includes('image')) {
        // 使用 Element UI 的 Image 预览
        const h = this.$createElement
        this.$msgbox({
          title: file.name,
          message: h('img', {
            attrs: {
              src: file.url,
              style: 'max-width: 100%'
            }
          }),
          showCancelButton: false,
          confirmButtonText: '关闭'
        })
      } else if (file.type.includes('video')) {
        // 使用自定义对话框预览视频
        this.$msgbox({
          title: file.name,
          message: h('video', {
            attrs: {
              src: file.url,
              controls: true,
              style: 'max-width: 100%'
            }
          }),
          showCancelButton: false,
          confirmButtonText: '关闭'
        })
      }
    },

    handleChange(value) {
      console.log('选中的标签ID：', value)
    },

    fetchDirectories() {
      getMaterialDirectoriesTree().then(res => {
        if (res.status === 200) {
          this.directories = res.result.data;
        } else {
          this.$message.error('获取目录失败');
        }
      });
    },
    handleDirectoryChange(value) {
      this.uploadForm.directoryId = value[value.length - 1];
      this.updateBreadcrumb(value);
    },

    // 更新面包屑
    updateBreadcrumb(selectedPath) {
      if (!selectedPath || selectedPath.length === 0) {
        this.breadcrumbItems = [];
        return;
      }

      // 根据选中的路径构建面包屑
      this.breadcrumbItems = selectedPath.map(id => {
        const directory = this.findDirectoryById(id, this.directories);
        return directory ? { id: directory.id, name: directory.name } : null;
      }).filter(Boolean);
    },

    // 递归查找目录
    findDirectoryById(id, directories) {
      for (const directory of directories) {
        if (directory.id === id) {
          return directory;
        }
        if (directory.children) {
          const found = this.findDirectoryById(id, directory.children);
          if (found) return found;
        }
      }
      return null;
    },

    saveMaterial(){
      // 表单验证
      // if (this.uploadForm.tags.length === 0) {
      //   this.$message.error('请选择标签')
      //   return
      // }
      if (this.uploadForm.directoryId === null) {
        this.$message.error('请选择目录')
        return
      }

      this.submit_loading = true

      // 上传文件并保存材料
      addMaterial(this.uploadForm).then(res => {
        if (res.status === 200) {
          this.$message.success('保存成功')
          // 跳转到素材管理页面
          this.$router.push('/assetManagement/materialManage')
        } else {
          this.$message.error('保存失败')
        }
      }).catch(error => {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      }).finally(() => {
        this.submit_loading = false
      })
    },
  }
}
</script>

<style scoped>
.upload-page {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.success-files {
  margin-top: 30px;
}

.clear-btn {
  margin-top: 20px;
}
</style>
