<template>
  <div>
    <div v-if="isToFolder" class="material_crumbs">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item><a href="/content">素材库</a></el-breadcrumb-item>
        <el-breadcrumb-item>{{ currentFolder }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="material_content">
      <!-- 上传 / 创建文件夹 -->
      <div class="material_item cont_upload">
        <Upload ref="uploadMaterial" @saveMaterial="saveMaterial" />
        <el-button v-if="!isToFolder" class="mkdir_btn" round type="primary" @click="handleMkdir(0)">创建文件夹</el-button>
        <el-button v-else class="return_btn" round type="primary"><a href="/content">返回</a></el-button>
      </div>
      <!-- 文件夹list -->
      <div v-for="(item,index) in materialFolders" :key="item.id" :class="['material_item', '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 materialList" :key="'list-'+index" :class="['material_item', 'item_cont', { 'item_multi': selectedListId.includes(item.material_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>

    <!-- 创建文件夹layer / 编辑 -->
    <div class="publish_layer">
      <el-dialog :title="layerTitle" :close-on-click-modal="false" :show-close="false" :visible.sync="mkdirVisible" width="616px">
        <el-form ref="folderForm" :inline="true" :model="folderForm" size="small" label-width="100px">
          <el-form-item
            :label="labelTxt"
            prop="name"
            :rules="[
              { required: true, message: '请输入名称', trigger: 'blur' }
            ]"
          >
            <el-input v-model="folderForm.name" style="width: 336px" />
          </el-form-item>
          <el-form-item v-if="formatType != 0" label="封面">
            <UploadCover ref="childUpload" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="!isEditMaterial" type="primary" round @click="submitForm('folderForm')">保 存</el-button>
          <el-button v-else type="primary" round @click="saveMaterial">保 存</el-button>
          <el-button round @click="resetForm()">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 多选操作 -->
    <div v-if="selectedListId.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" :disabled="selectedListId.length > 1" @click="editContent()">编辑</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="deleteMyMaterial">删除</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="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 { getMaterialList, saveMaterialFolder, deleteMaterialFolder, saveMaterial, deleteMyMaterial, moveMyMaterial } from '@/api/material/material'
import Upload from '../../components/upload'
import UploadCover from '../../components/upload_cover'
import { getSeconds, getFileFormat } from '@/utils/index.js'
export default {
  name: 'Material',
  components: { Upload, UploadCover },
  filters: {
    getSeconds(s) {
      return getSeconds(s)
    },
    getFileFormat(s) {
      return getFileFormat(s)
    }
  },
  props: {
    isMultiSelected: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      orga_id: '133221333123111', // 机构ID
      rootFolderId: null, // 根目录文件夹ID
      thisFoldId: null, // 当前父文件夹ID
      folderList: [], // 文件夹list
      materialFolders: [], // 文件夹list
      folderForm: { // form
        fid: '',
        id: '',
        img_path: '',
        name: '',
        orga_id: ''
      },
      isEditFolder: false, // 是否编辑文件夹
      mkdirVisible: false, // 新建编辑layer
      folderChecked: -1, // 文件夹是否单击选中
      materialList: [], // 素材库list
      isEditMaterial: false, // 是否是编辑素材
      formatType: null, // 上传素材类型 0 img 1 video 2 audio
      materialId: null, // 编辑时需要参数 id
      materialImgPath: '', // 素材封面
      materialDuration: 0, // 时长
      materialName: '', // 素材名称
      uploadFileUrl: null, // 素材保存路径
      selectedMaterial: [], // 素材选中
      selectedListId: [], // 素材选中的material_id
      selectinFolderid: [], // 素材选中的和文件关联表id -- in_folder_id
      layerTitle: '创建文件夹', // 文件夹/素材编辑框title
      labelTxt: '文件夹名称',
      isToFolder: false, // 是否进入文件夹
      currentFolder: '', // 当前进入的文件夹名
      currentFolderId: null,
      movingVisible: false,
      uploadListData: [ // 上传列表
      ],
      folderListChecked: -1,
      wjjList: []
    }
  },
  computed: {
    defaultImg() {
      return 'this.src="' + require('@/assets/images/menu_bg_02.png') + '"'
    }
  },
  watch: {
    isMultiSelected(newName, oldName) {
      console.log('newName', newName)
      if (newName === false) {
        this.selectedListId = []
      }
    },
    '$route.query.folderTag'(Val) {
      console.log(Val)
    }
  },
  mounted: function() {
    console.log(this.$route.query.folderTag)
    this.getMaterialList()
    document.addEventListener('click', this.hiddenFolderActiveClick)
  },
  methods: {
    // 获取素材库list
    getMaterialList() {
      let params
      if (this.$route.query.folderTag) {
        console.log('文件夹内')
        this.isToFolder = true
        this.currentFolder = localStorage.getItem('currentFolder')
        this.currentFolderId = localStorage.getItem('currentFolderId')
        params = {
          'folder_id': this.currentFolderId,
          'material_name': null,
          'material_type': null,
          'orga_id': this.orga_id
        }
      } else {
        console.log('文件夹外')
        this.isToFolder = false
        localStorage.removeItem('currentFolder')
        localStorage.removeItem('currentFolderId')
        params = {
          'folder_id': null,
          'material_name': null,
          'material_type': null,
          'material_type_not': null,
          'orga_id': this.orga_id
        }
      }
      getMaterialList(params).then(res => {
        if (!this.$route.query.folderTag) {
          localStorage.setItem('rootFolderId', res.data.thisFoldId)
        }
        this.materialFolders = res.data.materialFolders
        this.materialList = res.data.pageThemeVO
        // 创建文件夹获取data
        this.thisFoldId = res.data.thisFoldId
      })
    },
    // 新建 / 编辑 文件夹
    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.isEditMaterial = false
      this.$router.replace(
        {
          path: '/content', query: { folderTag: 1 }
        }
      )
      this.currentFolder = item.name
      this.currentFolderId = item.id
      localStorage.setItem('currentFolder', this.currentFolder)
      localStorage.setItem('currentFolderId', this.currentFolderId)
      this.getMaterialList()
      this.selectedListId = []
      this.folderChecked = -1
      this.isEditFolder = false
    },
    // 点击其他区域选中的文件夹 去掉选中样式
    hiddenFolderActiveClick() {
      this.folderChecked = -1
      this.isEditFolder = false
    },
    // 选择 编辑 文件夹
    editFolder(item, index) {
      this.isEditMaterial = false
      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() {
      this.$confirm('此操作将永久删除该文件夹, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: this.folderForm.id
        }
        deleteMaterialFolder(params).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '删除文件夹成功',
              type: 'success'
            })
            this.getMaterialList()
            this.folderChecked = -1
            this.isEditFolder = false
          }
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'info'
        })
      })
    },
    // 提交表单 - 新建/编辑
    submitForm(formName) {
      this.folderForm.img_path = this.$refs.childUpload.imageUrl
      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveMaterialFolder(this.folderForm).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '创建文件夹成功',
                duration: 2000,
                type: 'success'
              })
              this.mkdirVisible = false
              this.getMaterialList()
            } else {
              this.$message({
                message: '创建文件夹失败',
                duration: 2000,
                type: 'warning'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置表单
    resetForm() {
      // 强制重置folderForm表单
      // Object.assign(this.$data.folderForm, this.$options.data.call(this).folderForm)
      this.mkdirVisible = false
    },
    // 选择素材 - to 即时发布/定时发布
    publishHandle(index) {
      this.$router.push(
        {
          path: '/release', query: { tag: index }
        }
      )
      localStorage.removeItem('selectedMaterial')
      localStorage.setItem('selectedMaterial', JSON.stringify(this.selectedMaterial))
    },
    // 素材 - 编辑
    editContent() {
      this.mkdirVisible = true
      this.labelTxt = '文件名称'
      this.isEditMaterial = true
      if (this.formatType == 1) {
        this.layerTitle = '视频编辑'
      } else if (this.formatType == 2) {
        this.layerTitle = '音频编辑'
      } else {
        this.layerTitle = '图片编辑'
      }
      const checkedMaterial = this.materialList.filter(item => {
        return item.material_id == this.selectedListId[0]
      })
      this.materialId = checkedMaterial[0].material_id
      this.folderForm.name = checkedMaterial[0].material_name
      this.materialDuration = checkedMaterial[0].duration
      this.uploadFileUrl = checkedMaterial[0].deposit_url
      this.materialImgPath = checkedMaterial[0].img_path
    },
    // 上传素材
    saveMaterial() {
      if (!this.isEditMaterial) {
        console.log('新增')
        console.log(this.$refs.uploadMaterial.fileSize)
        const formatType = this.$refs.uploadMaterial.formatType
        this.uploadFileUrl = this.$refs.uploadMaterial.uploadFileUrl
        // 视频和音频的时长
        const duration = this.$refs.uploadMaterial.duration
        this.materialName = this.$refs.uploadMaterial.fileNames
        switch (formatType) {
          case 'image':
            this.formatType = 0
            this.materialImgPath = this.uploadFileUrl
            this.materialDuration = 0
            break
          case 'video':
            this.formatType = 1
            this.materialDuration = duration
            break
          case 'audio':
            this.formatType = 2
            this.materialDuration = duration
            break
        }
      } else {
        this.materialName = this.folderForm.name
        this.$nextTick(() => {
          if (this.$refs.childUpload) {
            this.materialImgPath = this.$refs.childUpload.imageUrl
          }
        })
      }
      setTimeout(() => {
        const params = {
          'class_ids': [
            // 素材类id集合
          ],
          'deposit_url': this.uploadFileUrl, // 素材存放路径
          'device_direction': 1, // 横竖屏 1.横屏 2.竖屏,
          'duration': this.materialDuration, // 时长s
          'material_id': this.materialId,
          'folder_id': this.thisFoldId, // 文件夹id
          'img_path': this.materialImgPath, // 封面图片id
          'material_name': this.materialName, // 素材名称
          'material_type': this.formatType, // 素材类别
          'file_size': this.$refs.uploadMaterial.fileSize, // 文件大小
          'orga_id': this.orga_id, // 机构id
          'store_type': 1 // 库类型 1.素材库 2.主题库
        }
        console.log(params)
        if (!this.isEditMaterial) {
          // 新上传素材时不需要该字段
          delete params.material_id
        }
        saveMaterial(params).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '上传素材成功',
              type: 'success'
            })
            this.mkdirVisible = false
            this.getMaterialList()
            this.materialImgPath = ''
          }
        })
      }, 200)
    },
    // 素材 - 多选
    selectedItem(item) {
      const id = item.material_id
      const inFolderId = item.in_folder_id
      const type = item.material_type
      const arr = this.selectedListId
      if (arr.includes(id)) {
        const index = arr.indexOf(id)
        if (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
      }
    },
    // 素材 - 删除
    deleteMyMaterial() {
      this.$confirm('此操作将永久删除该素材, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          ids: this.selectedListId
        }
        deleteMyMaterial(params).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '删除素材成功',
              type: 'success'
            })
            this.getMaterialList()
            this.selectedListId = []
          }
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'info'
        })
      })
    },
    UploadList() {
      this.uploadListVisible = true
    },
    // 点击-移动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
      }
      moveMyMaterial(params).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '移动成功',
            type: 'success'
          })
          this.movingVisible = false
          this.getMaterialList()
          this.selectedListId = []
        }
      })
    },
    format(percentage) {
      return percentage === 100 ? '100%' : `${percentage}%`
    },
    start() {
      const that = this
      that.$nextTick(() => {
        that.progressLoading = true
        that.percentage = 0
        that.timeStart = setInterval(() => {
          if (that.percentage < 100) {
            that.percentage += 1
          }
        }, 100)
      })
    },
    // 进度条结束
    end() {
      this.loading_txt = '继续'
      // const that = this
      // that.percentage = 100
      clearInterval(this.timeStart)
      // setTimeout(() => {
      //   that.progressLoading = false
      // }, 300)
    }
  }
}
</script>

<style lang="scss" scoped>
.material_crumbs {
  padding: 0 24px 15px 24px;
  ::v-deep .el-breadcrumb {
    font-size: 12px;
    color: #999999;
  }
}
.material_content {
  display: flex;
  flex-wrap: wrap;
  margin-left: 24px;
  .material_item {
    position: relative;
    width: 174px;
    height: 182px;
    border-radius: 4px;
    margin: 0 20px 20px 0;
    overflow: hidden;
  }
  .item_cont {
    border-color: #dcdde3;
    img {
      width: 100%;
      height: 148px;
    }
    .radio_img {
      width: 100%;
      height: 148px;
    }
  }
}
.upload_layer {
  ::v-deep .el-dialog__body {
    padding: 0 20px 30px 20px;
  }
}
::v-deep .el-table {
  .el-button {
    padding: 0 10px;
    height: 24px;
    &.upload_delt {
      background-color: #f76b6b;
    }
  }
}
.multi_handle {
  div {
    display: flex;
  }
}
</style>
