<!-- 封面组件 -->
<template>
  <div>
    <div class="uploader-log" @click="openDialog">
      <div v-if="!getImageUrl(item)">
        <i class="el-icon-plus"></i>
        <div>选择封面</div>
      </div>

      <div v-else>
        <img :src="getImageUrl(item)" />
      </div>
    </div>

    <!-- 选择图片弹出框 -->
    <el-dialog class="cover-image-dialog" :visible="visible" :title="'选择图片'" width="960px" :close-on-click-modal="false"
      :before-close="cancel" append-to-body>
      <div class="row">
        <aside>
          <!-- 筛选 -->
          <div class="filter">
            <slot name="head_filter" style="display: inline"></slot>
            <span style="display: inline-block">
              <cs-field-search v-model="filter.keywords"></cs-field-search>
            </span>
            <el-link style="margin-left: 5px" icon="el-icon-refresh" :title="$t('common.refresh')" @click="init"></el-link>
          </div>

          <!-- 上传文件 -->
          <div class="button">
            <div class="el-upload__tip">只能上传jpg、png、jpeg、gif文件，且不超过5M</div>

            <el-upload :action="'/api/DbFile/{0}'.format(this.tenantId)" accept="image/jpg, image/jpeg, image/png, image/gif"
              :show-file-list="false" multiple :limit="9" :on-success="uploadSuccess" :on-error="uploadError" :before-upload="beforeUpload"
              :on-exceed="handleExceed">
              <el-button size="mini" type="primary">点击上传</el-button>
            </el-upload>
          </div>
          <div class="clearfloat"></div>
        </aside>

        <!-- 图片内容 -->
        <div class="image-list" v-for="image in images" :key="image.Id" @click="coverItem = image">
          <el-image class="image-item" :class="(coverItem && coverItem.Id == image.Id) ? 'selection' : ''" :src="getImageUrl(image)">
          </el-image>
          <div class="title">
            <span>{{ image.Title }}</span>
          </div>
        </div>
        <div class="clearfloat"></div>

        <!-- 下部分页标签 -->
        <cs-table-pagination :currentPage="page" :pageSize="pageSize" :pageSizes="pageSizes" :total="total"
          @change="handlePageOrSizeChange"></cs-table-pagination>
      </div>

      <div class="footer-button">
        <cs-button @click="cancel()">取消</cs-button>
        <cs-button-save @click="confirm()" :disabled="!coverItem">确定</cs-button-save>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Request from '../../../lib/utils/request'

export default {
  name: 'CsCoverImage',
  props: {
    value: {
      type: String,
      default: null,
    },
    tenantId: {
      type: Number,
      default: null,
    },
    objectTypeName: {
      type: String,
      default: null,
    },
  },
  components: {},
  data() {
    return {
      imageUrl: '',
      item: {},

      visible: false,
      coverItem: null,

      page: 1,
      pageSize: 12,
      pageSizes: [12],
      total: 0,
      filter: {
        keywords: '',
      },

      platformDatas: [],
      originalDatas: [],
      images: [],
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    filter: {
      handler(val) {
        this.initData()
      },
      immediate: false, // 首次绑定是否执行
      deep: true, // 对象内部的属性监听，也叫深度监听
    },
  },
  //方法集合
  methods: {
    /** 获取图片地址 */
    getImageUrl(item) {
      if (!item) {
        return false
      }
      if (item.FileId) {
        return this.$util.getThumbnail(this.tenantId, item.FileId)
      } else if (item.FileUrl) {
        return item.FileUrl
      }
    },

    /** 上传文件之前检查 */
    beforeUpload(file) {
      switch (file.type) {
        case 'image/png':
        case 'image/jpg':
        case 'image/jpeg':
        case 'image/gif':
          break
        default:
          this.$util.warning('上传的图片格式不正确')
          return false
      }
      return true
    },

    /** 文件超出个数限制时 */
    handleExceed(files, fileList) {
      this.$message.warning(
        `单次最多上传9个文件，本次选择了 ${files.length} 个文件`
      )
    },

    /** 上传图片失败 */
    uploadError(res) {
      this.$emit('on-error', res)
    },

    /** 上传图片成功 */
    uploadSuccess(fileId) {
      Request({
        url: '/api/CoverImage/{0}'.format(this.tenantId),
        params: { fileId: fileId, objectTypeName: this.objectTypeName },
        method: 'post',
      }).then((res) => {
        this.originalDatas.unshift(res)
        this.initData()
      })
    },

    /** 打开弹出框 */
    openDialog() {
      this.visible = true
      this.init()
    },

    /** 取消 */
    cancel() {
      this.coverItem = null
      this.visible = false
    },

    /** 确认 */
    confirm() {
      this.$emit('input', this.getImageUrl(this.coverItem))
      this.item = this.$util.copy(this.coverItem)
      this.cancel()
    },

    /** 当前页面或者页面显示数据个数变动 */
    handlePageOrSizeChange({ currentPage, pageSize }) {
      this.page = currentPage
      this.pageSize = pageSize
      this.initData()
    },

    /** 筛选 */
    filterItemFunc(item) {
      const filter = this.filter
      //关键字筛选
      if (filter.keywords) {
        if (!this.$util.containsObjProperty(item, filter.keywords, ['Title'])) {
          return false
        }
      }
      return true
    },

    /** 构造数据 */
    initData() {
      // 生成表格数据
      this.images = []
      let tableData = []
      for (let i = 0; i < this.originalDatas.length; i++) {
        const item = this.$util.copy(this.originalDatas[i])

        //如果筛选不通过跳过
        if (!this.filterItemFunc(item)) {
          continue
        }
        tableData.push(item)
      }
      this.total = tableData.length
      this.images = tableData.slice(
        (this.page - 1) * this.pageSize,
        this.page * this.pageSize
      )
    },

    /** 获取所有封面信息 */
    init() {
      Request({
        url: '/api/CoverImage/{0}'.format(this.tenantId),
        params: { objectTypeName: this.objectTypeName },
        method: 'get',
      }).then((res) => {
        this.platformDatas = []
        res.forEach((group) => {
          // 租户
          if (group.Type == 1) {
            this.originalDatas = group.CoverImages
          }
          // 平台
          else if (group.Type == 0) {
            this.platformDatas = group.CoverImages
          }
        })

        this.initData()
      })
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    if (!this.tenantId) {
      this.$util.warning('请传入租户编号')
      return
    }

    if (!this.objectTypeName) {
      this.$util.warning('请传入对象类型名称')
      return
    }

    if (this.value) {
      this.item = { FileUrl: this.value }
    }
  },
  mounted() {}, //生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
aside {
  height: auto;
  padding: 5px;
  margin: 0px;

  .button {
    right: 4px;
    float: right;
    white-space: nowrap;
    margin-left: 10px;
    display: flex;
    text-align: right;

    .el-upload__tip {
      margin: 0 10px 0 0;
    }
  }

  .filter {
    right: 4px;
    float: left;
    padding-left: 5px;
  }
}

// 外部 选择封面样式
.uploader-log {
  max-width: 300px;
  min-width: 300px;
  height: 168.75px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  padding-top: 55px;
  text-align: center;

  i {
    width: 100%;
    color: #8c939d;
    font-size: 28px;
    text-align: center;
  }
  img {
    width: 100%;
    height: 100%;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    object-fit: cover;
    object-position: center;
  }
}
.uploader-log:hover {
  border-color: #409eff;
}

// 弹出框 底部按钮
.footer-button {
  text-align: center;
  margin-top: 15px;
}
</style>
<style lang='scss'>
// 图片弹出框
.cover-image-dialog {
  .el-dialog__body {
    padding-left: 0 !important;

    // 图片内容
    .row {
      width: 100%;
      padding: 20px;

      // 图片显示列表
      .image-list {
        float: left;
        margin: 10px;
        text-align: center;

        .image-item {
          width: 130px;
          height: 130px;
          border: 1px solid white;

          img {
            max-width: 130px;
            max-height: 130px;
            object-fit: contain;
            object-position: center;
          }
        }

        .image-item.selection {
          border: 1px solid #1890ff;
          border-radius: 3px;
        }

        .image-item:hover {
          border: 1px dotted #1890ff;
          border-radius: 3px;
        }

        .image-item.selection:hover {
          border: 1px solid #1890ff;
          border-radius: 3px;
        }
      }

      // 分页组件
      .el-pagination {
        margin-top: 15px;
      }
    }
  }
}
</style>