<!--  -->
<template>
  <div  v-loading.fullscreen.lock="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    class="edit-cultural-relic"
    element-loading-background="rgba(0, 0, 0, 0.8)">
    <main-top :crumb="crumbData"></main-top>
    <div class="table-interface">
      <div class="top-body">
        <div class="top-title">文物信息:</div>
        <div class="form-con">
          <el-form ref="form"  :rules="rules" status-icon  :model="form" label-width="120px">
            <el-form-item prop="name" label="文物名称：" style="width:318px;">
              <el-input v-model="form.name" placeholder="请输入文物名称"></el-input>
            </el-form-item>
            <el-form-item prop="verticalName" label="竖排文物名">
              <el-input type="textarea" v-model="form.verticalName" class="verticla-input" />
              <!-- <textarea rows="10" >
                在w3school，你可以找到你所需要的所有的网站建设教程。
                </textarea> -->
            </el-form-item>
            <el-form-item label="文物类别：">
              <el-select v-model="form.typeId" placeholder="请选择文物类别">
                  <el-option v-for="(item,i) in plist" :key="i" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="分类年代：" :rules="[
              { required: true}
            ]">
              <el-select v-model="form.timeId" placeholder="请选择分类年代" style="width:400px">
                <el-option v-for="(item,i) in tlist" :key="i" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="文物年代：" >
              <el-input v-model="form.typeTime" maxlength="50" show-word-limit placeholder="请输入文物年代"></el-input>
            </el-form-item>

            <el-form-item label="文物介绍：">
                <vue-editor v-model="form.description" />
            </el-form-item>
            <el-form-item label="文物介绍预览：">
                <el-input type="textarea" v-model="form.description1" disabled />
            </el-form-item>
            <el-form-item label="出土信息：" style="width:100%;">
              <el-input v-model="form.venue" maxlength="50" show-word-limit placeholder="请输入出土信息"></el-input>
            </el-form-item>

             <el-form-item label="文物用途：" style="width:100%;">
              <el-input v-model="form.purpose" maxlength="50" show-word-limit placeholder="请输入文物用途"></el-input>
            </el-form-item>

             <el-form-item label="文物材质：" style="width:100%;">
              <el-input v-model="form.texture" maxlength="50" show-word-limit placeholder="请输入文物材质"></el-input>
            </el-form-item>

             <el-form-item label="文物尺寸：" style="width:100%;">
              <el-input v-model="form.size" maxlength="50" show-word-limit placeholder="请输入文物尺寸"></el-input>
            </el-form-item>

            <el-form-item label="备注信息：" style="width:100%;">
              <el-input v-model="form.remarks" maxlength="50" show-word-limit placeholder="请输入文物出土地点"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="top-title">展览信息:</div>
        <div class="form-con">
          <el-form ref="form" :model="form" label-width="120px">
            <el-form-item label="文物展示方式：">
                <el-radio-group v-model="form.type">
                  <el-radio :label="'2D'" >2D</el-radio>
                  <el-radio :label="'3D'" >3D</el-radio>
                </el-radio-group>
            </el-form-item>

            <template v-if="form.type === '2D'">
              <el-form-item label="轮播板式：">
                <div class="banshi">
                  <draggable v-model="uploadList" group="people" @start="drag=true" @end="drag=false">
                    <div v-for="(item,i) in uploadList" :key="i"  class="imgdiv">
                      <img v-if="item" :src="$serverName.replace('/zhoushan','') + item" alt="">
                      <i class="el-icon-circle-close" @click.stop="delUploadItem(i)"></i>
                    </div>
                  </draggable>
                </div>
                <el-upload
                  class="upload-demo"
                  drag
                  :on-success="upload_imglist_success"
                  :action='uploadUrl'
                  :headers="{
                    token,
                  }"
                  :limit="10"
                  :on-exceed="handleExceed"
                  :before-upload="before_imglistUpload"
                  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">*海报规定尺寸比例:3:4 </div>
              </el-form-item>
            </template>

            <el-form-item v-else label="文物模型：" style="width:340px;">
              <el-input v-model="form.modelUrl" placeholder="请输入文物模型链接（url地址）"></el-input>
            </el-form-item>

            <el-form-item label="展示封面：">
               <Cropper
                  :width="512"
                  :height="512"
                  :fixed-number="[1,1]"
                  :uploadUrl = "'/exhibition/upload'"
                  :img="form.pic"
                  @clearImg="form.pic=''"
                  @subUploadSucceed="getShopImages"
              />
              <span class="wwtxt" style="color:#C0C4CC">建议上传512*512的png格式图片</span>
            </el-form-item>

            <el-form-item label="文物展示：">
               <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="{
                  token,
                }"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="upload_avatar_success"
                >
                <img v-if="form.unityPic" :src="form.unityPic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <span class="wwtxt" style="color:#C0C4CC">仅支持上传文物展示的JPG格式文件</span>
            </el-form-item>

            <!-- <el-form-item label="四维模库：" style="width:340px;">
              <el-button type="primary" @click="open">立即前往</el-button>
            </el-form-item> -->

            <el-form-item label="unity文件：">
              <el-upload
                class="upload-demo"
                drag
                :headers="{
                  token
                }"
                :action="uploadUrl"
                :file-list="unityUrlList"
                :show-file-list="true"
                :before-remove="beforeUnityUrlRemove"
                :before-upload="beforeUnityUpload"
                :on-success="upload_unity_success"
              >
                <div >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                  </div>
                </div>
                <div class="el-upload__tip" slot="tip">支持上传unity文件：.unity, .ab, .u3d</div>
              </el-upload>
            </el-form-item>

            <el-form-item label="视频动画：">
              <el-upload
                class="upload-demo"
                drag
                :headers="{
                  token
                }"
                :file-list="contentUrlList"
                :show-file-list="true"
                :action="uploadUrl"
                :before-remove="beforeRemove"
                :before-upload="beforeUpload"
                :on-success="upload_success"
              >
                <div>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                  </div>
                </div>
                <div class="el-upload__tip" slot="tip">支持视频动画格式：.wmv, .wav, .mp4</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="二维码信息：">
               <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="{
                  token,
                }"
                :show-file-list="false"
                :before-upload="beforeqrCodeUpload"
                :on-success="upload_qrCode_success"
                >
                <div v-if="form.qrCode" class="imgdiv">
                  <img
                    style="width: 100%;height:100%;"
                    :src="$serverName.replace('/zhoushan','') + form.qrCode"
                  >
                  <i class="el-icon-circle-close" @click.stop="form.qrCode=''"></i>
                </div>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>

            </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>
        </div>
        <el-button type="primary" @click="onSubmit">发布</el-button>
        <el-button @click="$router.back()">取消</el-button>
      </div>
    </div>
  </div>
</template>

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

import MainTop from '@/components/main-top'
import { VueEditor } from 'vue2-editor'
import Cropper from '@/components/cropper'
import draggable from 'vuedraggable'

let urlType = {
  0: '/collection/addCollection',
  1: '/collection/updateCollection'
}

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    MainTop,
    VueEditor,
    Cropper,
    draggable
  },
  data () {
    let crumbData = [
      {
        name: '文物库',
        id: 0
      },
      {
        name: this.$route.params.type ? '编辑文物' : '新增文物',
        id: 1
      }
    ]
    return {
      uploadList: [],
      crumbData,
      loading: false,
      contentUrlList: [],
      unityUrlList: [],
      rules: {
        name: [{ required: true, message: '请输入文物名称', trigger: 'blur' }],
        verticalName: [{ required: true, message: '请输入竖排文物名', trigger: 'blur' }]
      },
      form: {
        name: '',
        typeId: 2,
        timeId: 1,
        typeTime: '',
        num: '',
        discoveryTime: '',
        venue: '',
        modelUrl: '',
        pic: '',
        qrCode: '',
        contentUrl: '',
        unityPic: '',
        unityUrl: '',
        description: '',
        purpose: '',
        remarks: '',
        repairTime: '',
        size: '',
        start: 0,
        state: 0,
        texture: '',
        type: '2D',
        typeImages: '',
        verticalName: ''
      },
      plist: [],
      tlist: [],
      realType: '',
      token: window.localStorage.getItem('token'),
      uploadUrl: `${this.$serverName}/collection/upload`,
      type: this.$route.params.type
    }
  },
  watch: {
    'form.description' (val) {
      this.form.description1 = val.replace(/<("[^"]*"|'[^']*'|[^'">])*>/g, '').replace(/&nbsp/g, '').replace(/<\/\w*>/g, '\n')
    }
  },
  methods: {
    delUploadItem (i) {
      this.uploadList.splice(i, 1)
    },
    getShopImages (img) {
      this.form.pic = img
    },
    getQrCodeImages (img) {
      this.form.qrCode = img
      console.log(this.form.qrCode)
    },
    getModelImages (img) {
      this.form.unityPic = img
    },
    handleExceed (files, fileList) {
      this.$message.warning(`上传数量超出限制`)
    },
    before_imglistUpload () {
      this.loading = true
    },
    upload_imglist_success (data) {
      this.loading = false
      this.uploadList.push(data.data)
    },
    async onSubmit () {
      let {name,
        typeId,
        type,
        timeId,
        typeTime,
        purpose,
        num,
        discoveryTime,
        repairTime,
        venue,
        modelUrl,
        pic,
        qrCode,
        contentUrl,
        size,
        typeImages,
        unityPic,
        texture,
        unityUrl,
        state,
        remarks,
        description,
        verticalName,
        id} = this.form
      if (!name) {
        this.$notify.error({
          title: '错误',
          message: '请输入文物名称',
          duration: 2000
        })
        return
      }
      if (!verticalName) {
        this.$notify.error({
          title: '错误',
          message: '请输入竖排文物名称',
          duration: 2000
        })
        return
      }
      contentUrl = this.contentUrlList[0] ? this.contentUrlList[0].url : ''
      unityUrl = this.unityUrlList[0] ? this.unityUrlList[0].url : ''
      if (type === '2D') {
        typeImages = this.uploadList
      }
      description = this.form.description1
      let data = {name,
        typeId,
        timeId,
        typeTime,
        num,
        discoveryTime,
        repairTime,
        typeImages,
        type,
        size,
        venue,
        modelUrl,
        unityPic,
        unityUrl,
        texture,
        remarks,
        purpose,
        pic,
        qrCode,
        contentUrl,
        state,
        verticalName,
        description}
      if (this.type) {
        data['id'] = id
      }
      this.$http.post(urlType[this.type], data).then(res => {
        if (res.code === 0) {
          this.$alert(this.$route.params.type ? '操作成功' : '操作成功', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.$router.back()
            }
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 2000
          })
        }
      })
    },
    open () {
      window.open('https://www.4dmodel.com', '_blank')
    },

    beforeAvatarUpload (file) {
      this.loading = true
      let typeArr = ['jpg']
      let type = this.isTypeBySend(file.name, typeArr)
      if (!type) {
        this.loading = false
        this.$message.error('仅支持上传文物展示的JPG格式文件')
        return type
      }
    },

    beforeUnityUpload (file) {
      this.loading = true
      let typeArr = ['unity', 'ab', 'u3d']
      let type = this.isTypeBySend(file.name, typeArr)
      if (!type) {
        this.loading = false
        this.$message.error('支持上传unity文件：.unity, .ab, .u3d')
        return type
      }
    },

    beforeUnityUrlRemove (file) {
      this.unityUrlList = []
    },

    beforeRemove (file) {
      this.contentUrlList = []
    },

    beforeUpload (file) {
      this.loading = true
      let typeArr = ['wmv', 'wav', 'mp4']
      let type = this.isTypeBySend(file.name, typeArr)
      if (!type) {
        this.loading = false
        this.$message.error('支持视频动画格式：.wmv, .wav, .mp4')
        return type
      }
    },

    beforeqrCodeUpload () {
      this.loading = true
    },
    upload_qrCode_success (data) {
      this.loading = false
      this.form.qrCode = data.data
    },
    upload_avatar_success (data) {
      this.loading = false
      this.form.unityPic = data.data
    },

    upload_unity_success (data) {
      this.loading = false
      this.form.unityUrl = data.data
      this.unityUrlList = [{
        name: data.data.split('/')[data.data.split('/').length - 1],
        url: data.data
      }]
    },

    upload_success (data) {
      this.loading = false
      this.form.contentUrl = data.data
      this.contentUrlList = [{
        name: data.data.split('/')[data.data.split('/').length - 1],
        url: data.data
      }]
    },

    async getPositionList () {
      let result = await this.$http({
        method: 'post',
        data: {
          state: 0
        },
        url: '/collection/typeList'
      })

      this.plist = result.data
    },
    async getTypeList () {
      let result = await this.$http({
        method: 'post',
        url: '/collection/timeList'
      })

      this.tlist = result.data
    }

  },
  mounted () {
    this.getPositionList()
    this.getTypeList()
    if (this.type) {
      let info = window.localStorage.getItem('editCollection')
      if (info) {
        this.form = JSON.parse(info)
        this.form.typeId = Number(this.form.typeId)
        this.form.equipmentId = Number(this.form.equipmentId)
        this.form.state = Number(this.form.state)
        let unityUrl = this.form.unityUrl
        let contentUrl = this.form.contentUrl

        if (unityUrl) {
          this.unityUrlList = [{
            name: unityUrl.split('/')[unityUrl.split('/').length - 1],
            url: unityUrl
          }]
        }

        if (contentUrl) {
          this.contentUrlList = [{
            name: contentUrl.split('/')[contentUrl.split('/').length - 1],
            url: contentUrl
          }]
        }
        setTimeout(() => {
          this.uploadList = this.form.typeImages ? JSON.parse(this.form.typeImages) : []
        })
      }
    } else {
      this.form = {
        name: '',
        typeId: 2,
        timeId: 1,
        typeTime: '',
        num: '',
        discoveryTime: '',
        venue: '',
        modelUrl: '',
        pic: '',
        qrCode: '',
        contentUrl: '',
        unityPic: '',
        unityUrl: '',
        description: '',
        purpose: '',
        remarks: '',
        repairTime: '',
        size: '',
        start: 0,
        state: 0,
        texture: '',
        type: '2D',
        typeImages: ''
      }
    }
  }
}
</script>

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

<style  lang='less'>
.ql-picker-label {
  line-height: 1;
  overflow: hidden;
}

.avatar-uploader .el-upload {
  /* border: 1px dashed #000; */
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.ql-picker-label {
  line-height: 1;
  overflow: hidden;
}

.avatar-uploader{
  border: 1px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  margin-top: 10px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px!important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.edit-cultural-relic {
  .verticla-input {
    height: 200px;
    width: 40px;
    textarea {
      height: 100% !important;
      resize: none;
    }
  }
}

</style>
