<template>
  <table-dialog
    ref="dialog"
    title="垫片"
    :schema="schema"
  >
    <single-asset-dialog
      ref="assetDialog"
      :choosen="onChoosenAsset"
      @directory-changed="onAssetDirectoryChanged"
      @view="onViewAsset"
    />
    <preview-dialog ref="previewDialog" />
  </table-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { AssetType } from '@/constant'
import {
  getSpacers,
  addSpacers,
  deleteSpacer
} from '@/api/platform'

export default {
  name: 'SpacerTenantConfigDialog',
  data () {
    return {
      schema: {
        nonPagination: true,
        list: this.getSpacers,
        buttons: [
          { type: 'add', label: '新增图片', on: this.onAddImage },
          { type: 'add', label: '新增视频', on: this.onAddVideo }
        ],
        cols: [
          { prop: 'tagInfo', label: '类型', width: 80 },
          { prop: 'typeInfo', label: '资源', align: 'center', width: 72 },
          { prop: 'file', label: '', type: 'asset', on: this.onViewAsset },
          { prop: 'sizeInfo', label: '资源大小', 'align': 'right' },
          { prop: 'diff', label: '其他', 'align': 'right' },
          { type: 'invoke', render: [
            { label: '查看', on: this.onViewAsset },
            { label: '删除', on: this.onDel }
          ] }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['tenant'])
  },
  methods: {
    show () {
      this.$refs.dialog.show()
    },
    getSpacers () {
      return getSpacers({
        targetType: 2,
        targetKey: this.tenant
      })
    },
    onAddImage () {
      this.$refs.assetDialog.show(
        AssetType.IMAGE,
        this.directoryOption
      )
    },
    onAddVideo () {
      this.$refs.assetDialog.show(
        AssetType.VIDEO,
        this.directoryOption
      )
    },
    onAssetDirectoryChanged (directory) {
      this.directoryOption = directory
    },
    onViewAsset ({ file }) {
      this.$refs.previewDialog.show(file)
    },
    onChoosenAsset ({ tag, type, keyName, size, duration, md5 }) {
      return addSpacers({
        targetType: 2,
        targetKey: this.tenant,
        spacers: [
          { tag, type, keyName, size, duration, md5 }
        ]
      }).then(() => {
        this.$refs.dialog.getTable().pageTo(1)
      })
    },
    onDel (spacer) {
      deleteSpacer(spacer).then(() => {
        this.$refs.dialog.getTable().decrease(1)
      })
    }
  }
}
</script>
