<!--  -->
<template>
  <div v-loading.fullscreen.lock="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
    <main-top :crumb="crumbData"></main-top>
    <div class="table-interface">
      <div class="top-body">
        <el-form ref="form" :model="form" label-width="100px">
          <el-form-item label="资讯名称：" style="width:318px;">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="资讯类型：">
            <el-select v-model="form.type" placeholder="请选择资讯类型">
              <el-option label="海报轮播" :value="0"></el-option>
              <el-option label="视频轮播" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="轮播时间：" style="width:518px;">
            <el-date-picker
              v-model="form.date"
              type="daterange"
              @change="handleChange"
              value-format="timestamp"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="资讯说明：">
            <vue-editor v-model="form.description" />
          </el-form-item>
          <template v-if="form.type === 0">
            <el-form-item label="轮播板式：">
              <el-radio-group v-model="form.contentNum" @change="handleRadio">
                <el-radio v-for="(item,i) in banshi"  :key="i" :label="item.size">{{item.size}}</el-radio>
              </el-radio-group>
              <div class="banshi">
                <draggable v-model="uploadList" group="people" @start="drag=true" @end="drag=false">
                  <div v-for="(element,i) in radioActive.arr" :key="i">
                    <img v-if="uploadList[i]" :src="$serverName.replace('/zhoushan','') + uploadList[i]" alt="">
                  </div>
                </draggable>
              </div>
              <el-upload
                class="upload-demo"
                drag
                :on-success="upload_success"
                :action='uploadUrl'
                :headers="{
                  token,
                }"
                :limit="form.contentNum"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                multiple
                :show-file-list="false"
              >
                <div>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                </div>
                <div class="el-upload__tip" slot="tip">
                  支持扩展名：.jpg, .jpgc, .png
                </div>
              </el-upload>
              <div class="el-upload__tip">*海报规定尺寸: {{radioActive.dec}}</div>
            </el-form-item>
          </template>

          <template v-if="form.type === 1">
            <el-form-item label="轮播内容：">
              <el-upload
                class="upload-demo"
                drag
                :on-success="upload_success"
                :action='uploadUrl'
                :before-upload="beforeUpload"
                :headers="{
                  token,
                }"
                multiple
              >
                <img
                  style="width:100%"
                  v-if="form.contentUrl"
                  :src="form.contentUrl"
                  alt=""
                />
                <div v-else>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                </div>
                <div class="el-upload__tip" slot="tip">
                  支持扩展名：.wma, .rmvb, .rm, .flash, .mp4
                </div>
              </el-upload>
            </el-form-item>
          </template>

          <el-form-item label="展示顺序：">
            <el-input-number
              v-model="form.orderNum"
              :min="1"
              :max="1000"
              label="展示顺序"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="是否启用：">
            <el-radio-group v-model="form.state">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="预览效果：">
            <el-button @click="dialogTableVisible = true">点击查看</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">发布</el-button>
            <el-button @click="$router.back()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-dialog title="预览效果" :visible.sync="dialogTableVisible">
           <video
              controls="controls"
              v-if="form.type === 1"
              autoplay
              :src="$serverName.replace('/zhoushan','') + form.contentUrl"
              style="width:100%"
            ></video>
          <div class="showImg" v-else>
            <div v-for="(item,i) in uploadList" :key="i">
              <img :src="$serverName.replace('/zhoushan','') + item" alt="">
            </div>
          </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

import MainTop from '@/components/main-top'
import { VueEditor } from 'vue2-editor'
import draggable from 'vuedraggable'
let urlType = {
  0: '/information/addInformation',
  1: '/information/updateInformation'
}

let banshi = [{
  size: 1,
  dec: '8640*1920'
}, {
  size: 2,
  dec: '4320*1920'
}, {
  size: 4,
  dec: '2160*1920'
}, {
  size: 6,
  dec: '1440*1920'
}, {
  size: 8,
  dec: '1080*1920'
}]

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    MainTop,
    VueEditor,
    draggable
  },
  data () {
    let crumbData = [
      {
        name: '资讯管理',
        id: 0
      },
      {
        name: this.$route.params.type ? '编辑资讯' : '发布资讯',
        id: 0
      }
    ]
    return {
      mediatype: '',
      crumbData,
      content: '<h1>Some initial content</h1>',
      banshi,
      loading: false,
      form: {
        name: '',
        type: 0,
        startTime: '',
        endTime: '',
        date: [],
        description: '',
        contentUrl: '',
        orderNum: 1,
        state: 0,
        id: '',
        contentNum: 4
      },
      dialogTableVisible: false,
      type: this.$route.params.type,
      radioActive: [],
      uploadUrl: `${this.$serverName}/exhibition/upload`,
      token: window.localStorage.getItem('token'),
      uploadList: []
    }
  },
  watch: {
    'form.contentUrl': {
      immediate: true,
      handler: function () {
        this.mediatype = this.getType()
      }
    },
    'form.contentNum': {
      immediate: true,
      handler: function (newVal) {
        let tmp = banshi.filter(item => item.size === newVal) || ''
        this.radioActive = {
          dec: tmp[0].dec,
          arr: new Array(tmp[0].size)
        }
        this.uploadList = []
      }
    }
  },

  methods: {
    handleRadio (type) {
      console.log(type)
    },
    getType () {
      if (!this.form.contentUrl) {
        return null
      }
      let type = this.form.contentUrl.split('.')
      type = type[type.length - 1]
      var a = [
        'cd',
        'ogg',
        'mp3',
        'asf',
        'wma',
        'wav',
        'mp3pro',
        'rm',
        'real',
        'ape',
        'module',
        'midi',
        'vqf'
      ]
      var v = ['jpg', 'jpgc', 'png']
      var m = ['wma', 'rmvb', 'rm', 'flash', 'mp4']

      for (var i in a) {
        if (a[i] === type.toLowerCase()) return 'audio'
      } // 音频
      for (var j in v) {
        if (v[j] === type.toLowerCase()) return 'picture'
      } // 图片
      for (var k in m) {
        if (m[k] === type.toLowerCase()) return 'video'
      } // 图片

      return null
    },
    onSubmit () {
      let {
        type,
        id,
        name,
        contentUrl,
        orderNum,
        state,
        startTime,
        endTime,
        description,
        contentNum
      } = this.form
      if (type === 0) {
        contentUrl = this.uploadList
      }
      let data = {
        name,
        type: Number(type),
        contentUrl,
        orderNum,
        contentNum,
        state,
        startTime,
        endTime,
        description
      }
      if (this.type) {
        data['id'] = id
      }
      this.$http.post(urlType[this.type], data).then(res => {
        if (res.code === 0) {
          this.$alert('操作成功', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.$router.back()
            }
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message
          })
        }
      })
    },

    handleChange (data) {
      this.form.startTime = data[0]
      this.form.endTime = data[1]
    },

    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 ${this.radio} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeUpload () {
      this.loading = true
    },
    upload_success (data) {
      this.loading = false
      if (this.form.type === 0) {
        this.uploadList.push(data.data)
      } else {
        this.form.contentUrl = data.data
      }
    }
  },
  mounted () {
    if (this.type) {
      let info = window.localStorage.getItem('editInfo')
      if (info) {
        this.form = JSON.parse(info)
        this.form.state = Number(this.form.state || 0)

        this.form.date = [
          Number(this.form.startTime),
          Number(this.form.endTime)
        ]
        setTimeout(() => {
          this.uploadList = this.form.contentUrl ? JSON.parse(this.form.contentUrl) : []
        })
      }
    }
  }
}
</script>

<style lang='less' scoped>
/* 引入公共css类 */
@import './style.less';
</style>

<style>
.ql-picker-label {
  line-height: 1;
  overflow: hidden;
}
</style>
