<!--  -->
<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="messageform" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="轮播名称：" style="width:318px;" prop="name">
            <el-input v-model="form.name" placeholder="请输入轮播名称"></el-input>
          </el-form-item>
          <el-form-item label="轮播类型：" prop="type">
            <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;" prop="date">
            <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="轮播说明：" prop="description">
            <vue-editor v-model="form.description" />
          </el-form-item>
          <template v-if="form.type === 0">
            <el-form-item label="轮播板式：" prop="uploadList">
              <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 class="bs-item" v-for="(element,i) in radioActive.arr" :key="i">
                    <img v-if="uploadList[i]" :src="$serverName.replace('/zhoushan','') + uploadList[i]" alt="">
                    <img v-if="uploadList[i]" @click.stop="delItem(i)" class="del" src="@/assets/img/del.png" alt="">
                  </div>
                </draggable>
              </div>
              <el-upload
                class="upload-demo"
                drag
                ref="uploadbanshi"
                :on-success="upload_success"
                :action='uploadUrl'
                :headers="{
                  token,
                }"
                :on-exceed="handleExceed"
                :limit="form.contentNum"
                :before-upload="beforeUpload1"
                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="轮播内容：" prop="contentUrl">
              <el-upload
                class="upload-demo"
                drag
                :on-success="upload_success"
                :action='uploadUrl'
                :before-upload="beforeUpload"
                :headers="{
                  token,
                }"
                multiple
              >
              <video style="width:100%" v-if="form.contentUrl" autoplay
                  :src="form.contentUrl"></video>
                <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="展示顺序：" prop="orderNum">
            <el-input-number
              v-model="form.orderNum"
              :min="1"
              :max="1000"
              label="展示顺序"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="是否启用：" prop="state">
            <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'
}]

var checkbanshi = (rule, value, callback) => {
  callback()
}

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    MainTop,
    VueEditor,
    draggable
  },
  data () {
    let crumbData = [
      {
        name: '轮播管理',
        id: 0
      },
      {
        name: parseInt(this.$route.params.type) ? '编辑轮播' : '新增轮播',
        id: 0
      }
    ]
    return {
      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
      },
      rules: {
        name: [{ required: true, message: '请输入轮播名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择轮播类型', trigger: 'blur' }],
        date: [{ required: true, message: '请选择轮播时间', trigger: 'blur' }],
        description: [{ required: true, message: '请输入轮播说明', trigger: 'blur' }],
        uploadList: [{ required: true, message: '请输入轮播板式', validator: checkbanshi, trigger: 'blur' }],
        contentUrl: [{ required: true, message: '请输入轮播内容', trigger: 'change' }],
        orderNum: [{ required: true, message: '请输入展示顺序', trigger: 'blur' }],
        state: [{required: true}]
      },
      dialogTableVisible: false,
      type: this.$route.params.type,
      radioActive: [],
      uploadUrl: `${this.$serverName}/exhibition/upload`,
      token: window.localStorage.getItem('token'),
      uploadList: []
    }
  },
  watch: {
    'form.type': {
      immediate: true,
      handler: function () {
        this.$refs.uploadbanshi && this.$refs.uploadbanshi.clearFiles()
        this.uploadList = []
      }
    },
    '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.$refs.uploadbanshi && this.$refs.uploadbanshi.clearFiles()
        // this.$refs.uploadbanshi.fileList = []
        this.uploadList = []
      }
    }
  },

  methods: {
    delItem (i) {
      this.uploadList.splice(i, 1)
      this.$refs.uploadbanshi && this.$refs.uploadbanshi.fileList.splice(i, 1)
    },
    handleRadio (type) {
    },
    getType () {
      if (!this.form.contentUrl) {
        return null
      }
      console.log(this.form.contentUrl)
      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 () {
      this.$refs['messageform'].validate(async (valid) => {
        if (!valid) {
          return
        }
        let {
          type,
          id,
          name,
          contentUrl,
          orderNum,
          state,
          startTime,
          endTime,
          description,
          contentNum
        } = this.form
        if (type === 0) {
          contentUrl = this.uploadList
          if (this.uploadList.length !== contentNum) {
            return this.$alert('请上传板式对应图片数量。', '提示', {
              confirmButtonText: '确定',
              type: 'warning',
              callback: action => {
              }
            })
          }
        }
        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.$alert('上传图片不能超过板式规定的数量', '提示', {
        confirmButtonText: '确定',
        type: 'warning',
        callback: action => {
        }
      })
    },
    beforeUpload1 (file) {
      if (this.uploadList.length >= this.form.contentNum) {
        this.$alert(`当前限制选择 ${this.form.contentNum} 个文件，您已超出限定上传文件数。`, '提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {
          }
        })
        return false
      }
      this.loading = true
      let typeArr = ['jpg', 'jpgc', 'png']
      let type = this.isTypeBySend(file.name, typeArr)
      if (!type) {
        this.loading = false
        this.$message.error('支持扩展名：.jpg, .jpgc, .png')
        return type
      }
    },
    beforeUpload (file) {
      this.loading = true
      let typeArr = ['wma', 'rmvb', 'rm', 'flash', 'mp4']
      let type = this.isTypeBySend(file.name, typeArr)
      if (!type) {
        this.loading = false
        this.$message.error('支持扩展名：.wma, .rmvb, .rm, .flash, .mp4')
        return type
      }
    },
    upload_success (data) {
      this.loading = false
      if (this.form.type === 0) {
        if (this.uploadList.length >= this.form.contentNum) {
          this.$alert(`当前限制选择 ${this.form.contentNum} 个文件，您已超出限定上传文件数。`, '提示', {
            confirmButtonText: '确定',
            type: 'warning',
            callback: action => {
            }
          })
          return false
        }
        this.uploadList.push(data.data)
      } else {
        this.form.contentUrl = data.data
      }
    }
  },
  mounted () {
    if (parseInt(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 || []
        })
      }
    }
  }
}
</script>

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

<style>
.ql-picker-label {
  line-height: 1;
  overflow: hidden;
}
.ql-snow .ql-tooltip[data-mode=link]::before{
  content:"输入链接："!important;
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after{
  content:"保存"!important;
}
</style>
