<template>
  <div  style="min-height:calc(100vh - 200px);margin-top: 20px;max-width:960px;">
    <el-toolbar>
      <el-button v-if="hasPrivs('Draft.Person.Resource.Add')" @click="create"><i class="fa fa-plus"></i>新建</el-button>
    </el-toolbar>
    <el-row type="flex" class="row-bg" align="middle">
      <el-col :span="9">
        <el-input v-model="searchData.title" placeholder="请输入标题" size="medium" @keyup.enter.native="search" />
      </el-col >
      <el-col :span="7" style="margin-left: 10px;">
        <el-select class="layout-select" placeholder="选择类型" clearable v-model="searchData.resourceType" @change="search">
           <el-option v-for="item in resourceTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-col>
      <el-col :span="7" style="margin-left: 10px;">
        <resource-tag-search :tags.sync="searchData.tags" ref="tagRef" @callback="search"></resource-tag-search>
      </el-col >
      </el-row>
      <div style="padding:3px"></div>
      <el-row type="flex" class="row-bg" align="middle">
      <el-col :span="9">
        <el-date-picker
          id="person-date-picker"
          class="layout-date-picker"
          v-model="searchData.dateInterval"
          type="datetimerange"
          start-placeholder="添加时间"
          @change="search" end-placeholder="添加时间"
          style="width:100%"
          :picker-options="selectDates">
        </el-date-picker>
      </el-col>
      <!-- <el-col :span="7"></el-col> -->
      <el-col :span="7" style="margin-left: 10px;">
        <el-button  type="primary" @click="search">
          <i class="fa fa-search"></i>搜索
        </el-button>
      </el-col>
    </el-row>
    <el-list-view
      class="catalog-resource-list"
      :data-read-url="getData"
      ref="multipleTable"
      :page-size="10"
      selectable
      :multi-operates="multiOperates">
      <template slot-scope="row">
        <div class="panel-card">
          <el-row :gutter="20">
            <el-col :span="5"  >
              <div class="resource-thumbnail" :class="row.resourceType=='audio'?'audio-resource-div':''">
                <div class="img-logo-file" v-if="row.resourceType=='image'||row.resourceType=='file'" :style="{backgroundImage:'url('+`${prefix}${row.logoFile}?${Date.now()}`+'),url(assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png)'}"></div>
                <audio-player v-if="row.resourceType=='audio'" :src="prefix+row.path" :title="row.oldName"  :auto-play="false"></audio-player>
                <video-player v-if="row.resourceType=='video'"  width="100%" height="100%" :src="prefix+row.path" :poster="prefix+row.logoFile" :title="row.oldName"  :auto-play="false"></video-player>
              </div>
            </el-col>
            <el-col :span="19">
              <el-row>
                <el-col :span="24" style="width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><img :src="row.icon"/><a class="list-card-title" href="javascript:void(0)" > {{row.oldName}}</a></el-col>
              </el-row>
              <div>
                <el-row>
                  <el-col :span="12"><span>大小：</span> <em>{{row.fileSize || '0kb'}}</em> </el-col>
                  <el-col :span="12"><span>内部名称：</span> <em>{{row.name || '无'}}</em> </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12"><span>资源类型：</span> <em>{{row.suffix}}{{row.resourceType|fixIcon}}</em> </el-col>
                  <el-col :span="12"><span>最后修改时间：</span> <em>{{(row.modifyTime?row.modifyTime:row.addTime)|fixDateTime}}</em> </el-col>
                </el-row>
              </div>
              <el-row>
                <el-col :span="24" class="tar">
                  <el-button type="text" title="复制资源路径" @click="copyResourceURL(row.path)"><i class="fa fa-copy"></i>复制资源路径</el-button>
                  <el-button v-if="hasPrivs('Draft.Person.Resource.Reload')" @click.stop="reload(row)" type="text" title="重新上传" >
                    <i class="fa fa-plus-square"></i>重新上传</el-button>
                  <el-button v-if="hasPrivs('Draft.Person.Resource.Cut')&&row.resourceType=='image'&&!row.path.startsWith('http')" @click.stop="cut(row)" type="text" title="裁剪" >
                    <i class="fa fa-scissors"></i>裁剪</el-button>
                  <el-button v-if="hasPrivs('Draft.Person.Resource.Del')" @click.stop="del(row)" type="text" title="删除" >
                    <i class="fa fa-remove"></i>删除</el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

        </div>
      </template>
    </el-list-view>

    <image-cutting-dialog :show.sync="imageCutData.show" :siteID="imageCutData.siteID" :imagePath="imageCutData.path" @callback="cutingCallBack"></image-cutting-dialog>
    <upload-resource :uploadType.sync="uploadType" @callback="cutingCallBack"></upload-resource>
    <el-dialog :visible.sync="copyDialogVisible" class="dialog-copy-resource-url" title="复制资源路径">
      <el-input ref="resourceCopyInput" v-model="copyPath">
        <el-button slot="append" @click="doCopyResourceURL($event)"><i class="fa fa-copy"></i></el-button>
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="copyDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import Privilege from '@src/common/privilege.js'
import clipboard from '@src/common/clipboard.js'
import CopyResourceDialog from '../contentcore/components/CopyResourceDialog.vue'
import ImageCuttingDialog from '../contentcore/commonImageCuttingDialog.vue'
import AudioPlayer from '@src/components/AudioPlayer.vue'
import VideoPlayer from '@src/components/VideoPlayer.vue'
import UploadResource from './components/uploadResource.vue'
import ResourceTagSearch from './ResourceTagSearch.vue'
export default {
  components: {
    'copy-dialog': CopyResourceDialog,
    'image-cutting-dialog': ImageCuttingDialog,
    'audio-player': AudioPlayer,
    'video-player': VideoPlayer,
    'upload-resource': UploadResource,
    'resource-tag-search': ResourceTagSearch
  },
  filters: {
    fixIcon: function(type) {
      switch (type) {
        case 'image':
          return '图片资源'
        case 'audio':
          return '音频资源'
        case 'video':
          return '视频资源'
        case 'file':
          return '文件资源'
        default:
          return '无'
      }
    },
    fixDateTime: function(val) {
      return val ? util.formatDate(val, 'yyyy-MM-dd HH:mm') : '无'
    }
  },
  data() {
    return {
      searchData: {
        resourceType: '',
        tags: '',
        title: '',
        dateInterval: ''
      },
      resourceTypes: [],
      selectDates: {
        shortcuts: [
          {
            text: '最近一天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      prefix: this.$root.prefix,
      editorMode: '',
      editorConfig: '',
      initfileList: {
        platformID: null,
        siteID: null,
        platformPath: ''
      },
      imageCutData: {
        show: false,
        siteID: '',
        path: ''
      },
      uploadType: {},
      siteID: 0,
      multiOperates: [
        {
          label: '删除',
          value: 'delete',
          fn: rows => {
            this.deleteResources(rows)
          }
        }
      ],
      siteInfo: null,
      copyPath: '',
      copyDialogVisible: false
    }
  },
  created() {
    this.getResources()
  },
  methods: {
    // 批量删除内容
    deleteResources(rows) {
      if (!Privilege.hasPriv('Draft.Person.Resource.Del')) {
        util.showError('您没有操作权限！')
        return
      }

      this.$confirm(`确认删除选择的<span class='icon-danger'>${rows.length}个</span>资源吗？`, {
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      })
        .then(async r => {
          let IDs = _.map(rows, 'ID').join()
          let res = await axios.delete(`/ui/resourcelibray/${IDs}`)
          util.showResponseMessage(res.data)
          res.data.status === 1 && this.search()
        })
        .catch(err => { console.error(err) })
    },
    hasPrivs: function(val) {
      return !!(val && Privilege.hasPriv(val))
    },
    async getResources() {
      let res = await axios.get(`/ui/platform/codes/CatalogResourceType`)
      this.resourceTypes = res.data.data
      this.siteID = res.data.siteID
    },
    getData() {
      let params = Object.assign({}, this.searchData, {
        tags: encodeURIComponent(this.searchData.tags),
        title: encodeURIComponent(this.searchData.title)
      })
      if (this.searchData.dateInterval) {
        params = Object.assign({}, params, {
          startTime: Date.parse(this.searchData.dateInterval[0]),
          endTime: Date.parse(this.searchData.dateInterval[1])
        })
      }
      return ['/ui/resourcelibray/person', { params }]
    },
    create(type) {
      type = type ? 'file' : type
      this.uploadType = Object.assign({}, { show: true, type: type })
    },
    reload(row) {
      this.uploadType = Object.assign({}, { ID: row.ID, show: true, type: row.resourceType })
    },
    cut(row) {
      if (this.disabled || !row.path || row.resourceType !== 'image') {
        return
      }
      if (row.path.toLowerCase().startsWith('http')) {
        this.$alert('网络图片不能剪切！', '提示', {
          type: 'info'
        })
        return
      }
      if (row.path.toLowerCase().startsWith('http')) {
        this.$alert('网络图片不能剪切！', '提示', {
          type: 'info'
        })
        return
      }
      this.imageCutData = Object.assign({ show: true }, row)
    },
    async del(row) {
      let ids = row && row.ID ? [row.ID] : util.getSelectedIDs(row)
      if (!ids || !ids.length) {
        this.$alert('请先选择一条记录！', '提示', {
          type: 'warning'
        })
        return
      }
      try {
        await this.$confirm('确认删除？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.delete(`/ui/resourcelibray/${ids.join(',')}`)
        util.showResponseMessage(res.data)
        res.data.status === 1 && this.search()
      } catch (e) {

      }
    },
    search() {
      this.$refs.multipleTable.getData()
    },
    cutingCallBack() {
      this.$refs.multipleTable.getData()
    },
    async copyResourceURL(path) {
      if (this.siteInfo === null) {
        this.siteInfo = await this.$root.getCurrentSite()
      }
      this.copyPath = this.siteInfo.siteURL + path
      this.copyDialogVisible = true
      this.$nextTick(_ => {
        this.$refs['resourceCopyInput'].select()
      })
    },
    doCopyResourceURL(evt) {
      clipboard(this.copyPath, evt, (result) => {
        if (result === 'success') {
          this.copyDialogVisible = false
          this.$message({
            message: '复制成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '复制失败，可能是您的浏览器不支持，可使用Ctrl+C直接复制',
            type: 'warning'
          })
          this.$refs['resourceCopyInput'].select()
        }
      })
    }
  }
}
</script>

<style scoped>
.upload-allow-hint {
  display: -webkit-box;
  display: -moz-box;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}

.el-pagination__rightwrapper {
  float: right;
}
.catalog-resource-list .logo-file {
  max-width: 124px;
  max-height: 108px;
  vertical-align: middle;
}
.img-logo-file {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 70%;
  overflow: hidden;
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  margin-top: 2px;
  margin-bottom: 2px;
}
.resource-thumbnail >>> .audio-player .audio-title {
  display: none;
}
.resource-thumbnail >>> .vjs-big-play-button {
  top: 68px !important;
  left: 70px !important;
  font-size: 3em !important;
  line-height: 1em !important;
  height: 1em !important;
  width: 2em !important;
  margin-left: -10px;
  margin-top: -4px;
}
.resource-thumbnail >>> .video-js .vjs-play-control {
  margin-top: 0.3em;
}
.resource-thumbnail >>> .video-js .vjs-control {
  width: 2em !important;
}
.resource-thumbnail >>> .video-js .vjs-mute-control {
  padding-left: 0em !important;
  padding-right: 0em !important;
}

.resource-thumbnail >>> .video-js .vjs-fullscreen-control {
  margin-top: 0.25em;
}
.resource-thumbnail >>> .video-js .vjs-progress-control {
  min-width: 2em !important;
}
.resource-thumbnail >>> .video-js .vjs-mute-control {
  padding-left: 1em !important;
  padding-right: 1em !important;
}
.resource-thumbnail >>> .video-js .vjs-time-control {
  padding-left: 0em !important;
  padding-right: 0em !important;
}
.resource-thumbnail >>> .video-js .vjs-volume-panel {
  display: none;
}
.resource-thumbnail >>> .video-js .vjs-fullscreen-control {
  margin-top: 0.2em;
}
.catalog-resource-list .resource-thumbnail {
  height: 120px;
}
.catalog-resource-list >>> .audio-resource-div {
  padding-top: 2.2em;
}
.dialog-copy-resource-url >>> .el-dialog {
  width: 600px;
 }
</style>
<style>
.catalog-resources-upload-dlg .el-dialog {
  width: 400px;
}
@media (max-width: 480px) {
  .catalog-resources-upload-dlg .el-dialog {
    width: 96%;
  }
}

</style>
