<template>
  <confirm-dialog
    ref="configDialog"
    :title="title"
    @confirm="onSave"
  >
    <div class="c-grid-form auto u-align-self--center">
      <span class="c-grid-form__label">自助投放</span>
      <div class="l-flex--row c-grid-form__option">
        <el-switch
          v-model="attributes.enable"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </div>
      <span class="c-grid-form__label">单次时长(s)</span>
      <el-input-number
        v-model="attributes.minDuration"
        class="has-info"
        data-info="范围：5~600"
        controls-position="right"
        :min="5"
        :max="600"
        :step="5"
        step-strictly
      />
      <span class="c-grid-form__label">起投次数</span>
      <el-input-number
        v-model="attributes.minCount"
        controls-position="right"
        :min="1"
        :max="1000"
        step-strictly
      />
      <span class="c-grid-form__label">单价(分)</span>
      <el-input-number
        v-model="attributes.price"
        class="has-info"
        :data-info="price"
        controls-position="right"
        :min="1"
        :max="1000000000"
        step-strictly
      />
      <span class="c-grid-form__label">类型</span>
      <el-select
        v-model="attributes.tag"
        class="u-width--sm"
      >
        <el-option
          v-for="option in tagOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      <span class="c-grid-form__label">简介</span>
      <el-input
        v-model.trim="attributes.introduce"
        class="u-width--lg"
        type="textarea"
        :rows="3"
      />
      <span class="c-grid-form__label">简介图片</span>
      <div class="l-flex--row">
        <div
          v-for="(file, index) in files"
          :key="index"
          class="l-flex--row c-sibling-item u-relative"
        >
          <img
            class="c-media"
            :src="file.url"
          >
          <i
            class="l-flex__none c-media__del el-icon-delete has-active"
            @click="onDelFile(file, index)"
          />
        </div>
        <div
          v-show="files.length < 3"
          class="c-sibling-item c-media add u-pointer"
          @click="onSelect"
        >
          <i class="el-icon-plus" />
        </div>
        <!-- <el-upload
          ref="upload"
          class="c-config-dialog__upload"
          action="none"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onChange"
        >
          <button class="c-sibling-item o-button">
            上传 <i class="el-icon-upload el-icon--right" />
          </button>
        </el-upload> -->
      </div>
      <span class="c-grid-form__label">日均观看人次</span>
      <el-input
        v-model.trim="attributes.dailyFlow"
        class="u-width"
      />
      <span class="c-grid-form__label">男女比(%)</span>
      <el-input
        v-model.trim="attributes.gendeRatio"
        class="u-width"
      />
      <span class="c-grid-form__label">老少青比(%)</span>
      <el-input
        v-model.trim="attributes.ageRatio"
        class="u-width"
      />
    </div>
    <single-asset-dialog
      ref="assetDialog"
      :choosen="onChoosenAsset"
      @directory-changed="onAssetDirectoryChanged"
      @view="onViewAsset"
    />
    <preview-dialog ref="previewDialog" />
  </confirm-dialog>
</template>

<script>
import { AssetType } from '@/constant'
import {
  getAssetsByQuery,
  getAssetUrl
} from '@/api/asset'
import {
  getAdAttributes,
  updateAdAttributes,
  bindFileToAttributes
} from '../api'

export default {
  name: 'AdConfigDialog',
  data () {
    return {
      isAdd: false,
      attributes: {},
      files: [],
      schema: {
        list: getAssetsByQuery,
        cols: [
          { prop: 'file', label: '', type: 'asset' }
        ]
      },
      tagOptions: [
        { label: '不限', value: '' },
        { label: '商圈百货', value: '1' },
        { label: '星级酒店', value: '2' },
        { label: '地产物业', value: '3' },
        { label: '企业机构', value: '4' },
        { label: '机场车站', value: '5' },
        { label: '旅游景区', value: '6' },
        { label: '住宅社区', value: '7' },
        { label: '医疗机构', value: '8' },
        { label: '教育机构', value: '9' }
      ],
      directoryOption: null
    }
  },
  computed: {
    title () {
      return `${this.isAdd ? '新增' : '更新'}广告属性`
    },
    price () {
      const price = this.attributes.price || 0
      return `5秒 x ${this.attributes.minCount}次 = ${(price / 100).toFixed(2)}元`
    }
  },
  methods: {
    onChange ({ raw }) {
      this.$refs.upload.clearFiles()
      const isImg = raw.type === 'image/jpeg' || raw.type === 'image/png' || raw.type === 'image/jpg'
      if (!isImg) {
        this.$message({
          type: 'warning',
          message: '上传格式不正确（只能是.png,.jpg,.jpeg'
        })
        return
      }
      bindFileToAttributes(this.$deviceId, raw)
    },
    randomDailyFlow () {
      return Math.random() * 2000 | 0
    },
    randomGende () {
      const random = Math.random() * 100 | 0
      return `${random}:${100 - random}`
    },
    randomAge () {
      const random1 = Math.random() * 100 | 0
      const random2 = Math.random() * (100 - random1) | 0
      return `${100 - random1 - random2}:${random1}:${random2}`
    },
    show ({ id }) {
      const loading = this.$showLoading()
      this.$deviceId = id
      getAdAttributes(id).then(({ data }) => {
        this.isAdd = !data
        this.files = data?.pictureUrl ? this.getFiles(data.pictureUrl) : []
        this.attributes = {
          enable: false,
          minDuration: 5, // 最小投放广告时长（单位秒）
          minCount: 10, // 最小投放次数
          price: 1000, // 单位分
          ...data,
          dailyFlow: this.randomDailyFlow(),
          gendeRatio: this.randomGende(),
          ageRatio: this.randomAge()
        }
        this.$refs.configDialog.show()
      }).finally(() => {
        this.$closeLoading(loading)
      })
    },
    getFiles (pictureUrl) {
      const result = []
      pictureUrl.split(',').forEach(keyName => {
        result.push({
          url: getAssetUrl(keyName),
          keyName
        })
      })
      return result
    },
    onSave (done) {
      updateAdAttributes(this.$deviceId, {
        ...this.attributes,
        pictureUrl: this.files.map(({ keyName }) => keyName).join(',')
      }).then(done)
    },
    onSelect () {
      this.$refs.assetDialog.show(
        AssetType.IMAGE,
        this.directoryOption
      )
    },
    onAssetDirectoryChanged (directory) {
      this.directoryOption = directory
    },
    onViewAsset ({ file }) {
      this.$refs.previewDialog.show(file)
    },
    onChoosenAsset ({ keyName }) {
      this.files.push({
        url: getAssetUrl(keyName),
        keyName
      })
      return Promise.resolve()
    },
    onDelFile (file, index) {
      this.files.splice(index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.c-media {
  width: 64px;
  height: 64px;
  border-radius: $radius;

  &.add {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    border: 1px dashed #ccc;

    &:hover{
      border: 1px dashed $primary;
    }
  }

  &__del {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: $padding--2xs;
    right: $padding--2xs;
    color: $gray;
  }
}
</style>
