<!--  -->
<template>
  <div class="tab2Add">
    <div class="top">
      典藏信息 > {{ ruleForm.type === "img" ? "精品图片" : "三维模型" }} >
      {{ ruleForm.id ? "编辑" : "新增" }}
    </div>
    <div class="conten">
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <!-- 名称 -->
        <div class="checkBox2">
          <el-form-item label="名称：">
            <i class="biaoshi biaoshi2"></i>
            <el-input
              v-model="ruleForm.name"
              maxlength="10"
              show-word-limit
            ></el-input>
          </el-form-item>
          <!-- 总登记号 -->
          <el-form-item label="总登记号：">
            <el-input
              v-model="ruleForm.registerNum"
              maxlength="25"
              show-word-limit
            ></el-input>
          </el-form-item>
        </div>
        <div class="checkBox">
          <!-- 日期 -->
          <el-form-item label="日期：">
            <i class="biaoshi biaoshi2"></i>
            <el-date-picker
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              v-model="day"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>

          <!-- 类型 -->
          <el-form-item label="类别：">
            <el-select
              v-model="ruleForm.dictTextureId"
              clearable
              placeholder="请选择类别"
            >
              <el-option
                v-for="i in dictTextureArr"
                :key="i.value"
                :label="i.label"
                :value="i.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 年代 -->
          <el-form-item label="年代：">
            <el-cascader
              ref="elCascader"
              clearable
              v-model="dictAgeId"
              :options="options"
            >
            </el-cascader>
          </el-form-item>
          <!-- 级别 -->
          <el-form-item label="级别：">
            <el-select
              v-model="ruleForm.dictLevelId"
              clearable
              placeholder="请选择级别"
            >
              <el-option
                v-for="i in dictLevelArr"
                :key="i.value"
                :label="i.label"
                :value="i.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 尺寸 -->
        <el-form-item label="尺寸：" class="sizeInput">
          <el-input v-model="chang" maxlength="100" show-word-limit></el-input>
        </el-form-item>

        <!-- 图片 -->
        <el-form-item label="图片：">
          <i class="biaoshi biaoshi1"></i>
          <el-upload
            accept=".png,.jpg,.jpeg,.gif"
            :data="{ type: 'img' }"
            class="avatar-uploader"
            :action="baseURL + '/api/cms/goods/upload'"
            :headers="{ token }"
            :show-file-list="true"
            :before-upload="beforethumbUpload"
            :on-success="upload_thumb_success"
          >
            <div v-if="ruleForm.thumb" class="imgdiv">
              <img
                style="
                  width: 150px;
                  height: 150px;
                  display: block;
                  object-fit: cover;
                "
                :src="baseURL + ruleForm.thumb"
              />
              <i
                class="el-icon-circle-close"
                @click.stop="ruleForm.thumb = ''"
              ></i>
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="upHint">
            格式要求：支持png、jpg、gif和jpeg的图片格式；最大支持20MB。
          </p>
        </el-form-item>
        <!-- 说明 -->
        <el-form-item label="说明：">
          <div class="txtBtn">
            <el-button
              :disabled="ruleForm.description.length >= 128"
              size="small"
              round
              @click="ruleForm.description += '&emsp;&emsp;'"
              >首行缩进</el-button
            >
            <el-button
              :disabled="ruleForm.description.length >= 135"
              size="small"
              round
              @click="ruleForm.description += '<br/>'"
              >换行</el-button
            >
          </div>
          <el-input
            type="textarea"
            v-model="ruleForm.description"
            maxlength="140"
            show-word-limit
          ></el-input>
        </el-form-item>
        <!-- 附件 -->
        <div class="rowFrom">
          <el-form-item label="模型文件：" v-if="ruleForm.type === 'model'">
            <i class="biaoshi"></i>
            <el-upload
              accept=".4dage"
              multiple
              drag
              class="upload-demo"
              :data="{ type: 'model' }"
              :file-list="fileList"
              :action="baseURL + '/api/cms/goods/upload'"
              :headers="{ token }"
              :before-upload="beforeFujian"
              :on-success="successFujian"
              :before-remove="beforeRemove"
              :on-remove="handleRemove"
              :limit="1"
              :on-exceed="handleExceed"
              :show-file-list="true"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__text smEl">
                仅支持.4dage格式的模型文件，大小不得超过500MB
              </div>
            </el-upload>
          </el-form-item>
          &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
          <el-form-item label="音频文件：" v-if="ruleForm.type === 'model'">
            <el-upload
              accept=".mp3"
              multiple
              drag
              class="upload-demo"
              :data="{ type: 'audio' }"
              :file-list="fileList2"
              :action="baseURL + '/api/cms/goods/upload'"
              :headers="{ token }"
              :before-upload="beforeFujian2"
              :on-success="successFujian2"
              :before-remove="beforeRemove2"
              :on-remove="handleRemove2"
              :limit="1"
              :on-exceed="handleExceed2"
              :show-file-list="true"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__text smEl">
                仅支持MP3格式的音频文件，大小不得超过10MB
              </div>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 底部按钮 -->
    <div class="con_btn">
      <el-button @click="goBack">取 消</el-button>&emsp;
      <el-button type="primary" @click="saveGood">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { goodsSave, goodsDetail, dictGetTree } from '../../apis/tab2'
import axios from '@/utils/request'
export default {
  name: 'tab2Add',
  components: {},
  data () {
    // 这里存放数据
    return {
      // 日期
      day: '',

      // 服务器前缀地址
      baseURL: '',
      // 尺寸
      chang: '',
      // 年代
      dictAgeId: [],
      options: [],
      // 类型数组
      dictTextureArr: [],
      // 级别数组
      dictLevelArr: [],
      ruleForm: {
        // 总登记号
        registerNum: '',
        // 类别
        dictTextureId: '',
        // 级别
        dictLevelId: '',
        name: '',
        type: null,
        description: '',
        thumb: '',
        // 上传模型
        filePath: '',
        fileName: ''
      },
      fileList: [],
      // ---------音频
      fileList2: []
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 点击取消
    goBack () {
      let k = this.$route.query.k
      if (!k) k = '1'
      this.$router.push({
        path: '/layout/tab2',
        query: { typeU: this.ruleForm.type, k }
      })
    },
    // 点击保存
    async saveGood () {
      if (this.ruleForm.name.trim() === '') {
        return this.$message.warning('名称不能为空')
      }
      if (this.ruleForm.thumb === '') {
        return this.$message.warning('图片不能为空')
      }
      if (this.ruleForm.filePath === '' && this.ruleForm.type === 'model') {
        return this.$message.warning('文件不能为空')
      }
      if (!this.day) return this.$message.warning('日期不能为空')
      const obj = { ...this.ruleForm }
      obj.day = this.day
      // 年代数据判断
      if (this.dictAgeId && this.dictAgeId[1]) {
        obj.dictAgeId = this.dictAgeId[1]
        // eslint-disable-next-line no-constant-condition
        const tempArr = this.$refs.elCascader.getCheckedNodes()[0].pathLabels
        obj.dictAgeFront = tempArr.join('/')
      }
      // 长宽高判断
      if (this.chang) obj.sizeLength = this.chang
      const res = await goodsSave(obj)
      if (res.code === 0) {
        this.$message.success('操作成功')
        this.goBack()
      } else this.$message.warning(res.msg)
    },
    // 上传图片
    beforethumbUpload (file) {
      // console.log(998, file)
      // 限制图片大小和格式
      const sizeOk = file.size / 1024 / 1024 < 20
      const typeOk =
        file.type === 'image/png' ||
        (file.type === 'image/jpeg' && !file.name.includes('.jfif')) ||
        file.type === 'image/gif'

      return new Promise((resolve, reject) => {
        if (!typeOk) {
          this.$message.error('图片格式有误！')
          reject(file)
        } else if (!sizeOk) {
          this.$message.error('图片大小超过20M！')
          reject(file)
        } else {
          resolve(file)
        }
      })
    },
    upload_thumb_success (data) {
      this.$message.success('上传成功')
      this.ruleForm.thumb = data.data.filePath
    },
    // 上传附件
    beforeFujian (file) {
      console.log('附件上传前', file)
      const sizeOk = file.size / 1024 / 1024 < 500
      const typeOk = file.type === '' && file.name.includes('.4dage')
      return new Promise((resolve, reject) => {
        if (!sizeOk) {
          this.$message.error('模型大小超过500M！')
          reject(file)
        } else if (!typeOk) {
          this.$message.error('模型格式有误！')
          reject(file)
        } else {
          resolve(file)
        }
      })
    },
    successFujian (file) {
      console.log('上传附件成功', file)
      if (file.code === 0) {
        this.ruleForm.filePath = file.data.filePath
        this.ruleForm.fileName = file.data.fileName
        this.$message.success('上传成功')
      } else if (file.code === -1) {
        this.$message.warning('上传失败，不支持的文件格式')
      }
    },
    beforeRemove (file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`)
      }
    },
    handleRemove (file, fileList) {
      this.ruleForm.filePath = ''
      this.ruleForm.fileName = ''
    },
    handleExceed (files, fileList) {
      this.$message.warning('只能上传一个文件，请删除原文件后操作')
    },

    // 上传音频-------------
    beforeFujian2 (file) {
      console.log('附件上传前222', file)
      const sizeOk = file.size / 1024 / 1024 < 10
      const typeOk = file.type === 'audio/mpeg'
      return new Promise((resolve, reject) => {
        if (!sizeOk) {
          this.$message.error('音频大小超过10M！')
          reject(file)
        } else if (!typeOk) {
          this.$message.error('音频格式有误！')
          reject(file)
        } else {
          resolve(file)
        }
      })
    },
    successFujian2 (file) {
      console.log('上传附件成功222', file)
      if (file.code === 0) {
        this.ruleForm.audioPath = file.data.filePath
        this.ruleForm.audioName = file.data.fileName
        this.$message.success('上传成功')
      } else if (file.code === -1) {
        this.$message.warning('上传失败，不支持的文件格式')
      }
    },
    beforeRemove2 (file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`)
      }
    },
    handleRemove2 (file, fileList) {
      this.ruleForm.audioPath = ''
      this.ruleForm.audioName = ''
    },
    handleExceed2 (files, fileList) {
      this.$message.warning('只能上传一个文件，请删除原文件后操作')
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created () {
    // 获取服务器前缀地址
    this.baseURL = axios.defaults.baseURL
    // 获取用户token
    this.token = localStorage.getItem('HNBWY_token')
    // 拿到路由跳转传过来的数据
    this.ruleForm.type = this.$route.query.typeU

    // 几个下拉框的数据
    // --------年代
    const res = await dictGetTree({ type: 'age' })
    const temp = []
    res.data.forEach((v, i) => {
      temp.push({ value: v.id, label: v.name, children: [] })
      v.children.forEach((p) => {
        temp[i].children.push({ value: p.id, label: p.name })
      })
    })
    this.options = [...temp]

    // -------类别
    const res2 = await dictGetTree({ type: 'texture' })
    this.dictTextureArr = res2.data.map((v) => {
      return { value: v.id, label: v.name }
    })
    // -------级别
    const res3 = await dictGetTree({ type: 'level' })
    this.dictLevelArr = res3.data.map((v) => {
      return { value: v.id, label: v.name }
    })

    // 如果是编辑
    let id = this.$route.query.id
    if (id) {
      id = Number(id)
      const resSon = await goodsDetail(id)
      this.ruleForm = resSon.data
      // 附件回显
      this.fileList = [{ name: resSon.data.fileName }]
      // 音频回显
      if (resSon.data.audioName) {
        this.fileList2 = [{ name: resSon.data.audioName }]
      }

      // 年代回显
      if (resSon.data.dictAgeId) {
        res.data.forEach((v) => {
          v.children.forEach((p) => {
            if (p.id === resSon.data.dictAgeId) this.dictAgeId = [v.id, p.id]
          })
        })
      }
      // 尺寸回显
      this.chang = resSon.data.sizeLength
      // 日期回显
      this.day = resSon.data.day
    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {},
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='less' scoped>
.tab2Add {
  width: 100%;
  height: 100%;

  .rowFrom {
    display: flex;

    /deep/.el-upload-list {
      width: 360px;
    }

    /deep/.el-upload-list li {
      width: 360px !important;
    }
  }

  .top {
    margin-top: -20px;
    height: 50px;
    line-height: 50px;
    padding-left: 50px;
    background-color: #f8f8f8;
    font-weight: 700;
  }

  .conten {
    padding-right: 300px;
    padding-top: 20px;

    .upHint {
      position: absolute;
      bottom: 40px;
      left: 160px;
    }

    .avatar-uploader .el-upload {
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #3e5eb3;
    }

    .avatar-uploader-icon {
      border: 1px dashed #ccc;
      font-size: 28px;
      color: #8c939d;
      width: 150px;
      height: 150px;
      line-height: 150px;
      text-align: center;
    }

    .biaoshi1::before {
      left: -64px;
    }

    .biaoshi2::before {
      top: -11px;
      left: -64px;
    }

    /deep/.el-form-item {
      margin-bottom: 12px;
    }

    /deep/.el-textarea textarea {
      margin-top: 10px;
      height: 55px;
      resize: none;
    }

    /deep/.el-textarea .el-input__count {
      position: absolute;
      bottom: -24px;
      right: 4px;
      background-color: transparent;
      height: 30px;
      line-height: 30px;
    }

    .smEl {
      color: #ccc;
      font-size: 12px;
      margin-top: -15px;
    }
  }

  .con_btn {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
  }

  .txtBtn {
    position: absolute;
    top: -32px;
    right: 4px;
  }

  /deep/.imgdiv .el-icon-circle-close {
    font-size: 20px;
  }

  .checkBox {
    display: flex;
  }

  .checkBox2 {
    width: 100%;
    display: flex;

    & > div {
      width: 50%;
    }
  }

  .fromSize {
    /deep/.el-form-item__content {
      display: flex;
    }

    /deep/.el-input {
      width: 100px;
    }

    /deep/.el-input--suffix {
      width: 90px;
    }

    /deep/.el-input__inner {
      padding: 0 5px !important;
    }

    .sizeRow {
      margin-right: 90px;
    }

    .sizeRow2 {
      /deep/.el-input {
        width: 110px;
      }
    }
  }
  .sizeInput{
    /deep/input{
      padding-right: 70px !important;
    }
  }

  /deep/.el-upload-list {
    margin-top: -12px;
  }
}
</style>
