<template>
  <div>
    <!-- 我的画册-创建文件夹btn -->
    <div v-if="isToFolder" class="material_crumbs">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item><a href="/theme">主题库</a></el-breadcrumb-item>
        <el-breadcrumb-item><a @click="breadcrumbToAlbum">我的画册</a></el-breadcrumb-item>
        <el-breadcrumb-item>{{ currentFolder }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div style="display:flex; flex-wrap: wrap">
      <div v-if="!isToFolder" class="theme_mkdir cont_upload" @click="handleMkdir(0)">
        <svg class="font-icon icon" aria-hidden="true">
          <use xlink:href="#icon-a-xinzeng" />
        </svg>
        <el-button class="mkdir_btn" round type="primary">创建文件夹</el-button>
      </div>
      <div v-else class="theme_mkdir cont_upload">
        <el-button class="cont_upload_btn" round type="primary">添加</el-button>
        <el-button class="return_btn" round type="primary" @click="breadcrumbToAlbum">返回</el-button>
      </div>
      <div v-for="(item,index) in materialFolders" :key="item.id" :class="['theme_mkdir', 'folder', { 'item_multi': folderChecked == index }]" @click.stop="editFolder(item,index)" @dblclick="floderDbClick(item,index)">
        <div class="icon_bg">
          <svg v-if="!item.imgPath" class="font-icon icon" aria-hidden="true">
            <use xlink:href="#icon-wenjianjia" />
          </svg>
          <img v-else :src="item.imgPath" />
        </div>
        <p class="file_name">{{ item.name }}</p>
        <span v-if="folderChecked == index" class="checked_btn"></span>
      </div>
      <!-- 画册list -->
      <div v-for="(item, index) in themeGalleryList" :key="index" :class="['theme_item', { 'item_multi': selectInFolderid.includes(item.in_folder_id) }]">
        <img v-if="item.img_path || item.material_type == 1" :src="item.img_path" :onerror="defaultImg" alt />
        <div v-if="!item.img_path && item.material_type == 2" class="radio_img"></div>
        <div class="item_format">
          <span class="item_type">{{ item.deposit_url | getFileFormat }}</span>
          <span v-if="item.material_type != 0" class="item_time">{{ item.duration | getSeconds }}</span>
        </div>
        <div class="file_name">{{ item.material_name }}</div>
        <span v-if="isMultiSelected" class="checked_btn" @click="selectedItem(item)"></span>
      </div>
    </div>

    <!-- 多选操作 -->
    <div v-if="selectInFolderid.length !== 0 || folderChecked != -1" class="multi_handle">
      <div v-if="!isEditFolder && folderChecked == -1 && isMultiSelected">
        <el-button type="button" class="mulit_btn" @click="publishHandle(0)">即时发布</el-button>
        <el-button type="button" class="mulit_btn" @click="publishHandle(1)">定时发布</el-button>
        <el-button type="button" class="mulit_btn">下载</el-button>
        <el-button type="button" class="mulit_btn" @click="moveingTo">移动</el-button>
        <el-button type="button" class="mulit_btn mulit_delt_btn" @click="deltMyAlbumItem">删除</el-button>
      </div>
      <div v-else>
        <el-button type="button" class="mulit_btn" @click="handleMkdir(1)">编辑</el-button>
        <el-button type="button" class="mulit_btn mulit_delt_btn" @click="deleteMaterialFolder">删除</el-button>
      </div>
    </div>
    <!-- 创建文件夹layer / 编辑 -->
    <div class="publish_layer">
      <el-dialog title="创建文件夹" :close-on-click-modal="false" :show-close="false" :visible.sync="mkdirVisible" width="616px" height="384px">
        <el-form ref="folderForm" :inline="true" :model="folderForm" size="small" label-width="100px">
          <el-form-item
            label="文件夹名称"
            prop="name"
            :rules="[
              { required: true, message: '请输入名称', trigger: 'blur' }
            ]"
          >
            <el-input v-model="folderForm.name" style="width: 336px" />
          </el-form-item>
          <el-form-item label="封面" prop="file">
            <UploadCover ref="childUpload" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" round @click="submitFolderForm('folderForm')">保 存</el-button>
          <el-button round @click="mkdirVisible=false">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 移动至layer -->
    <div class="wjj_layer">
      <!-- width="736px" -->
      <el-dialog title="移动至" :close-on-click-modal="false" :show-close="false" :visible.sync="movingVisible" width="576px" height="384px">
        <div class="wjj_list">
          <div v-for="(item, index) in folderList" :key="index" :class="['wjj_item', { 'wjj_item_active': folderListChecked == index }]" @click="wjjSelected(item,index)">
            <svg class="font-icon icon" aria-hidden="true">
              <use xlink:href="#icon-wenjianjia" />
            </svg>
            <p class="wjj_name">{{ item.name }}</p>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" round @click="moveFile">确定</el-button>
          <el-button round @click="movingVisible=false">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { FetchMyAlbum, FetchDeleteMyAlbum, FetchSaveThemeFolder, FetchDeleteThemeFolder, FetchMoveMyThemeMaterial } from '@/api/theme/theme.js'
import { getSeconds, getFileFormat } from '@/utils/index.js'
import UploadCover from './upload_cover'
export default {
  name: 'ThemeGalleryList',
  components: { UploadCover },
  filters: {
    getSeconds(s) {
      return getSeconds(s)
    },
    getFileFormat(s) {
      return getFileFormat(s)
    }
  },
  props: {
    isMultiSelected: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      orga_id: '133221333123111', // 机构ID
      isAlbumList: [],
      themeGalleryList: [], // 主题库的列表
      materialFolders: [], // 文件夹list
      selectedListId: [],
      selectInFolderid: [], // 关联素材得主键得ID
      selectedMaterial: [], // 素材选中
      thisFoldId: null || '',
      rootFolderId: null,
      thisAlbumFoldId: null,
      isEditFolder: false, // 是否编辑文件夹
      mkdirVisible: false, // 新建编辑layer
      folderChecked: -1, // 文件夹是否单击选中
      folderListChecked: -1,
      isToFolder: false, // 是否进入文件夹
      currentFolder: '', // 当前进入的文件夹名
      currentFolderId: null,
      folderList: [], // 文件夹list
      movingVisible: false,
      movingChecked: null,
      folderForm: { // form
        fid: '',
        id: '',
        img_path: '',
        name: '',
        orga_id: ''
      }
    }
  },
  computed: {
    defaultImg() {
      return 'this.src="' + require('@/assets/images/menu_bg_02.png') + '"'
    }
  },
  watch: {
    isMultiSelected(newName, oldName) {
      if (newName === false) {
        this.selectedListId = []
        this.selectInFolderid = []
      }
    }
  },
  mounted() {
    this.getMyAlbum()
    document.addEventListener('click', this.hiddenFolderActiveClick)
  },
  methods: {
    breadcrumbToAlbum() {
      this.$router.push('/theme')
      this.getMyAlbum()
    },
    // 获取我的画册 list
    getMyAlbum() {
      let inOrOutFolderId
      if (this.$route.query.folderTag) {
        console.log('文件夹内')
        this.isToFolder = true
        this.currentFolder = localStorage.getItem('currentFolder')
        this.currentFolderId = localStorage.getItem('currentFolderId')
        inOrOutFolderId = this.currentFolderId
      } else {
        console.log('文件夹外')
        this.isToFolder = false
        localStorage.removeItem('currentFolder')
        localStorage.removeItem('currentFolderId')
        inOrOutFolderId = null
      }
      const params = {
        'theme_name': null,
        'theme_class': null,
        'device_direction': null,
        'orga_id': this.orga_id,
        'start_time': null,
        'end_time': null,
        'folder_id': inOrOutFolderId
      }
      // this.materialFolders = []
      // this.themeGalleryList = []
      FetchMyAlbum(params).then(res => {
        if (res.code == 200) {
          this.materialFolders = res.data.materialFolders
          this.themeGalleryList = res.data.pageThemeVO

          this.isAlbumList = res.data.pageThemeVO
          this.thisAlbumFoldId = res.data.thisFoldId
          if (!this.$route.query.folderTag) {
            localStorage.setItem('rootFolderId', res.data.thisFoldId)
          }
          // 创建文件夹获取data
          this.thisFoldId = res.data.thisFoldId
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 删除我的画册里的素材
    deltMyAlbumItem() {
      const params = {
        ids: this.selectInFolderid
      }
      FetchDeleteMyAlbum(params).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          this.getMyAlbum()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 多选选中
    selectedItem(item) {
      const id = item.material_id
      const inFolderId = item.in_folder_id
      // const type = item.material_type
      const arr = this.selectedListId
      const arr2 = this.selectInFolderid
      if (arr2.includes(inFolderId)) {
        const index = arr2.indexOf(inFolderId)
        if (index > -1) {
          arr2.splice(index, 1)
          arr.splice(index, 1)
          this.selectInFolderid.splice(index, 1)
          this.selectedMaterial.splice(index, 1)
        }
      } else {
        this.selectedListId.push(id)
        this.selectInFolderid.push(inFolderId)
        this.selectedMaterial.push(item)
        // this.formatType = type
      }
    },
    // 新建 / 编辑 文件夹
    handleMkdir(mkdirType) {
      this.mkdirVisible = true
      this.folderForm.fid = this.thisFoldId
      this.folderForm.orga_id = this.orga_id
      if (mkdirType === 0) {
        this.$nextTick(() => {
          this.$refs.childUpload.imageUrl = ''
          this.folderForm.img_path = ''
          this.folderForm.name = ''
        })
        delete this.folderForm.id
      } else {
        this.$nextTick(() => {
          this.$refs.childUpload.imageUrl = this.folderForm.img_path
        })
      }
    },
    // 文件夹双击操作
    floderDbClick(item, index) {
      this.$router.replace(
        {
          path: '/theme', query: { folderTag: 1 }
        }
      )
      this.currentFolder = item.name
      this.currentFolderId = item.id
      localStorage.setItem('currentFolder', this.currentFolder)
      localStorage.setItem('currentFolderId', this.currentFolderId)
      this.getMyAlbum()
      this.selectedListId = []
      this.folderChecked = -1
      this.isEditFolder = false
    },
    // 点击其他区域选中的文件夹 去掉选中样式
    hiddenFolderActiveClick() {
      this.folderChecked = -1
      this.isEditFolder = false
    },
    // 选择 编辑 文件夹
    editFolder(item, index) {
      this.selectedListId = []
      // 有选择中的文件夹时，同时存在素材多选操作时
      this.$emit('changedMultiSelected')
      if (index != this.folderChecked) {
        this.folderChecked = index
        this.isEditFolder = true
        this.folderForm = {
          fid: item.fid,
          id: item.id,
          name: item.name,
          img_path: item.imgPath,
          orga_id: item.orgaId
        }
      } else {
        this.folderChecked = -1
        this.isEditFolder = false
      }
    },
    // 删除 文件夹
    deleteMaterialFolder() {
      console.log(this.folderForm.id)
      this.$confirm('此操作将永久删除该文件夹, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        ids.push(this.folderForm.id)
        const params = {
          ids: ids
        }
        FetchDeleteThemeFolder(params).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '删除文件夹成功',
              type: 'success'
            })
            this.getMyAlbum()
            this.folderChecked = -1
            this.isEditFolder = false
          }
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'info'
        })
      })
    },
    // 提交表单 - 新建/编辑
    submitFolderForm(formName) {
      this.folderForm.img_path = this.$refs.childUpload.imageUrl
      console.log(this.folderForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          FetchSaveThemeFolder(this.folderForm).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '创建文件夹成功',
                duration: 2000,
                type: 'success'
              })
              this.mkdirVisible = false
              this.getMyAlbum()
            } else {
              this.$message({
                message: '创建文件夹失败',
                duration: 2000,
                type: 'warning'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 点击-移动btn
    moveingTo(index) {
      this.folderList = []
      if (this.materialFolders.length > 0) {
        this.folderList = this.materialFolders.slice(0, this.materialFolders.length)
      }
      this.rootFolderId = localStorage.getItem('rootFolderId')
      const returnFolder = {
        id: this.rootFolderId,
        name: '返回上一级'
      }
      this.folderList.unshift(returnFolder)
      this.movingVisible = true
    },
    // 文件夹list - 选中操作
    wjjSelected(item, index) {
      this.folderListChecked = index
      this.thisFoldId = item.id
    },
    // 点击确定 - 移动素材
    moveFile() {
      if (this.materialFolders.length > 0) {
        if (this.thisFoldId == this.rootFolderId) {
          this.$message({
            message: '不能讲文件移动到自身目录下哦~',
            type: 'error'
          })
          return
        }
      } else {
        this.thisFoldId = this.rootFolderId
      }
      const params = {
        'folder_id': this.thisFoldId,
        'ids': this.selectInFolderid,
        'material_ids': this.selectedListId
      }
      FetchMoveMyThemeMaterial(params).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '移动成功',
            type: 'success'
          })
          this.movingVisible = false
          this.getMyAlbum()
          this.selectedListId = []
          this.selectInFolderid = []
        }
      })
    },
    // 即时发布/定时发布
    publishHandle(index) {
      localStorage.removeItem('selectedMaterial')
      localStorage.removeItem('releaseId')
      this.selectedMaterial = this.filterArrObj(this.selectedMaterial, 'material_id')
      // 判断是否选择了多个音频文件
      const resultAudio = []
      this.selectedMaterial.map(item => {
        if (item.material_type == 2) {
          resultAudio.push(item)
        }
      })
      if (resultAudio.length > 1) {
        this.$message.error('音频类型的文件只可选择1个')
        return
      }
      localStorage.setItem('selectedMaterial', JSON.stringify(this.selectedMaterial))
      this.$router.push(
        {
          path: '/release', query: { tag: index }
        }
      )
    },
    // 主题库存在重复得情况，发布前过滤
    filterArrObj(arr, filterField) {
      const newArr = arr.reduce((pre, cur) => pre.some(item => item[filterField] == cur[filterField])
        ? pre : [...pre, cur], [])
      return newArr
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tabs {
  margin-bottom: 0;
}
::v-deep .el-tabs__item.is-active {
  color: #3a8aeb;
}
.theme_img {
  .theme_mkdir {
    position: relative;
    width: 140px;
    height: 250px;
    margin: 0 24px 24px 0;
    &.cont_upload .font-icon {
      width: 45px;
      height: 45px;
      margin-bottom: 20px;
    }
    &.folder .font-icon {
      width: 84px;
      height: 69px;
    }
    .icon_bg{
      img{
        display: block;
        width: 140px;
        height: 250px;
      }
    }
  }
  .theme_item {
    width: 140px;
    height: 250px;
  }
  .icon_bg {
    height: 220px;
  }
  .theme_item {
    .file_name {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 30px;
      background: rgba(255, 255, 255, 0.6);
      line-height: 30px;
    }
  }
}
.material_crumbs {
  padding: 0 0 15px 0;
  line-height: 30px;
  background: #fff;
  ::v-deep .el-breadcrumb {
    font-size: 12px;
    color: #999999;
  }
}
</style>
