<template>
  <div class="ad-material-manager">
    <el-container>
      <!-- 左侧目录树 -->
      <el-aside width="250px" class="aside">
        <div class="directory-header">
          <span>素材目录</span>
          <el-button type="text" size="small" @click="showNewDirDialog(null)">
            <i class="el-icon-plus"></i> 新建目录
          </el-button>
        </div>
        <el-tree
          ref="directoryTree"
          :data="directories"
          :props="defaultProps"
          node-key="id"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span class="directory-actions">
              <el-button
                type="text"
                size="mini"
                @click.stop="showNewDirDialog(data.id)"
              >
                <i class="el-icon-plus"></i>
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click.stop="handleDeleteDirectory(node, data)"
              >
                <i class="el-icon-delete"></i>
              </el-button>
            </span>
          </span>
        </el-tree>
      </el-aside>

      <!-- 右侧内容区 -->
      <el-main class="main">
        <div class="content-header">
          <div class="current-path">
            当前位置：{{ currentPath }}
          </div>
        </div>

        <el-form inline>

          <el-form-item label="标签">
            <material-tag-select
              v-model="tagFilter"
              placeholder="请选择标签..."
              @change="handleTagFilterChange"
            />
          </el-form-item>

          <el-form-item label="设计师">
            <desigher-select v-model="designer"
                             @change="fetchMaterials()"
            />

          </el-form-item>
          <el-form-item label="素材类型">
            <el-select
            v-model="resType"
            placeholder="素材类型"
            clearable
            @change="fetchMaterials"
          >
            <el-option
              key="1"
              label="图片"
              value="1"
            >
            </el-option>

            <el-option
              key="2"
              label="视频"
              value="2"
            >
            </el-option>
          </el-select>
          </el-form-item>

          <el-form-item label="语言">
            <el-select
              v-model="language"
              placeholder="请选择语言"
              clearable
              @change="fetchMaterials"
            >
              <el-option label="英语" value="en" />
              <el-option label="日语" value="ja" />
              <el-option label="韩语" value="ko" />
              <el-option label="西班牙语" value="es" />
              <el-option label="葡萄牙语" value="pt" />
              <el-option label="法语" value="fr" />
              <el-option label="德语" value="de" />
              <el-option label="意大利语" value="it" />
              <el-option label="中文" value="zh" />
              <el-option label="俄语" value="ru" />
            </el-select>
          </el-form-item>

          <el-form-item label="创建日期">
            <el-date-picker
              v-model="queryDate"
              type="daterange"
              align="right"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="fetchMaterials"
            />
          
          </el-form-item>
            
        </el-form>

        <div style="margin-bottom: 10px;">
          <el-button type="primary" size="small"  @click="openMaterialUpload">上传</el-button>
          <el-dropdown :disabled="multipleSelection.length == 0" @command="handleBatchCommand" style="margin-left: 10px;">
            <el-button size="small" :disabled="multipleSelection.length == 0">
              批量操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="batchAddTags">批量添加标签</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <!-- 文件列表 -->
        <el-table v-loading="loading" :data="materials" style="width: 100%" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="预览" width="120">
            <template slot-scope="scope">
              <div class="preview-container">
                <img
                  v-if="scope.row.resType === 1"
                  :src="scope.row.url"
                  class="preview-image"
                />
                <video
                  v-else-if="scope.row.resType === 2"
                  :src="scope.row.url"
                  class="preview-video"
                  controls
                >
                </video>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="materialName" label="文件名" width="300"></el-table-column>
          <el-table-column prop="resType" label="类型" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.resType === 1 ? '图片' : scope.row.resType === 2 ? '视频' : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="上传时间" width="180">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="realName" label="设计师" width="80"/>
          <el-table-column prop="language" label="语言" width="120"/>
          <el-table-column label="标签">
            <template slot-scope="scope">
              <el-tag style="margin-left: 10px"
                v-for="tag in scope.row.tagList"
                :key="tag.id"
                size="mini"
              >
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="showMoveDialog(scope.row)">
                移动
              </el-button>
              <el-button size="mini" type="text" @click="handlePreview(scope.row)">
                预览
              </el-button>
              <el-button
                size="mini"
                type="text"
                class="delete-btn"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        >
        </el-pagination>
      </el-main>
    </el-container>

    <!-- 新建目录弹窗 -->
    <el-dialog
      :title="parentId ? '新建子目录' : '新建目录'"
      :visible.sync="newDirDialogVisible"
      width="30%"
    >
      <el-form :model="newDirForm" ref="newDirForm" :rules="dirFormRules">
        <el-form-item label="目录名称" prop="name">
          <el-input v-model="newDirForm.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="newDirDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createDirectory">确定</el-button>
      </div>
    </el-dialog>

    <!-- 移动文件弹窗 -->
    <el-dialog title="移动到" :visible.sync="moveDialogVisible" width="30%">
      <el-tree
        ref="moveTree"
        :data="directories"
        :props="defaultProps"
        
        node-key="id"
        :default-expand-all="true"
        @node-click="handleMoveNodeClick"
      ></el-tree>
      <div slot="footer">
        <el-button @click="moveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMove">确定</el-button>
      </div>
    </el-dialog>

    <!-- 预览弹窗 -->
    <el-dialog
      :visible.sync="previewDialogVisible"
      width="50%"
      class="preview-dialog"
    >
      <div class="preview-content">
        <img
          v-if="previewFile && previewFile.resType === 1"
          :src="previewFile.url"
          class="preview-image"
        />
        <video
          v-else-if="previewFile && previewFile.resType === 2"
          :src="previewFile.url"
          controls
          class="preview-video"
        >
        </video>
      </div>
    </el-dialog>

    <!-- 批量添加标签对话框 -->
  <el-dialog title="批量添加标签" :visible.sync="batchTagsDialogVisible" width="30%">
    <el-form>
      <el-form-item label="选择标签">
        <material-tag-select
          v-model="selectedTags"
          placeholder="请选择标签..."
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelAddTags" >取消</el-button>
      <el-button type="primary" @click="confirmAddTags" :loading="batchAddTagBtn">确定</el-button>
    </div>
  </el-dialog>

  </div>

  
</template>

<script>
import {
  getMaterialDirectoriesTree,
  createDirectory,
  deleteDirectory,
  fetchMaterials,
  movematerial,
  uploadMaterial,
  getMaterialDesigners,
  getAllTags,
  deleteMaterialById
} from '@/api/report';
import { batchAddTagsToMaterials } from '@/api/materialTag';
import FileUpload from '../../components/FileUpload'
import MaterialTagSelect from '../../components/MaterialTagSelect'
import DesigherSelect from '../../components/DesignerSelect'


export default {
  name: 'MaterialManage',

  components: {
    MaterialTagSelect,
    DesigherSelect,
  },

  data() {
    return {
      // 目录树数据
      directories: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      currentDirectory: null, // 当前选中的目录ID
      currentPath: '根目录', // 当前路径
      selectedTags: [], // 批量添加标签选中的标签
      batchTagsDialogVisible: false, // 批量添加标签对话框是否可见
      batchAddTagBtn: false,
      // 文件列表数据
      materials: [],
      loading: false,
      queryDate: [],
      startDate: '',
      endDate: '',
      // 新建目录相关
      newDirDialogVisible: false,
      newDirForm: {
        name: '',
        parentId: null
      },
      dirFormRules: {
        name: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ]
      },
      parentId: null,

      // 移动文件相关
      moveDialogVisible: false,
      selectedMoveDirectory: null,
      currentMoveFile: null,

      // 预览相关
      previewDialogVisible: false,
      previewFile: null,

      // 上传相关


      // 分页相关
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      includeSubdirectories: true,
      selectedDirectoryIds: [],
      fileList:[],
      materialDesigners: [],
      tagFilter: [],
      designer: '',
      resType: '',
      language: '',
      allTags: [],
      multipleSelection: []
    };
  },

  created() {
    this.currentPage = 1;
    this.fetchDirectories();
    this.fetchMaterialDesigners();
  },
  mounted() {
    this.fetchAllTags();
  },

  methods: {
    fetchDirectories() {
      getMaterialDirectoriesTree().then(res => {
        if (res.status === 200) {
          this.directories = res.result.data;
        } else {
          this.$message.error('获取目录失败');
        }
      });
    },
    async fetchMaterialDesigners() {
      try {
        const response = await getMaterialDesigners();
        if (response && response.status === 200 && response.result) {
          this.materialDesigners = response.result.data;
        } else {
          this.$message.error('获取创作者列表失败');
          console.error('获取创作者列表失败:', response);
        }
      } catch (error) {
        this.$message.error('获取创作者列表失败');
        console.error('获取创作者列表失败:', error);
      }
    },

    fetchMaterials(){
      if(this.currentDirectory == null){
        return
      }
      this.loading = true;
      let tagFilterStr = this.tagFilter.map(String).join(',');

      if (this.queryDate && this.queryDate.length === 2) {
          this.startDate = this.queryDate[0];
          this.endDate = this.queryDate[1];
      } else {
        this.startDate = "";
        this.endDate = "";
      }

      fetchMaterials({
        tags: tagFilterStr,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        directoryId: this.currentDirectory,
        includeSubdirectories: this.includeSubdirectories,
        designer: this.designer || null,
        resType: this.resType,
        language: this.language || null,
        startDate: this.startDate,
        endDate: this.endDate
      }).then(response => {
        if (response && response.status === 200) {
          this.materials = response.result.data.value;
          this.totalCount = response.result.data.total;
        } else {
          this.$message.error(response.msg || '获取素材列表失败');
        }
      }).catch(error => {
        this.$message.error('获取数据失败');
        console.error('获取数据失败:', error);
      }).finally(() => {
        this.loading = false;
      });
    },

    handleTagFilterChange(value) {
      this.tagFilter = value;
      this.fetchMaterials()
    },
    async fetchAllTags() {
      try {
        const response = await getAllTags();
        if (response && response.status === 200) {
          this.allTags = response.result.data;
        } else {
          this.$message.error('获取标签列表失败');
        }
      } catch (error) {
        console.error('获取标签列表失败:', error);
        this.$message.error('获取标签列表失败');
      }
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchMaterials()

    },
    // 处理目录点击
    handleNodeClick(data) {
      this.currentDirectory = data.id;
      this.currentPath = this.getNodePath(data);
      this.currentPage = 1;
      this.fetchMaterials()
    },


    // 翻页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchMaterials()

    },

    // 获取节点路径
    getNodePath(node) {
      const path = [];
      let currentNode = node;
      while (currentNode) {
        path.unshift(currentNode.name);
        currentNode = currentNode.parent;
      }
      return path.join(' / ');
    },

    // 显示新建目录弹窗
    showNewDirDialog(parentId) {
      this.parentId = parentId;
      this.newDirForm.name = '';
      this.newDirForm.parentId = parentId;
      this.newDirDialogVisible = true;
    },

    // 创建目录
    createDirectory() {
      this.$refs.newDirForm.validate((valid) => {
        if (valid) {
          createDirectory({
            name: this.newDirForm.name,
            parentId: this.newDirForm.parentId
          })
            .then(response => {
              if (
                response &&
                response.status === 200 &&
                response.result &&
                response.result.data
              ) {
                this.$message.success('创建成功');
                this.newDirDialogVisible = false;
                this.fetchDirectories();
              } else {
                this.$message.error(response.msg || '创建失败');
              }
            })
            .catch(error => {
              this.$message.error('创建失败');
              console.error('创建目录失败:', error);
            });
        }
      });
    },

    // 删除目录
    handleDeleteDirectory(node, data) {
      this.$confirm('确认删除该目录吗？其下的所有文件将被删除', '提示', {
        type: 'warning'
      })
        .then(async () => {
          try {
            const response = await deleteDirectory({id:data.id});
            console.log("delete", response)
            if (response.status == 200) {
              this.$message.success('删除成功');
              await this.fetchDirectories(); // 重新获取目录树
              // 如果删除的是当前选中的目录，清空文件列表
              if (data.id === this.currentDirectory) {
                this.materials = [];
                this.currentDirectory = null;
                this.currentPath = '根目录';
              }
            } else {
              this.$message.error(response.msg || '删除失败');
            }
          } catch (error) {
            this.$message.error('删除失败');
            console.error('删除目录失败:', error);
          }
        })
        .catch(() => {});
    },

    // 显示移动文件弹窗
    showMoveDialog(file) {
      this.currentMoveFile = file;
      this.selectedMoveDirectory = null;
      this.moveDialogVisible = true;
    },

    // 处理移动目标目录选择
    handleMoveNodeClick(data) {
      this.selectedMoveDirectory = data.id;
    },

    // 确认移动文件
    async confirmMove() {
      if (!this.selectedMoveDirectory) {
        this.$message.warning('请选择目标目录');
        return;
      }

      try {
        const response = await movematerial({
          materialId: this.currentMoveFile.id, // 素材的 ID
          targetDirectoryId: this.selectedMoveDirectory // 目标目录的 ID
        });

        // 移动成功
        if (response && response.status === 200) {
          this.$message.success("移动成功");
          this.moveDialogVisible = false;
          this.fetchMaterials()
        } else {
          this.$message.error(response.msg || "移动失败");
        }
      } catch (error) {
        this.$message.error('移动失败');
        console.error('移动文件失败:', error);
      }
    },

    // 删除文件
    handleDelete(row) {
      this.$confirm('确认删除该文件吗？', '提示', {
        type: 'warning'
      })
        .then(()=>{
          this.loading = true
          deleteMaterialById({id: row.id}).then((res) => {
            if (res.status == 200) {
              this.$message.success("删除成功!")
              this.fetchMaterials()
            } else {
              this.$message.error("保存失败!")
              this.loading = false
            }
          })
        })
        .catch(() => {});
    },

    // 预览文件
    handlePreview(file) {
      this.previewFile = file;
      this.previewDialogVisible = true;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 工具方法 - 格式化文件大小
    formatFileSize(size) {
      if (size < 1024) {
        return size + ' B';
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB';
      } else {
        return (size / 1024 / 1024).toFixed(2) + ' MB';
      }
    },

    // 工具方法 - 格式化日期
    formatDate(date) {
      return new Date(date).toLocaleString();
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
  
    handleDirectoryChange(value) {
      this.uploadVideoForm.directoryId = value[value.length - 1];
    },

    openMaterialUpload(){
      window.open(`/materialUpload`)
      // this.$router.push({ name: 'google.fbAdDetail', query: { pkg: row.pkg } });
    },

    // 处理批量操作命令
    handleBatchCommand(command) {
      if (command === 'batchAddTags') {
        this.showBatchAddTagsDialog();
      }
    },

    // 显示批量添加标签对话框
    showBatchAddTagsDialog() {
      this.batchTagsDialogVisible = true;
      this.selectedTags = [];
    },
    
    // 确认批量添加标签
    confirmAddTags() {
      if (this.selectedTags.length > 0) {
        this.addTagsToSelectedMaterials(this.selectedTags);
      } else {
        this.$message.warning('请选择标签');
      }
    },
    
    // 取消批量添加标签
    cancelAddTags() {
      this.batchTagsDialogVisible = false;
      this.selectedTags = [];
    },

    // 为选中的素材添加标签
    addTagsToSelectedMaterials(tags) {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择素材');
        return;
      }

      const materialIds = this.multipleSelection.map(item => item.id);
      const tagIds = tags.map(Number); // 确保标签ID是数值格式
      console.log(materialIds, tagIds)
      // 添加进度相关数据
      this.batchAddTagBtn = true
      
      // 调用批量添加标签的API
      batchAddTagsToMaterials(materialIds, tagIds)
        .then(res => {
          if (res.status === 200) {
            this.$message.success(`已为${materialIds.length}个素材添加标签`);
            this.fetchMaterials(); // 刷新素材列表
          } else {
            this.$message.error(res.msg || '添加标签失败');
          }
        })
        .catch(error => {
          this.$message.error('添加标签失败');
          console.error('添加标签失败:', error);
        })
        .finally(() => {
          this.batchAddTagBtn = false
          this.batchTagsDialogVisible = false;
          
        });
      }
    },
  }
</script>

<style scoped>
.ad-material-manager {
  height: 100%;
  min-height: 500px;
}

.el-container {
  height: 100%;
}

.aside {
  /* background-color: #f5f7fa; */
  border-right: 1px solid #e6e6e6;
}

.directory-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6e6e6;
}

.main {
  padding: 20px;
}

.content-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.current-path {
  font-size: 14px;
  color: #606266;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.directory-actions {
  opacity: 0;
  transition: opacity 0.2s;
}

.custom-tree-node:hover .directory-actions {
  opacity: 1;
}

.preview-container {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #e6e6e6;
}

.preview-image,
.preview-video {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f78989;
}

.preview-dialog .preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-dialog .preview-image {
  max-width: 100%;
  max-height: 70vh;
}

.preview-dialog .preview-video {
  max-width: 100%;
  max-height: 70vh;
}
</style>
