<template>
  <schema-table
    ref="table"
    :schema="schema"
  >
    <confirm-dialog
      ref="editDialog"
      title="新增数据集"
      @confirm="onSave"
    >
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label required">名称</span>
        <el-input
          v-model.trim="dataset.name"
          placeholder="最多20个字符"
          maxlength="20"
          clearable
        />
      </div>
    </confirm-dialog>
    <table-dialog
      ref="assetDialog"
      :title="assetDialogName"
      size="medium fixed"
      :schema="assetSchema"
    />
    <preview-dialog ref="previewDialog" />
    <table-dialog
      ref="assetAddDialog"
      title="上播内容选择"
      :schema="assetAddSchema"
      @choosen="onChoosenAsset"
    />
    <table-dialog
      ref="deviceDialog"
      :title="deviceDialog"
      :schema="deviceSchema"
    />
  </schema-table>
</template>

<script>
import {
  State,
  AssetTag,
  AssetTagInfo,
  AssetType,
  AssetTypeInfo
} from '@/constant'
import {
  parseDuration,
  getAssetThumb
} from '@/utils'
import {
  getAssets,
  getDatasets,
  addDataset,
  updateDataset,
  getDataset,
  deleteDataset,
  bindAssetToDataset,
  unbindAssetsFromDataset,
  getDevicesByDataset,
  updateDatasetAssetDuration
} from '@/api/asset'

export default {
  name: 'DatasetTable',
  props: {
    tenant: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      schema: {
        buttons: [
          { type: 'add', on: this.onAdd }
        ],
        list: this.getDatasets,
        cols: [
          { prop: 'name', label: '名称', render: (data, h) => h('edit-input', {
            props: {
              value: `${data.name}`,
              maxlength: 20
            },
            on: { edit: val => this.onEditName(data, val) }
          }) },
          // { label: '使用情况', type: 'tag', render: ({ delFlag }) => {
          //   return {
          //     type: ['primary', 'success'][delFlag],
          //     label: ['暂未使用', '已使用'][delFlag]
          //   }
          // }, width: 120, align: 'center' },
          { type: 'invoke', render: [
            { label: '上播内容', on: this.onEdit },
            { label: '查看关联设备', on: this.onViewDevices },
            { label: '删除', on: this.onDel }
          ], width: 240 }
        ]
      },
      assetSchema: {
        buttons: [
          { type: 'add', on: this.onAddAsset }
        ],
        list: this.getAssetsByDataset,
        transform: this.transformDatasetAsset,
        cols: [
          { prop: 'tagInfo', label: '类型', align: 'center', width: 80 },
          { prop: 'typeName', label: '文件', align: 'center', width: 80 },
          { prop: 'file', label: '', type: 'asset', on: this.onViewAsset },
          { prop: 'name', label: '' },
          { label: '上播时长(s)', render: (data, h) => data.type === AssetType.IMAGE
            ? h('edit-input', {
              staticClass: 'border',
              props: {
                value: `${data.adDuration}`,
                align: 'center'
              },
              on: {
                edit: val => this.onEditAssetDuration(data, val)
              }
            })
            : parseDuration(data.adDuration), width: 100, align: 'center' },
          { type: 'invoke', render: [
            { label: '查看', on: this.onViewAssetItem },
            { label: '移除', on: this.onDelAsset }
          ] }
        ]
      },
      assetAddSchema: {
        condition: { status: State.AVAILABLE_TENANT, tag: AssetTag.PUBLICITY, type: AssetType.IMAGE, originalName: '' },
        list: getAssets,
        transform: this.transformAsset,
        filters: [
          { key: 'tag', type: 'select', options: [
            { value: AssetTag.PUBLICITY, label: AssetTagInfo[AssetTag.PUBLICITY] },
            { value: AssetTag.LOCAL_PUBLICITY, label: AssetTagInfo[AssetTag.LOCAL_PUBLICITY] },
            { value: AssetTag.SHIM, label: AssetTagInfo[AssetTag.SHIM] }
          ] },
          { key: 'type', type: 'select', options: [
            { value: AssetType.IMAGE, label: AssetTypeInfo[AssetType.IMAGE] },
            { value: AssetType.VIDEO, label: AssetTypeInfo[AssetType.VIDEO] }
          ] },
          { key: 'originalName', type: 'search', placeholder: '素材名称' }
        ],
        cols: [
          { prop: 'file', label: '文件', type: 'asset', on: this.onViewAsset },
          { prop: 'name', label: '' },
          { prop: 'diff', label: '其他', 'align': 'right' },
          { type: 'invoke', render: [
            { label: '查看', on: this.onViewAssetItem }
          ] }
        ]
      },
      deviceSchema: {
        list: getDevicesByDataset,
        cols: [
          { prop: 'name', label: '名称' },
          { prop: 'address', label: '地址' }
        ]
      },
      datasetName: '',
      dataset: {}
    }
  },
  computed: {
    assetDialogName () {
      return `${this.datasetName}的上播内容`
    },
    deviceDialog () {
      return `${this.datasetName}关联的设备`
    }
  },
  watch: {
    tenant () {
      this.$refs.table.pageTo(1)
    }
  },
  methods: {
    getDatasets (params) {
      return getDatasets({
        tenant: this.tenant,
        ...params
      })
    },
    onAdd () {
      this.dataset = { name: '' }
      this.$refs.editDialog.show()
    },
    onSave (done) {
      const { name } = this.dataset
      if (!name) {
        this.$message({
          type: 'warning',
          message: '请填写数据集名称'
        })
        return
      }
      addDataset({
        name,
        tenant: this.tenant
      }).then(() => {
        done()
        this.$refs.table.pageTo()
      })
    },
    onEditName (dataset, { newVal, oldVal }) {
      if (newVal === oldVal) {
        return
      }
      if (!newVal) {
        this.$message({
          type: 'warning',
          message: '请填写数据集名称'
        })
        return
      }
      dataset.name = newVal
      updateDataset({
        id: dataset.id,
        name: newVal
      }).catch(() => {
        dataset.name = oldVal
      })
    },
    onEdit ({ id, name }) {
      this.datasetName = name
      this.$datasetId = id
      this.$refs.assetDialog.show()
    },
    getAssetsByDataset () {
      return getDataset(this.$datasetId).then(({ data: { mediaList } }) => {
        return {
          data: mediaList
        }
      })
    },
    transformDatasetAsset (asset) {
      asset.tagInfo = AssetTagInfo[asset.tag]
      asset.typeName = AssetTypeInfo[asset.type]
      asset.file = {
        type: asset.type,
        url: asset.keyName,
        thumbnail: getAssetThumb({
          type: asset.type,
          keyName: asset.keyName,
          screenshot: asset.minioData.screenshot
        })
      }
      asset.name = asset.minioData.originalName
      return asset
    },
    transformAsset (asset) {
      asset.file = {
        type: asset.type,
        url: asset.keyName,
        thumbnail: getAssetThumb(asset)
      }
      asset.name = asset.originalName
      asset.diff = parseDuration(asset.duration)
      return asset
    },
    onAddAsset () {
      this.$refs.assetAddDialog.show()
    },
    onViewAssetItem ({ file }) {
      this.onViewAsset(file)
    },
    onViewAsset (file) {
      this.$refs.previewDialog.show(file)
    },
    onChoosenAsset ({ value: { tag, type, keyName, duration }, done }) {
      bindAssetToDataset(this.$datasetId, {
        tag,
        type,
        keyName,
        adDuration: duration || 5
      }).then(() => {
        done()
        this.$refs.assetDialog.getTable().pageTo()
      })
    },
    onEditAssetDuration (asset, { newVal, oldVal }) {
      if (!newVal || !/^\d+$/.test(newVal) || Number(newVal) < 1) {
        return
      }
      if (newVal !== oldVal) {
        asset.adDuration = Number(newVal)
        updateDatasetAssetDuration(asset.relationId, asset.adDuration).catch(() => {
          asset.adDuration = oldVal
        })
      }
    },
    onDelAsset ({ keyName }) {
      unbindAssetsFromDataset(this.$datasetId, [keyName]).then(() => {
        this.$refs.assetDialog.getTable().pageTo()
      })
    },
    onViewDevices ({ id, name }) {
      this.datasetName = name
      this.$refs.deviceDialog.show({ datasetId: id })
    },
    onDel (dataset) {
      deleteDataset(dataset).then(() => {
        this.$refs.table.decrease(1)
      })
    }
  }
}
</script>
