<template>
  <wrapper
    fill
    margin
    background
  >
    <div class="l-flex__none l-flex--row c-step">
      <div class="l-flex__none c-sibling-item o-button hidden" />
      <div class="l-flex__fill u-text-center">
        请选择需要上播的设备对应的宽高比并配置相关上播内容
      </div>
      <button
        class="l-flex__none c-sibling-item o-button"
        :class="{ hidden: hideNext }"
        @click="publish"
      >
        发布
      </button>
    </div>
    <div class="l-flex__fill l-flex has-padding">
      <ratio-tree-single
        ref="tree"
        class="c-sibling-item"
        @change="onChange"
      />
      <div class="c-sibling-item far c-list u-overflow-y--auto">
        <div class="l-flex--row c-sibling-item--v u-bold">上播时间</div>
        <div class="c-sibling-item--v far u-font-size--sm">优先级</div>
        <el-select
          v-model="priority"
          class="c-sibling-item--v near"
        >
          <el-option
            v-for="option in priorityOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
        <div class="c-sibling-item--v u-font-size--sm u-required">开始时间</div>
        <el-date-picker
          v-model="startDate"
          class="c-sibling-item--v near"
          type="datetime"
          placeholder="请选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          @change="onDateTimeChange('startDate')"
        />
        <div class="c-sibling-item--v u-font-size--sm u-required">结束时间</div>
        <el-date-picker
          v-model="endDate"
          class="c-sibling-item--v near"
          type="datetime"
          popper-class="is-hide-now"
          :disabled="!startDate"
          placeholder="请选择结束时间"
          :default-value="defaultEndDateDate"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="endPickerOptions"
          @change="onDateTimeChange('endDate')"
        />
      </div>
      <div class="l-flex--col c-sibling-item far c-list fill">
        <div class="l-flex--row c-sibling-item--v u-bold">
          <span class="c-sibling-item u-bold">上播内容</span>
          <i
            class="c-sibling-item el-icon-circle-plus-outline u-color--blue u-pointer"
            @click="onAddAsset"
          />
        </div>
        <draggable
          v-model="assets"
          class="l-flex__fill c-sibling-item--v far u-overflow-y--auto"
          handle=".mover"
          animation="300"
        >
          <div
            v-for="(asset, index) in assets"
            :key="asset.key"
            class="l-flex--row c-sibling-item--v o-publish-asset"
          >
            <div class="l-flex__auto l-flex--row mover">
              <i class="l-flex__none o-publish-asset__mover el-icon-sort has-active" />
              <div
                class="l-flex__auto o-publish-asset__name u-ellipsis has-active u-pointer"
                @click="onViewAssetItem(asset)"
              >
                {{ asset.tagInfo }} {{ asset.name }}
              </div>
            </div>
            <template v-if="needDuration">
              <span class="l-flex__none u-color--info">上播时长(s)：</span>
              <el-input-number
                v-model="asset.duration"
                class="l-flex__none o-publish-asset__seconds"
                controls-position="right"
                :min="1"
                :max="86400"
                :step="1"
                :disabled="asset.disabled"
                step-strictly
              />
            </template>
            <i
              class="l-flex__none o-publish-asset__del el-icon-delete has-active u-pointer"
              @click="onDelAsset(asset, index)"
            />
          </div>
        </draggable>
      </div>
    </div>
    <table-dialog
      ref="assetTableDialog"
      title="上播内容选择"
      :schema="assetTableSchema"
      @choosen="onChoosenAsset"
    />
    <preview-dialog ref="previewDialog" />
  </wrapper>
</template>

<script>
import {
  AssetTagInfo,
  AssetType,
  EventFreq,
  EventTarget,
  PublishType,
  PublishTargetType,
  EventPriority,
  EventPriorityInfo
} from '@/constant'
import {
  parseTime,
  getAssetDuration
} from '@/utils'
import { toDate } from '@/utils/event'
import { publish } from '@/api/platform'
import { assetTableMixin } from '@/mixins/asset-table'
import Draggable from 'vuedraggable'

export default {
  name: 'DeployRatio',
  components: {
    Draggable
  },
  mixins: [assetTableMixin],
  data () {
    return {
      priority: EventPriority.INSERTED,
      priorityOptions: [
        { value: EventPriority.SCHEDULING, label: EventPriorityInfo[EventPriority.SCHEDULING] },
        { value: EventPriority.INSERTED, label: EventPriorityInfo[EventPriority.INSERTED] },
        { value: EventPriority.EMBEDDED, label: EventPriorityInfo[EventPriority.EMBEDDED] },
        { value: EventPriority.EMERGENT, label: EventPriorityInfo[EventPriority.EMERGENT] }
      ],
      productType: null,
      startDate: null,
      endDate: null,
      assets: []
    }
  },
  computed: {
    hideNext () {
      return !this.productType || !this.startDate || !this.endDate || this.assets.length === 0
    },
    defaultEndDateDate () {
      if (this.startDate) {
        const date = new Date(this.startDate)
        date.setDate(date.getDate() + 1)
        return `${parseTime(date, '{y}-{m}-{d}')} 00:00:00`
      }
      return null
    },
    pickerOptions () {
      return {
        disabledDate: this.isDisableDate
      }
    },
    endPickerOptions () {
      return {
        disabledDate: this.isDisableEndDate
      }
    },
    minDate () {
      const now = new Date()
      return new Date(now.getFullYear(), now.getMonth(), now.getDate())
    },
    needDuration () {
      return this.assets.length > 1
    }
  },
  methods: {
    isDisableDate (date) {
      return date < this.minDate
    },
    isDisableEndDate (date) {
      if (date < this.minDate) {
        return true
      }
      const startDate = this.startDate
      if (startDate) {
        return date < new Date(startDate.replace(/\d{2}:\d{2}:\d{2}$/, '00:00:00'))
      }
      return false
    },
    onDateTimeChange (type) {
      const { startDate, endDate } = this
      if (startDate && endDate && startDate > endDate) {
        if (type === 'startDate') {
          this.endDate = startDate
        } else {
          this.startDate = endDate
        }
      }
    },
    onChange (productType) {
      this.productType = productType
    },
    onAddAsset () {
      this.$refs.assetTableDialog.show()
    },
    onChoosenAsset ({ value, done }) {
      const { tag, type, keyName, originalName, size, md5 } = value
      this.assets.push({
        key: `${Date.now()}_${Math.random().toString(16).slice(2)}`,
        tag,
        type,
        keyName,
        size,
        md5,
        tagInfo: AssetTagInfo[tag],
        name: originalName,
        duration: getAssetDuration(value),
        disabled: type === AssetType.VIDEO
      })
      done()
    },
    onDelAsset (asset, index) {
      this.assets.splice(index, 1)
    },
    onError (message) {
      this.$message({
        type: 'warning',
        message
      })
      return Promise.reject()
    },
    getPublishTarget () {
      if (this.startDate === this.endDate) {
        return this.onError('开始时间与结束时间不能一样')
      }
      const sources = this.assets.map(({ tag, type, keyName, duration, size, md5 }) => {
        return { tag, type, keyName, duration, size, md5 }
      })
      if (sources.length === 1) {
        sources.duration = Math.floor((toDate(this.endDate) - toDate(this.startDate)) / 1000)
      }
      return Promise.resolve({
        type: PublishTargetType.EVENT,
        detail: {
          freq: EventFreq.ONCE,
          start: this.startDate,
          until: this.endDate,
          priority: this.priority,
          target: {
            type: EventTarget.ASSETS,
            sources
          }
        }
      })
    },
    publish () {
      this.getPublishTarget().then(
        publishTarget => this.$confirm(
          '发布需审核生效，操作完成后请通知相关人员进行审核',
          `立即发布？`,
          {
            type: 'warning',
            confirmButtonText: '发布'
          }
        ).then(
          () => publish(
            PublishType.PRODUCT_TYPE,
            [this.productType.id],
            publishTarget,
            {
              programCalendarName: this.productType.name
            }
          )
        )
      ).then(() => {
        this.$refs.tree.reset()
        this.productType = null
        this.assets = []
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.c-step {
  padding: $spacing 0;
  margin: 0 $spacing;
  border-bottom: 1px solid $gray--light;

  .hidden {
    visibility: hidden;
  }
}

.c-list {
  flex: 0 0 auto;
  min-width: 200px;
  color: $black;

  & + & {
    padding-left: $spacing;
    border-left: 1px solid $gray--light;
  }

  &.fill {
    flex: 1 0 auto;
  }
}

.o-publish-asset {
  padding: 4px 0;
  border: 1px solid $gray;
  border-radius: $radius--mini;

  &.sortable-chosen {
    border-color: #c6e2ff;
    background-color: $blue--light;
  }

  &__mover {
    padding: 10px 16px;
    font-size: 18px;
    cursor: move;
  }

  &__name {
    padding: 16px 10px 16px 0;
  }

  &__seconds {
    width: 120px;
  }

  &__del {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    width: 50px;
    height: 40px;
    color: $gray;
    font-size: 18px;

    &.mini {
      width: 40px;
    }

    &:hover {
      color: $primary;
    }
  }
}
</style>
