<template>
  <div class="app-container">
    <div class="pic-header-container">
      <div>
        <el-breadcrumb>
          <el-breadcrumb-item v-show="!toggleOne">全部相册</el-breadcrumb-item>
          <div v-show="toggleOne">
            <el-breadcrumb-item>
              <el-button type="text" style="padding:0" @click="handleBackAll">全部相册</el-button>
            </el-breadcrumb-item>
            <el-breadcrumb-item>{{ groupInfo.name }}</el-breadcrumb-item>
          </div>
        </el-breadcrumb>
      </div>
      <div>
        <!-- <el-input v-model="searchParams.search_name" placeholder="查询相册名称" size="small" style="width:250px" />
        <el-button
          type="primary"
          size="small"
          @click="getCommunityPic"
        >
          查询
        </el-button> -->
        <!-- <el-button size="small" :disabled="toggleOne" @click="visible.group = true">新建相册</el-button> -->
        <el-button size="small" @click="handleSetUpload">新建相册</el-button>
      </div>
    </div>
    <!-- 全部 -->
    <div v-show="!toggleOne" class="img-container">
      <div
        v-for="item in imgList"
        :key="item.id"
        class="img-item"
        @click="seeGroupInfo(item)"
      >
        <div class="group-container">
          <i class="el-icon-folder-opened" style="font-size: 100px" />
        </div>
        <p class="img-name">{{ item.name }} </p>
      </div>
    </div>
    <!-- 单个相册 -->
    <div v-show="toggleOne" class="img-container">
      <div
        v-for="item in groupInfo.list"
        :key="item"
        class="img-item"
      >
        <el-image
          style="width: 130px; height: 130px;"
          :src="item"
          fit="cover"
        >
          <div slot="error" class="img-error">
            <i class="el-icon-picture-outline" style="font-size:36px" />
          </div>
        </el-image>
        <div class="hover-control">
          <i class="el-icon-delete" title="删除" style="font-size: 20px;" @click="deleteGroupOne(item)" />
        </div>
      </div>
    </div>
    <!-- 提示 -->
    <p v-if="toggleOne && groupInfo.list.length===0">该分组暂无图片</p>
    <p v-if="!toggleOne && imgList.length===0">暂无内容</p>
    <!-- 上传 -->
    <el-dialog
      title="图片上传"
      :visible.sync="visible.goods"
    >
      <el-form
        ref="uploadForm"
        :model="upload"
        :rules="uploadRule"
        label-width="100px"
        :before-close="handleCloseUpload"
      >
        <el-form-item label="相册名:" prop="name">
          <el-input v-model="upload.name" :disabled="toggleOne" />
        </el-form-item>
        <el-form-item label="图片上传:">
          <el-upload
            ref="upload"
            action=""
            multiple
            :limit="15"
            :http-request="requestUpload"
            :show-file-list="false"
            drag
            :before-upload="beforeUploadCheck"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">只能上传图片，每次最大上传数量不超过15张</div>
          </el-upload>
          <div class="img-container">
            <div
              v-for="(item, index) in fileList"
              :key="index"
              class="img-item"
            >
              <el-image
                style="width: 130px; height: 130px;"
                :src="item"
                fit="cover"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleUpload">上传</el-button>
          <el-button size="small" @click="handleCloseUpload">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 新建分组页面 -->
    <el-dialog
      title="新建相册"
      :visible.sync="visible.group"
      :before-close="handleCloseUpload"
    >
      <el-form
        ref="uploadForm"
        :model="upload"
        :rules="uploadRule"
        label-width="100px"
      >
        <el-form-item label="相册名:" prop="name">
          <el-input v-model="upload.name" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleAddGroup">创建</el-button>
          <el-button size="small" @click="handleCloseUpload">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>

import { getCommunityPic, uploadCommunityPic, uploadPic, editUploadCommunityPic } from '@/api/picture/community'

export default {
  data() {
    return {
      uploadRule: {
        name: [{ required: true, message: '请输入相册名', trigger: 'blur' }]
      },
      searchParams: {
        page_size: 10,
        page_index: 1,
        search_name: ''
      },
      imgList: [],
      tableTotal: 0,
      visible: {
        goods: false,
        group: false
      },
      upload: {
        name: ''
      },
      fileList: [],
      toggleOne: false,
      groupInfo: {
        list: [],
        name: '',
        id: ''
      }
    }
  },
  created() {
    this.getCommunityPic()
  },
  methods: {
    // 获取商品列表
    async getCommunityPic(callback) {
      try {
        const res = await getCommunityPic(this.searchParams)
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          const { list, total } = data
          this.imgList = list
          this.tableTotal = total
          callback ? callback() : null
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('获取商品图库失败')
      }
    },
    // 上传商品图片
    async uploadCommunityPic(data) {
      try {
        const res = await uploadCommunityPic(data)
        const { code, message } = res
        if (code === 200) {
          this.$message.success(message)
          this.handleCloseUpload()
          this.getCommunityPic()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('上传商品图片失败')
      }
    },
    // 自定义上传
    requestUpload(params) {
      const file = params.file
      const form = new FormData()
      form.append('file', file)
      form.append('type', 4)
      uploadPic(form).then(res => {
        if (res && res.code === 200) {
          this.fileList.push(res.data)
        }
      })
    },
    // 上传图片
    handleUpload() {
      this.$refs.uploadForm.validate((valid) => {
        if (valid) {
          if (this.fileList.length < 1) {
            this.$message.warning('还未选择图片!!!')
            return false
          } else {
            if (this.toggleOne) {
              const _this = this
              const arr = this.groupInfo.list.concat(this.fileList)
              this.editUploadCommunityPic({
                id: this.groupInfo.id,
                name: this.groupInfo.name,
                imgurl: arr
              }, () => {
                _this.handleCloseUpload()
                _this.getCommunityPic(() => {
                  // 判断存在是否相同id，重新打开
                  const sameItem = this.imgList.filter((item) => {
                    return item.id === this.groupInfo.id
                  })[0]
                  if (sameItem) {
                    this.seeGroupInfo(sameItem)
                  }
                })
              })
            } else {
              this.uploadCommunityPic({
                name: this.upload.name,
                imgurl: this.fileList
              })
            }
          }
        } else {
          return false
        }
      })
    },
    // 关闭上传
    handleCloseUpload() {
      this.$refs.uploadForm.resetFields()
      this.visible.goods = false
      this.visible.group = false
      this.fileList = []
    },
    // 重置groupinfo
    resetGroup() {
      this.groupInfo.id = ''
      this.groupInfo.name = ''
      this.groupInfo.list = []
      this.toggleOne = false
    },
    // 修改上传图片(相册添加)
    async editUploadCommunityPic(data, callback) {
      try {
        const res = await editUploadCommunityPic(data)
        const { code, message } = res
        if (code === 200) {
          this.$message.success(message)
          callback()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('修改商品图片失败')
      }
    },
    // 新建相册
    handleAddGroup() {
      this.$refs.uploadForm.validate((valid) => {
        if (valid) {
          this.uploadCommunityPic({
            name: this.upload.name,
            imgurl: []
          })
        } else {
          return false
        }
      })
    },
    // 查看相册
    seeGroupInfo(item) {
      const { imgurl, name, id } = item
      this.groupInfo.list = JSON.parse(imgurl)
      this.groupInfo.name = name
      this.groupInfo.id = id
      this.toggleOne = true
    },
    // 返回全部相册
    handleBackAll() {
      this.resetGroup()
      this.getCommunityPic()
    },
    // 点击上传按钮
    handleSetUpload() {
      if (this.toggleOne) {
        this.upload.name = this.groupInfo.name
      }
      this.visible.goods = true
    },
    // 上传文件检查
    beforeUploadCheck(file) {
      const SuffixName = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = SuffixName === 'jpg'
      const extension2 = SuffixName === 'png'
      if (!extension && !extension2) {
        this.$message.warning('只能上传jpg/png图片文件!!!')
        return false
      }
      return extension || extension2
    },
    // 删除单个相册中的图片
    deleteGroupOne(url) {
      const _this = this
      const index = this.groupInfo.list.indexOf(url)
      this.groupInfo.list.splice(index, 1)
      this.editUploadCommunityPic({
        id: this.groupInfo.id,
        name: this.groupInfo.name,
        imgurl: this.groupInfo.list
      }, () => {
        _this.getCommunityPic(() => {
          // 判断存在是否相同id，重新打开
          const sameItem = this.imgList.filter((item) => {
            return item.id === this.groupInfo.id
          })[0]
          if (sameItem) {
            this.seeGroupInfo(sameItem)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
    .pic-header-container{
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .img-container{
        display: flex;
        justify-content: flex-start;
        margin: 20px 0;

        .group-container{
            display: flex;
            justify-content: center;
            align-items: center;
            width: 130px;
            height: 130px;
            background: #F5F7FA;
            border: 1px solid #f1f1f1;
        }

        .img-item{
            width: 130px;
            height: 130px;
            margin-right: 20px;
            margin-bottom: 20px;
            cursor: pointer;
            position: relative;
            background: #f3f3f3;

            .hover-control{
                position: absolute;
                left: 0;
                right: 0;
                bottom: 0;
                display: none;
                color: #ffffff;
                height: 35px;
                line-height: 35px;
                text-align: center;
                background: #c1c1c1;
            }
        }
        .img-item:hover .hover-control{
            display: block;
        }
    }
</style>

<style lang="scss">
    .img-name {
        line-height: 30px;
        height: 30px;
        text-align: center;
        margin: 0;
        font-size: 12px;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
    }
    .img-error{
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #F5F7FA;
    }
</style>
