<template>
  <el-dialog
    :append-to-body="appendToBody"
    title="素材库"
    top="5%"
    :visible.sync="dialogFormVisible"
    width="80%"
    @close="close"
  >
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <!--        <div-->
        <!--          v-loading="galleryLoading"-->
        <!--          style="display: flex; justify-content: space-around; padding: 10px"-->
        <!--        >-->
        <el-button
          :type="gallery_type === 'image' ? 'primary' : ''"
          @click="queryGalleryData('image')"
        >
          {{ __('图片') }}
        </el-button>
        <el-button
          :type="gallery_type === 'video' ? 'primary' : ''"
          @click="queryGalleryData('video')"
        >
          {{ __('视频') }}
        </el-button>
        <el-button
          v-if="false"
          :type="gallery_type === 'audio' ? 'primary' : ''"
          @click="queryGalleryData('audio')"
        >
          {{ __('音频') }}
        </el-button>
        <el-button
          v-if="false"
          :type="gallery_type === 'document' ? 'primary' : ''"
          @click="queryGalleryData('document')"
        >
          {{ __('文档') }}
        </el-button>
        <el-button type="warning" @click="showGallery">
          {{ __('目录管理') }}
        </el-button>
        <!--        </div>-->
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-button icon="el-icon-plus" type="primary" @click="showUploadBase">
          {{ __('添加') }}
        </el-button>
        <el-button icon="el-icon-delete" type="danger" @click="handleDelete">
          {{ __('批量删除') }}
        </el-button>
      </vab-query-form-right-panel>
    </vab-query-form>
    <div class="material-media-div">
      <el-container>
        <el-container style="height: 60vh; border: 1px solid #eee">
          <el-aside width="25%">
            <div style="height: 55vh; overflow: auto">
              <el-menu
                :default-active="queryForm.gallery_id.toString()"
                @select="selectMenu"
              >
                <el-menu-item
                  v-for="(gallery, index) in galleryList"
                  :key="gallery.gallery_id"
                  :index="gallery.gallery_id.toString()"
                >
                  <i class="el-icon-folder"></i>
                  <span slot="title">
                    {{ getGalleryName(gallery.gallery_name) }}
                  </span>
                </el-menu-item>
              </el-menu>
            </div>
          </el-aside>
          <el-main>
            <vab-query-form>
              <vab-query-form-right-panel :span="24">
                <el-form
                  :inline="true"
                  :model="queryForm"
                  @submit.native.prevent
                >
                  <el-form-item>
                    <el-input
                      v-model.trim="queryForm.media_name"
                      clearable
                      :placeholder="__('请输入文件名称')"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      icon="el-icon-search"
                      type="primary"
                      @click="queryData"
                    >
                      {{ __('查询') }}
                    </el-button>
                  </el-form-item>
                </el-form>
              </vab-query-form-right-panel>
            </vab-query-form>
            <div style="height: 44vh">
              <el-table
                v-loading="listLoading"
                border
                :data="list"
                height="45vh"
                @selection-change="setSelectRows"
              >
                <el-table-column
                  align="center"
                  show-overflow-tooltip
                  type="selection"
                />
                <el-table-column align="center" :label="__('操作')" width="120">
                  <template #default="{ row }">
                    <el-button type="text" @click="openImgDialog(row)">
                      {{ __('编辑') }}
                    </el-button>
                    <el-button type="text" @click="handleDelete(row)">
                      {{ __('删除') }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  :label="__('文件编号')"
                  prop="media_id"
                  show-overflow-tooltip
                />
                <el-table-column
                  align="center"
                  :label="__('文件名称')"
                  prop="media_name"
                  show-overflow-tooltip
                />
                <el-table-column
                  align="center"
                  :label="__('文件预览')"
                  prop="topic_id"
                  show-overflow-tooltip
                >
                  <template #default="{ row }">
                    <el-image
                      v-if="row.media_url && row.media_type === 'image'"
                      :preview-src-list="[row.media_url]"
                      :src="row.media_url"
                      style="width: 35px; height: 35px"
                    />
                    <vab-icon
                      v-else
                      icon="video-fill"
                      style="font-size: xx-large"
                      @click="showPlayer(row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  :formatter="formatSizt"
                  :label="__('文件大小')"
                  prop="media_size"
                  show-overflow-tooltip
                />
                <el-table-column
                  align="center"
                  :label="__('上传时间')"
                  prop="media_time"
                  show-overflow-tooltip
                />
              </el-table>
            </div>
            <el-pagination
              background
              :current-page="queryForm.pageNum"
              :layout="layout"
              :page-size="queryForm.pageSize"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </el-main>
        </el-container>
      </el-container>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button type="primary" @click="save">{{ __('确定') }}</el-button>
    </div>
    <upload-base ref="base" @fetch-data="fetchData" />
    <gallery ref="gallery" @fetch-data="galleries" />
    <player ref="player" />
    <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-dialog>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { galleries } from '@/api/store/media/gallery'
  import { getList, doDelete, doEdit as editMedia } from '@/api/store/media'
  import uploadBase from '@/components/material/UploadBase'
  import gallery from '@/components/material/MediaGallery'
  import player from '@/components/material/Player'

  export default {
    name: 'Media',
    components: { uploadBase, gallery, player },
    props: {
      appendToBody: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        galleryList: [],
        galleryLoading: false,
        listLoading: false,
        gallery_type: 'image', // image/video
        dialogFormVisible: false,
        list: [],
        layout: 'total, sizes, prev, pager, next, jumper',
        selectRows: '',
        dialogVisible: false,
        imgForm: {},
        total: 0,
        queryForm: {
          media_name: '',
          gallery_id: 0,
          pageNum: 1,
          pageSize: 10,
        },
      }
    },
    created() {},
    methods: {
      __,
      formatSizt(row) {
        let media_size = row.media_size
        if (media_size) {
          return (media_size / 1000).toFixed(2) + 'KB'
        }
        return 0 + 'KB'
      },
      selectMenu(gallery_id) {
        this.queryForm.gallery_id = gallery_id
        this.queryData()
      },
      async queryGalleryData(gallery_type) {
        this.queryForm.gallery_id = 0
        this.gallery_type = gallery_type
        await this.galleries()
        this.queryData()
      },
      getGalleryName(gallery_name) {
        if (gallery_name && gallery_name.length > 16) {
          return gallery_name.substring(0, 16) + '...'
        }
        return gallery_name
      },
      async showEdit() {
        await this.galleries()
        this.queryForm.gallery_id = 0
        this.queryData()
        this.dialogFormVisible = true
      },
      showUploadBase() {
        let gallery_id = this.queryForm.gallery_id
        if (gallery_id || gallery_id === 0) {
          this.$refs['base'].showEdit(gallery_id)
        } else {
          this.$baseMessage('未选择相册！', 'error')
        }
      },
      showGallery() {
        this.$refs['gallery'].showEdit()
      },
      showPlayer(row) {
        this.$refs['player'].showEdit(row)
      },
      close() {
        this.selectRows = ''
        this.gallery_type = 'image'
        this.imgForm = {}
        this.dialogFormVisible = false
      },
      save() {
        let selectRows = this.selectRows
        if (selectRows && selectRows.length > 0) {
          this.$emit('save-file', selectRows)
          this.close()
        } else {
          this.$baseMessage('未选择文件！', 'error')
        }
      },
      async galleries() {
        this.galleryLoading = true
        const { data } = await galleries({
          gallery_type: this.gallery_type,
        })
        this.galleryList = data
        this.galleryLoading = false
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      handleDelete(row) {
        if (row.media_id) {
          this.$baseConfirm(this.__('你确定要删除当前项吗'), null, async () => {
            const { msg } = await doDelete({ media_ids: row.media_id })
            this.$baseMessage(msg, 'success')
            await this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const media_ids = this.selectRows
              .map((item) => item.media_id)
              .join()
            this.$baseConfirm(
              this.__('你确定要删除选中项吗'),
              null,
              async () => {
                const { msg } = await doDelete({ media_ids: media_ids })
                this.$baseMessage(msg, 'success')
                await this.fetchData()
              }
            )
          } else {
            this.$baseMessage(this.__('未选中任何行'), 'error')
            return false
          }
        }
      },
      openImgDialog(row) {
        this.imgForm = {
          media_url: row.media_url,
          media_id: row.media_id,
          media_name: row.media_name,
          media_desc: row.media_desc,
        }
        this.dialogVisible = true
      },
      async editMedia() {
        const { msg, status } = await editMedia(this.imgForm)
        if (200 === status) {
          await this.queryData()
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
        this.dialogVisible = false
      },
      closeImgDialog() {
        this.dialogVisible = false
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const { data } = await getList(this.queryForm)
        this.list = data.items
        this.total = data.records
        this.listLoading = false
      },
    },
  }
</script>
<style>
  .material-media-div {
    height: 60vh;
    overflow: auto;
  }
</style>
