<template>
  <div class="tab1Add2">
    <div class="insideTop">
      文物典藏管理 > 新增文物典藏
      <div class="add">
        <el-button type="primary" @click="goBack">返 回</el-button>
      </div>
    </div>
    <div class="obstruct"></div>
    <!-- 主要内容 -->
    <div class="conten">
      <div class="con_top">基本信息</div>
      <!-- 表单 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题：" prop="name">
          <el-input
            v-model="ruleForm.name"
            maxlength="25"
            show-word-limit
            style="width: 500px"
          ></el-input>
        </el-form-item>
        <el-form-item label="精品类型：">
          <i class="biaoshi biaoshi2"></i>
          <el-radio v-model="conLeftId" label="model" disabled>实物模型</el-radio>
          <el-radio v-model="conLeftId" label="img">专题图库</el-radio>
          <el-radio v-model="conLeftId" label="video：视频" disabled>视频档案</el-radio>
        </el-form-item>
        <!-- 图片 -->
        <el-form-item label="图片：" style="height:480px">
          <i class="biaoshi biaoshi1"></i>
          <div class="imgBox">
            <div
              class="imgdiv"
              v-for="(item, index) in imgList"
              :key="item.id"
            >
              <el-image
                style="width: 200px; height: 200px"
                :src="baseURL+item.filePath"
                :preview-src-list="imgListLook"
              >
              </el-image>
              <!-- 封面显示 -->
              <div class="cover" v-if="imgActive === index">封面图片</div>
              <!-- 下面的按钮 -->
              <div class="handle">
                <el-button size="mini" type="primary" round @click="goodsImgIndex(index)" v-if="imgActive !== index">设为封面</el-button>
              </div>
              <!-- 删除 -->
              <div class="delImg el-icon-delete" @click="delGoodsImg(index,item.id)" v-if="imgActive !== index"></div>
            </div>
            <el-upload
              ref="upload"
              class="avatar-uploader"
              :action="baseURL + '/cms/goods/upload'"
              :headers="{ token }"
              :show-file-list="true"
              :before-upload="beforethumbUpload"
              :on-success="upload_thumb_success"
            >
              <div class="upImg">
                <i slot="default" class="el-icon-plus"></i>
              </div>
            </el-upload>
          </div>
          <p class="upHint upHint1">格式要求：</p>
          <p class="upHint">
            1、支持png、jpg、gif和jpeg的图片格式；最大支持20M。
          </p>
          <p class="upHint">2、最多可上传18张图片。</p>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <div class="con_btn">
        <el-button type="primary" @click="goodsSave">保 存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { goodsSave, goodsDetail, goodsimgRemove } from '@/apis/tab1'
import axios from '@/utils/request'
export default {
  name: 'tab1Add2',
  components: {},
  data () {
    return {
      // 重新上传的数据
      imgActive: 0,
      // 上传成功后的图片数组
      imgList: [],
      imgListLook: [],
      conLeftId: 'img',
      fileList: [],
      // 服务器前缀地址
      baseURL: '',
      token: '',
      ruleForm: {
        code: new Date().valueOf(),
        name: '',
        type: 'img',
        thumb: ''
      },
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  methods: {
    // 点击保存
    async goodsSave () {
      if (this.ruleForm.name.trim() === '') { return this.$message.warning('标题不能为空') }
      if (this.imgList.length === 0) { return this.$message.warning('图片不能为空') }
      if (this.imgList.length > 18) { return this.$message.warning('图片不能超过18张') }
      const temp = []
      this.imgList.forEach(v => {
        temp.push(v.id)
      })
      const obj = { ...this.ruleForm, fileIds: temp.join(','), thumb: this.imgList[this.imgActive].filePath, indexId: this.imgList[this.imgActive].id }
      const res = await goodsSave(obj)
      if (res.code === 0) {
        this.$message.success('操作成功')
        this.$router.push({
          path: '/layout/tab1',
          query: { conLeftId: 'img' }
        })
      } else this.$message.warning(res.msg)
      // console.log(998, res)
    },
    // 点击删除
    delGoodsImg (index, id) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await goodsimgRemove(id)
          this.imgList.splice(index, 1)
          this.imgListLook.splice(index, 1)
          if (index < this.imgActive) this.imgActive--
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.info('已取消')
        })
    },
    // 点击设为封面
    async goodsImgIndex (index) {
      this.imgActive = index
      // this.ruleForm.thumb = this.imgList[index].filePath
      this.$message.success('操作成功')
    },
    // 点击返回
    goBack () {
      this.$confirm('点击返回后，编辑的信息将无法保存，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$router.push({
            path: '/layout/tab1',
            query: { conLeftId: 'img' }
          })
        })
        .catch(() => {
          this.$message.info('已取消')
        })
    },
    // 上传图片
    beforethumbUpload (file) {
      // console.log(998, file)
      // 限制图片大小和格式
      const sizeOk = file.size / 1024 / 1024 < 20
      const typeOk =
        file.type === 'image/png' ||
        file.type === 'image/jpeg' ||
        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 if (file.name.length > 32) {
          this.$message.error('照片名字不能超过32个字！')
          reject(file)
        } else {
          resolve(file)
        }
      })
    },
    async upload_thumb_success (data) {
      this.$message.success('上传成功')
      // console.log('图片上传成功', data)
      this.imgList.push({ name: data.data.name, id: data.data.id, filePath: data.data.filePath })
      this.imgListLook.push(this.baseURL + data.data.filePath)
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created () {
    // 获取服务器前缀地址
    this.baseURL = axios.defaults.baseURL
    // 获取用户token
    this.token = localStorage.getItem('CQLJXU_token')
    // 通过父亲传过来的id获取详情
    if (this.$route.query.id) {
      const res = await goodsDetail(Number(this.$route.query.id))
      this.ruleForm = res.data.entity
      this.imgList = res.data.file
      this.imgList.forEach((v, i) => {
        this.imgListLook.push(this.baseURL + v.filePath)
        // 修改封面显示
        if (v.isIndex === 1) this.imgActive = i
      })
      // console.log(998, res)
    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {},
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='less' scoped>
.tab1Add2 {
  height: 100%;
  .conten {
    /deep/.el-form-item{
      max-height: 480px;
      overflow-y: auto;
    }
    position: relative;
    /deep/.el-icon-plus {
      font-size: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #ccc;
      width: 200px;
      height: 200px;
    }
    height: calc(100% - 32px);
    .con_top {
      margin-bottom: 12px;
      height: 40px;
      line-height: 40px;
      padding-left: 20px;
      background-color: #fbfbfb;
    }
    .biaoshi1::before {
      left: -63px;
    }
    .biaoshi2::before {
      top: -10px;
    }
    .avatar-uploader .el-upload {
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #3e5eb3;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .con_btn {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      bottom: 15px;
    }
    .imgBox{
      display: flex;
      flex-wrap: wrap;
      .imgdiv{
        position: relative;
        margin-right: 30px;
        margin-bottom: 10px;
        .handle{
          display: flex;
          justify-content: center;
          margin-top: 5px;
        }
        .delImg{
          cursor: pointer;
          border-radius: 10px;
          color: #fff;
          background-color: #b9412e;
          padding: 3px;
          font-size: 26px;
          position: absolute;
          top: 5px;
          right: 5px;
        }
        .cover{
          pointer-events: none;
          font-size: 16px;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          z-index: 999;
          position: absolute;
          top: 44%;
          left: 0;
          transform: translateY(-50%);
          height: 40px;
          background-color: rgba(255,255,255,.4);
        }
      }
    }
    .upHint1{
      margin-top: 15px;
    }
  }
}
</style>
