<template>
  <div class="th-provider-panel full">
    <div class="top">
      <div class="top-left">
        <Input search clearable class="search inline" placeholder="请输入关键词筛选" v-model="keyword"/>
        <div class="tools inline" v-if="assetScope==='private'">
          <div class="file-upload" @click="selectFile" style="float: right;">
            <input type="file" style="display: none" :multiple="true" :accept="accept">
            <div class="icon-button">
              <Icon type="md-add" />
              <span>添加</span>
            </div>
          </div>
        </div>
      </div>
      <ThRadioGroup
        v-model="assetScope"
        :btns="[
          { name: '我的素材', value: 'private' },
          { name: '公共素材', value: 'public' },
        ]"
        @on-change="assetScopeChange"
        style="width: 150px;float: right;" 
      />
    </div>
    <AssetList class="list inline" :hideChange="hideChange" :assetFilterList="displayList" :selectedMenu="selectedMenu" :showEmptyAsset="showEmptyAsset" @on-select="selectAsset" @on-delete="deleteAsset" @on-update="updateAsset" @on-replace="replaceAsset" :assetScope="assetScope" :assetTitle="assetTitle" :accept="accept"/>
  </div>
</template>

<script>
import _ from 'lodash'
import util from '../../libs/util'
import config from '../../constants/config'
import AssetList from './AssetList.vue'
import ThRadioGroup from '../th-radio-group'
import {assetList,assetReplace} from '../../libs/request'
import moment from 'moment'
import IconButton from '../icon-button'
const fileTypes = {
  image: ['jpg', 'png', 'gif', 'svg', 'jpeg', 'bmp'],
  json: ['json', 'geojson'],
  video: ['mp4', 'ogg', 'webm']
}
export default {
  components: {AssetList,ThRadioGroup,IconButton},
  props: {
    value: String,
    type: String,
    selectedMenu:String,
    editByUrl:Boolean,
    assetTitle:String,
    showEmptyAsset:Boolean,
    hideChange:Boolean
  },
  methods: {
    getAssetList(ownerId){
      assetList(ownerId).then(res => {
          this.assetList=this.organizeAssetList(res.data)
        })
    },
    organizeAssetList(list){
      let newList = list.map(lt => {
        let assetIdArray = lt.assetId.split('.')
        lt.type = assetIdArray.pop()
        let timestamp =new Date().getTime();
        lt.thumbnail = `${util.getAPI('assets')}/${lt.owner}/${
          lt.assetId
        }?thumbnail=173X90&t=${timestamp}`
        lt.updatedAt = moment(lt.updatedAt).format('YYYY-MM-DD HH:mm:ss')
        lt.createdAt = moment(lt.createdAt).format('YYYY-MM-DD HH:mm:ss')
        return lt
      })
      // 按时间降序
      newList = _.orderBy(newList, ['createdAt', 'name'], ['desc', 'desc'])
      return newList
    },
    assetScopeChange(value){
      this.assetScope=value
      this.refreshAssets()
    },
    refreshAssets() {
      let ownerId=null
      if(this.assetScope==="private"){
        ownerId = config.USER
      }else{
        ownerId = config.PUBLIC_USER
      }
      this.getAssetList(ownerId)
    },
    selectAsset(item){
      this.selectedItem = item
      this.$emit('on-select', this.selectedItem)
    },
    selectFile() {
      let input = this.$el.querySelector('.file-upload input')
      input.onchange = e => {
        if (e.target.files.length === 0) {
          return
        }
        let ownerId = config.USER
        for(let i = 0;i < e.target.files.length;i++) {
          let file = e.target.files[i]
          let {name} = file
          let request = null
          let nameArr = name.split('.')
          let assetId = `${this.selectedMenu}/${nameArr[0].replace(/\s+/g,"_")}-${util.generateId()}.${nameArr[nameArr.length-1]}`
          request = assetReplace(ownerId, file, util.splitFileName(name), assetId)
            .then(() => {
              this.getAssetList(ownerId)
            })
          if (request) {
            request.catch(err => {
              this.$Modal.error({
                  title: "上传失败",
                  content: file.name
              });
              throw err
            })
          }
        }
      }
      input.click()
    },
    replaceAsset(data){
      let index=this.assetList.findIndex(o=>o.assetId===data.assetId)
      this.assetList.splice(index,1,data)
      this.organizeAssetList(this.assetList)
    },
    deleteAsset(assetId){
      let index = this.assetList.findIndex(l => l.assetId === assetId)
      if (index !== -1) {
        this.assetList.splice(index, 1)
      }
    },
    updateAsset({assetId, data}){
      let assetItem = this.assetList.find(item => item.assetId === assetId)
      if (!assetItem) {
        return
      }
      Object.assign(assetItem, data)
    }
  },
  mounted() {
    this.refreshAssets()
  },
  data() {
    return {
      dlg: false,
      selectedItem: null,
      keyword: '',
      currentMode: 'icon',
      assetList:[],
      assetScope:'private', // 数据类型，私有还是公共
    }
  },
  computed: {
    displayList() {
      let list = []
      let assets=_.cloneDeep(this.assetList)
      if (this.keyword !== '') {
        list = assets.filter((s) => s.name.indexOf(this.keyword) > -1)
      } else {
        list = assets
      }
      let filterList=[]
      list.forEach(asset => {
        let assetId=asset.assetId.split("/")
        if(assetId[0]===this.selectedMenu){
          filterList.push(asset)
        }
      });
      return filterList
    },
    // 允许上传的文件类型
    accept() {
      return fileTypes[this.type].reduce((pre, item) => {return `.${item},${pre}`}, '')
    }
  },
  watch:{
  }
}
</script>