<!-- 图片管理窗口组件 一般和富文本编辑器使用-->
<template>
  <el-dialog
    :append-to-body="appendToBody"
    :title="title"
    top="10px"
    :visible.sync="dialogFormVisible"
    width="70%"
    @close="close"
  >
    <el-container style="height: 700px; border: 1px solid #eee">
      <el-aside width="22%">
        <div>
          <el-button
            style="width: 100%; font-size: 15px; background-color: #68b828"
            type="success"
          >
            图片分类管理
          </el-button>
        </div>
        <el-menu
          v-loading="listLoading"
          default-active="0"
          @select="selectMenu"
        >
          <el-menu-item
            v-for="(gallery, index) in galleries"
            :key="gallery.gallery_id"
            :index="index.toString()"
          >
            <i class="el-icon-folder"></i>
            <span slot="title">{{ gallery.gallery_name }}</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <el-container>
        <el-header style="text-align: right; font-size: 12px">
          <span style="float: left; color: #2c2e2f; font-size: 27px">
            全部图片
          </span>
          <span>
            <el-button
              v-show="!checkAll"
              type="text"
              @click="handleCheckAllChange()"
            >
              全选
            </el-button>
            <el-button
              v-show="checkAll"
              type="text"
              @click="handleCheckAllChange()"
            >
              取消全选
            </el-button>
            <el-button
              class="el-icon-document-add"
              type="text"
              @click="showUpPictures"
            >
              添加图片
            </el-button>
            <el-button
              class="el-icon-delete"
              type="text"
              @click="delClickMedia()"
            >
              删除
            </el-button>
          </span>
        </el-header>

        <el-main style="background-color: #d6d5d5; padding: 0px">
          <ul
            v-infinite-scroll="load"
            infinite-scroll-disabled="disabled"
            style="padding: 0px"
          >
            <el-checkbox-group v-model="checkedMedias">
              <li
                v-for="(media, i) in medias"
                :key="i"
                class="infinite-list-item"
              >
                <el-checkbox
                  :key="media.media_id"
                  class="checkCls"
                  :label="media"
                  style="position: absolute; right: 15px; top: 15px"
                />
                <img
                  class="imageSty"
                  :src="media.media_url"
                  @click="imageClk(media)"
                />
                <span style="float: left; width: 70%">
                  <span class="mediaName">
                    {{ media.media_name }}
                  </span>
                </span>
                <span style="float: right">
                  <el-button
                    class="el-icon-edit"
                    type="text"
                    @click="openImgDialog(media)"
                  />
                  <el-button
                    class="el-icon-delete"
                    type="text"
                    @click="delMedia(media.media_id)"
                  />
                </span>
              </li>
            </el-checkbox-group>
          </ul>
          <div v-if="loading" class="loadMsg">{{ __('加载中...') }}</div>
          <div v-if="noMore" class="loadMsg">{{ __('没有更多了') }}</div>
          <el-dialog
            append-to-body
            top="30px"
            :visible.sync="dialogVisible"
            width="40%"
            @close="closeImgDialog"
          >
            <el-row>
              <el-col>
                <img alt="" :src="imgForm.media_url" style="width: 100%" />
              </el-col>
              <el-col>
                <el-form
                  ref="imgForm"
                  label-position="top"
                  label-width="100px"
                  :model="imgForm"
                  size="medium"
                >
                  <el-form-item label="标题" prop="media_name">
                    <el-input
                      v-model="imgForm.media_name"
                      clearable
                      placeholder="请输入标题"
                      :style="{ width: '100%' }"
                    />
                  </el-form-item>
                  <el-form-item label="描述" prop="media_desc">
                    <el-input
                      v-model="imgForm.media_desc"
                      placeholder="请输入描述"
                      :style="{ width: '100%' }"
                      type="textarea"
                    />
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
              <el-button @click="closeImgDialog">{{ __('取 消') }}</el-button>
              <el-button type="primary" @click="editMedia">
                {{ __('确 定') }}
              </el-button>
            </span>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button type="primary" @click="save">{{ __('确定') }}</el-button>
    </div>
    <up-pictures ref="upPictures" @fetch-data="fetchData" />
  </el-dialog>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { galleries } from '@/api/store/media/gallery'
  import {
    getList as getMedias,
    doDelete as delMedia,
    doEdit as editMedia,
  } from '@/api/store/media'
  import UpPictures from '@/components/quill/UploadPictures'

  export default {
    name: 'Media',
    components: { UpPictures },
    props: {
      appendToBody: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        title: '',
        dialogFormVisible: false,
        imgForm: {},
        dialogVisible: false,
        checkAll: false,
        loading: false,
        checkedMedias: [],
        medias: [],
        list: [],
        galleries: [],
        listLoading: false,
        total: 0,
        query: {
          pageNum: 1,
          pageSize: 50,
        },
      }
    },
    computed: {
      noMore() {
        return this.query.pageNum * this.query.pageSize >= this.total
      },
      disabled() {
        return this.loading || this.noMore
      },
    },
    async created() {
      await this.getGalleries()
      const galleries = this.galleries
      if (galleries.length > 0) {
        this.query.gallery_id = galleries[0].gallery_id
      }
      this.medias = await this.getMedias()
    },
    methods: {
      __,
      async fetchData() {
        this.query.pageNum = 1
        this.medias = await this.getMedias()
      },
      showEdit() {
        this.dialogFormVisible = true
      },
      close() {
        this.resetCheck()
        this.dialogFormVisible = false
      },
      save() {
        let urls = this.checkedMedias.map((media) => media.media_url)
        this.$emit('media-event', urls)
        this.close()
      },
      resetCheck() {
        this.checkAll = false
        this.checkedMedias = []
      },

      // 目录点击事件
      async selectMenu(index) {
        this.resetCheck()
        this.listLoading = true
        const dex = Number(index)
        const gallery_id = this.galleries[dex].gallery_id
        this.query.gallery_id = gallery_id
        this.query.pageNum = 1
        this.medias = await this.getMedias()
        this.listLoading = false
      },
      // 全选 --- 当绑定值变化时触发的事件
      handleCheckAllChange() {
        let val = this.checkAll
        this.checkAll = !this.checkAll
        this.checkedMedias = []
        if (val) {
          return
        }
        this.checkedMedias = this.medias
      },
      // 图片点击事件
      imageClk(media) {
        const indexOf = this.checkedMedias.indexOf(media)
        if (indexOf > -1) {
          this.checkedMedias.splice(indexOf, 1)
          return
        }
        this.checkedMedias.push(media)
      },
      // 图片连续加载事件
      load() {
        this.loading = true
        setTimeout(() => {
          this.query.pageNum++
          this.addMedias()
          this.loading = false
        }, 1000)
      },
      async getMedias() {
        const { data } = await getMedias(this.query)
        this.query.pageNum = data.current
        this.total = data.records
        return data.items
      },
      async getGalleries() {
        const { data } = await galleries()
        this.galleries = data
      },
      // media_ids 可以是单个media_id 也可以是多个media_id','分隔字符串
      async delMedia(media_ids) {
        this.$baseConfirm(
          this.__('如果图片被使用，删除后则无法正常显示，是否删除？'),
          null,
          async () => {
            const { msg } = await delMedia({ media_ids: media_ids })
            this.medias = await this.getMedias()
            this.checkedMedias = []
            this.checkAll = false
            this.$baseMessage(msg, 'success')
          }
        )
      },
      delClickMedia() {
        const medias = this.checkedMedias
        if (medias.length === 0) {
          this.$baseMessage('请选择需要删除的图片！', 'success')
          return
        }
        this.delMedia(medias.media_id.toString())
      },
      async editMedia() {
        this.$baseConfirm(
          this.__('修改立马生效,是否继续？'),
          null,
          async () => {
            const { msg } = await editMedia(this.imgForm)
            this.dialogVisible = false
            this.medias = await this.getMedias()
            this.$baseMessage(msg, 'success')
          }
        )
      },
      showUpPictures() {
        this.$refs['upPictures'].showEdit(this.query.gallery_id)
      },
      openImgDialog(media) {
        const Obj = Object.assign({}, media)
        this.imgForm = {
          media_url: Obj.media_url,
          media_id: Obj.media_id,
          media_name: Obj.media_name,
          media_desc: Obj.media_desc,
        }
        this.dialogVisible = true
      },
      closeImgDialog() {
        this.dialogVisible = false
      },
    },
  }
</script>
<style>
  .infinite-list-item {
    display: inline-block;
    width: 244.13px;
    height: 279.13px;
    padding: 10px;
    margin: 10px;
    position: relative;
    background-color: #ffffff;
  }
  .imageSty {
    cursor: pointer;
    width: 224.13px;
    height: 224.13px;
  }
  .checkCls .el-checkbox__label {
    display: none;
  }
  .loadMsg {
    color: red;
    text-align: center;
    font-size: 25px;
    height: 50px;
  }
  .mediaName {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #2c2e2f;
    font-weight: 700;
    font-size: 10px;
    height: 32px;
    line-height: 32px;
  }
</style>
