<template>
  <div>
    <HoverPopup
      ref="popupMenu"
      icon="ios-more"
      color="#0a6afc"
      :width="80"
    >
      <ThMenuItem
        width="70"
        name="重命名"
        icon="ios-create"
        @on-click="activeRename"
        v-if="assetScope!='public'"
      />
      <ThMenuItem
        width="70"
        name="删除"
        icon="ios-trash"
        @on-click="deleteAsset"
        v-if="assetScope!='public'"
      />
      <ThMenuItem
        width="70"
        name="替换"
        icon="ios-archive"
        @on-click="replaceAsset"
        v-if="assetScope!='public'"
      />
      <ThMenuItem
        width="70"
        name="查看原图"
        icon="ios-eye"
        @on-click="checkImage"
      />
    </HoverPopup>
    <div class="file-replace"><input type="file" style="display: none" :multiple="false" :accept="accept"></div>
  </div>
</template>

<script>
import {assetDelete,assetReplace} from '../../libs/request'
import util from '../../libs/util'
import config from '../../constants/config'
import HoverPopup from '../hover-popup'
import ThThMenuItem from '../th-menu-item'
export default {
  props: ['asset','index','assetScope','accept'],
  components: {HoverPopup,ThThMenuItem},
  methods: {
    deleteAsset() {
      let ownerId = config.USER
      this.$Modal.confirm({
        title: `确定要删除【${this.asset.name}】吗？`,
        content: '<p>该操作无法恢复，请谨慎操作！</p>',
        onOk: () => {
          assetDelete(ownerId, this.asset.assetId).then(() => {
            this.$emit('on-delete', this.asset.assetId)
            this.$Notice.success({
              title: '删除成功',
              duration: 3
            })
          })
        }
      })
    },
    checkImage() {
      window.open(`${util.getAPI('assets')}/${this.asset.owner}/${this.asset.assetId}`)
    },
    activeRename() {
      this.$emit("on-rename",{item:this.asset,index:this.index})
    },
    replaceAsset(){
      let input = this.$el.querySelector('.file-replace 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 request = assetReplace(ownerId, file, this.asset.name, this.asset.assetId)
            .then((res) => {
              this.$emit('on-replace',res.data)
            })
          if (request) {
            request.catch(err => {
              this.$Modal.error({
                  title: "替换失败",
                  content: file.name
              });
              throw err
            })
          }
        }
      }
      input.click()
    },
  },
  data() {
    return {}
  },
  computed: {},
  mounted(){
  }
}
</script>
