<!--  -->
<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">
        <div class="top-title">文物信息:</div>
        <div class="form-con">
          <el-form ref="ccform" :rules="rules" :model="form" label-width="120px" >
            <el-form-item label="文物名称：" style="width:318px;" prop="name">
              <el-input v-model="form.name" maxlength="50" show-word-limit placeholder="请输入文物名称"></el-input>
            </el-form-item>

            <el-form-item label="文物类别："  prop="typeId">
              <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="文物年代：" prop="timeId">
              <el-select v-model="form.timeId" placeholder="请选择文物类别">
                <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="藏品编号：" style="width:318px;">
              <el-input v-model="form.num" placeholder="请输入藏品编号"></el-input>
            </el-form-item>

            <el-form-item label="文物介绍：">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入文物介绍"
                maxlength="500"
                show-word-limit
                v-model="form.description">
              </el-input>
            </el-form-item>

            <el-form-item label="文物发现时间：">
              <el-date-picker value-format='timestamp' @change='data=>{form.discoveryTime = data}' v-model="form.discoveryTime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="文物维修时间：">
              <el-date-picker value-format='timestamp' @change='data=>{form.repairTime = data}' v-model="form.repairTime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>

            <el-form-item label="文物所在场馆：" style="width:318px;">
              <el-input v-model="form.venue" maxlength="20" show-word-limit placeholder="请输入场馆名称"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="top-title">展览信息:</div>
        <div class="form-con">
          <el-form :model="form" :rules="rules" label-width="120px">
            <el-form-item label="文物模型：" style="width:340px;">
              <el-input v-model="form.modelUrl" placeholder="请输入文物模型链接（url地址）"></el-input>
            </el-form-item>
            <el-form-item label="展示封面：" prop="pic">
               <Cropper
                  :width="512"
                  :height="512"
                  :fixed-number="[1,1]"
                  :uploadUrl = "'/exhibition/upload'"
                  :img="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_icon_success"
                >
                <img v-if="form.icon" :src="form.icon" 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="文物展示：">
               <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="unity文件：">
              <el-upload
                class="upload-demo"
                drag
                :headers="{
                  token
                }"
                :data="{
                  code:ran
                }"
                :action="uploadUnityUrl"
                :file-list="unityUrlList"
                :show-file-list="true"
                multiple
                :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文件：.obj, .ab, .png</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">支持视频动画格式：.wma, .wav, .mp4</div>
              </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 {randomWord} from '@/utils/index.js'

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

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    MainTop,
    VueEditor,
    Cropper
  },
  data () {
    let crumbData = [
      {
        name: '文物库',
        id: 0
      },
      {
        name: this.$route.params.type ? '编辑文物' : '新增文物',
        id: 1
      }
    ]
    return {
      crumbData,
      loading: false,
      contentUrlList: [],
      unityUrlList: [],
      ran: randomWord(true, 8, 8),
      form: {
        name: '',
        dirCode: '',
        typeId: 2,
        timeId: 1,
        num: '',
        discoveryTime: '',
        repairTime: '',
        venue: '',
        modelUrl: '',
        pic: '',
        contentUrl: '',
        unityPic: '',
        icon: '',
        unityUrl: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入文物名称', trigger: 'blur' }
        ],
        typeId: [
          { required: true, message: '请选择文物类别', trigger: 'change' }
        ],
        timeId: [
          { required: true, message: '请选择文物年代', trigger: 'change' }
        ],
        pic: [
          { required: true, message: '请上传展示封面', trigger: 'change' }
        ]
      },
      plist: [],
      tlist: [],
      realType: '',
      token: window.localStorage.getItem('token'),
      uploadUrl: `${this.$serverName}/collection/upload`,
      uploadUnityUrl: `${this.$serverName}/collection/uploadCode`,
      type: this.$route.params.type
    }
  },
  watch: {

  },
  methods: {
    getShopImages (img) {
      this.form.pic = img
    },
    getModelImages (img) {
      this.form.unityPic = img
    },
    onSubmit () {
      if (!this.form.name.trim()) {
        return this.$alert('文物名称不能为空')
      }
      if (!this.form.pic) {
        return this.$alert('展示封面不能为空')
      }

      this.$refs.ccform.validate((valid) => {
        if (valid) {
          let {name,
            typeId,
            timeId,
            num,
            discoveryTime,
            repairTime,
            venue,
            modelUrl,
            pic,
            contentUrl,
            unityPic,
            icon,
            unityUrl,
            state,
            description,
            id} = this.form
          contentUrl = this.contentUrlList[0] ? this.contentUrlList[0].url : ''

          let data = {
            name,
            typeId,
            timeId,
            num,
            discoveryTime,
            repairTime,
            venue,
            modelUrl,
            unityPic,
            icon,
            unityUrl,
            pic,
            contentUrl,
            state,
            description,
            dirCode: this.ran
          }
          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.msg
              })
            }
          })
        }
      })
    },

    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 = ['obj', 'png', 'ab']
      let type = this.isTypeBySend(file.name, typeArr)
      if (!type) {
        this.loading = false
        this.$message.error('支持上传文件：.obj, .ab, .png')
        return type
      }
    },

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

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

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

    upload_avatar_success (data) {
      this.loading = false
      this.form.unityPic = data.data
    },

    upload_icon_success (data) {
      this.loading = false
      this.form.icon = data.data
    },

    upload_unity_success () {
      this.loading = false
    },

    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 (parseInt(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)
        this.ran = this.form.dirCode || this.ran
        console.log(this.form, 1111)

        let contentUrl = this.form.contentUrl
        if (contentUrl) {
          this.contentUrlList = [{
            name: contentUrl.split('/')[contentUrl.split('/').length - 1],
            url: contentUrl
          }]
        }
      }
    } else {
      this.form = {
        name: '',
        typeId: 2,
        timeId: 1,
        num: '',
        discoveryTime: '',
        repairTime: '',
        venue: '',
        modelUrl: '',
        unityPic: '',
        unityUrl: '',
        pic: '',
        contentUrl: '',
        state: 0,
        description: ''
      }
    }
  }
}
</script>

<style scoped>
/* 引入公共css类 */
@import url(./style);
</style>

<style>
.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;
}
</style>
<style>
.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;
}

</style>
