<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

 https://www.mall4j.com/

 未经允许，不可做商业用途！

 版权所有，侵权必究！
-->
<template>
  <div class="component-img-box">
    <el-dialog
      v-model="visible"
      width="50%"
      :title="$t('biz.imgbox.picManager')"
      top="6vh"
      append-to-body
      class="elx-imgbox-dialog append-to-body-dialog"
      @close="closeDialog()"
    >
      <div class="file-group up-imgs">
        <div class="upload-btn">
          <div class="up-btn">
            <el-button
              v-permission="['resource:img:uploadImg']"
              type="primary"
              plain
              @click="uploadFileBtn"
            >
              {{ $t('biz.imgbox.uploadPic') }}
            </el-button>
          </div>
          <!-- 搜索 -->
          <el-form
            :inline="true"
            :model="dataForm"
            class="form"
            @submit.prevent
          >
            <el-form-item>
              <el-input
                v-model="fileName"
                :placeholder="$t('biz.imgbox.picName')"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="searchImg"
              >
                {{ $t("biz.imgbox.query") }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="img-group-box">
          <!-- 左侧栏 -->
          <div class="left-sidebar">
            <div class="group-list">
              <div :class="['group-item', dataForm.attachFileGroupId===0?'active':'']">
                <span
                  class="group-name"
                  @click="clickOneGroup(0)"
                >{{ $t('biz.imgbox.allPic') }}</span>
              </div>
              <div
                v-for="(gItem, gIdx) in groupList"
                :key="gIdx"
                :class="['group-item', dataForm.attachFileGroupId===gItem.attachFileGroupId?'active':'']"
              >
                <span
                  class="group-name"
                  @click="clickOneGroup(gItem.attachFileGroupId)"
                >{{ gItem.name }}</span>
                <span class="sidebar-operate" />
              </div>
            </div>
          </div>

          <!-- 图片列表 -->
          <div
            v-if="options.activeTab==='pick'"
            class="pick-block"
          >
            <div
              class="elx-main elx-img-list"
              style="width:100%;"
            >
              <div
                v-if="isLoading"
                class="elx-img-list-loading"
              >
                <el-icon class="el-icon-loading">
                  <Loading />
                </el-icon>
              </div>
              <div
                v-for="(img, itemIndex) in imgRes"
                :key="itemIndex"
                class="img-item"
              >
                <div
                  class="thumb-wp"
                  @click="onClickListImage(img)"
                >
                  <img-show :src="img.filePath" />
                </div>
                <div
                  class="title"
                  @click="onClickListImage(img)"
                >
                  {{ img.fileName }}
                </div>
                <span
                  v-if="img.selected"
                  class="selected"
                  @click="onClickListImage(img)"
                >
                  <el-icon class="icon el-icon-check"><Check /></el-icon>
                </span>
              </div>
              <div
                v-if="!imgRes.length"
                class="empty"
              >
                {{ $t('biz.imgbox.noPic') }}
              </div>
            </div>

            <el-pagination
              layout="->, total, prev, pager, next"
              :current-page="page.current"
              :page-size="page.size"
              :total="page.total"
              style="float: right"
              @current-change="onPageNumChange"
            />

            <div class="elx-foot">
              <el-badge
                v-if="!type"
                :value="images.length"
                class="item"
              >
                <el-button
                  type="primary"
                  :class="[images.length === 0 ? 'gray-btn' : '']"
                  :disabled="images.length === 0"
                  @click="onConfirm"
                >
                  {{ $t("table.confirm") }}
                </el-button>
              </el-badge>
              <el-button
                v-else
                type="primary"
                :class="[images.length === 0 ? 'gray-btn' : '']"
                :disabled="disabled"
                @click="onConfirm"
              >
                {{ $t("table.confirm") }}
              </el-button>
              <el-button
                v-permission="['resource:img:uploadImg']"
                type="primary"
                plain
                style="margin-left: 10px"
                @click="uploadFileBtn"
              >
                {{ $t("biz.imgbox.uploadPic") }}
              </el-button>
            </div>
          </div>

          <!-- 上传图片 -->
          <div
            v-if="options.activeTab==='upload'"
            class="upload-block"
          >
            <div class="elx-main">
              <div class="upload-title">
                {{ $t('biz.imgbox.selectPicGroup') }}：
              </div>
              <div class="file-gropu-btn">
                <!-- <span>分组：</span> -->
                <el-select
                  v-model="groupForm.attachFileGroupId"
                  class="select-array"
                  :placeholder="$t('biz.imgbox.selectPicGroup')"
                >
                  <el-option
                    v-for="item in groupList"
                    :key="item.attachFileGroupId"
                    :label="item.name"
                    :value="item.attachFileGroupId"
                  />
                </el-select>
                <el-button
                  v-if="!selectGroupName"
                  v-permission="['resource:img:saveImgGroup']"
                  style="margin-left: 10px"
                  link
                  type="primary"
                  @click="selectOrCreateGroup(1)"
                >
                  {{ $t('biz.imgbox.newGroup') }}
                </el-button>
              </div>
              <div class="upload-title">
                {{ $t("biz.imgbox.selectLocalPic") }}
              </div>
              <el-upload
                ref="uploadRef"
                v-model:file-list="fileList"
                :class="['upload-img-preview',hideUploadEdit?'hide':'']"
                list-type="picture-card"
                accept=".jpg,.png,.gif,.jpeg"
                action=""
                :http-request="httpRequest"
                :multiple="true"
                :auto-upload="false"
                :limit="uploadNumberLimit()"
                :before-upload="beforeUpload"
                :on-change="handleAvatarChange"
                :on-success="onUploadSuccess"
                :on-error="onUploadError"
                :on-exceed="onUploadExceedTip"
                :before-remove="beforeRemove"
                :on-remove="onRemove"
              >
                <el-icon class="el-icon-plus">
                  <Plus />
                </el-icon>
              </el-upload>

              <div class="upload-tip">
                {{ uploadTips() }}
              </div>

              <div class="elx-foot">
                <el-button
                  type="primary"
                  @click="onUploadConfirm"
                >
                  {{ $t("biz.imgbox.confirmUpload") }}
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 选择/创建/修改分组 -->
        <el-dialog
          v-model="showGroupVisible"
          :title="showGroupType===0?$t('biz.imgbox.selectGroup')
            :showGroupType===1?$t('biz.imgbox.newGroup'):$t('biz.imgbox.modifyGroup')"
          :append-to-body="showGroupVisible"
          :close-on-click-modal="false"
          width="600px"
        >
          <el-form
            ref="groupFormRef"
            :model="groupForm"
            :rules="rules"
            label-width="90px"
            style="width:500px"
            @submit.prevent
          >
            <el-form-item
              v-if="showGroupType !== 0"
              :label="$t('biz.imgbox.groupName')"
              prop="name"
            >
              <el-input
                v-model="groupForm.name"
                :placeholder="$t('biz.imgbox.groupNameTips')"
                show-word-limit
                maxlength="20"
              />
            </el-form-item>
            <el-form-item
              v-if="showGroupType===0"
              :label="$t('biz.imgbox.selectGroup')"
            >
              <el-select
                v-model="groupForm.attachFileGroupId"
                :placeholder="$t('biz.imgbox.selectTips')"
              >
                <el-option
                  v-for="item in groupList"
                  :key="item.attachFileGroupId"
                  :label="item.name"
                  :value="item.attachFileGroupId"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div
              class="dialog-footer"
            >
              <el-button
                plain
                @click="showGroupVisible = false"
              >
                {{ $t('table.cancel') }}
              </el-button>
              <el-button
                type="primary"
                @click="groupFormSubmit()"
              >
                {{ $t('table.confirm') }}
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>

      <!-- 修改图片名称 -->
      <el-dialog
        v-model="changeNameVisible"
        :title="$t('biz.imgbox.revisePicName')"
        :close-on-click-modal="false"
        top="160px"
        :append-to-body="visible"
        width="500px"
        class="changebox"
      >
        <el-form
          v-if="changeNameVisible"
          ref="imgDataForm"
          :model="imageObject"
          label-width="90px"
          @submit.prevent
        >
          <el-form-item :label="$t('biz.imgbox.pic')">
            <img-show
              :src="imageObject.filePath"
              :class-list="['changebox-img']"
            />
          </el-form-item>
          <el-form-item :label="$t('biz.imgbox.oldName')">
            <span class="old-name">{{ imageObject.fileName }}</span>
          </el-form-item>
          <el-form-item :label="$t('biz.imgbox.revName')">
            <el-input
              v-model="newImgName"
              :placeholder="$t('biz.imgbox.inputNewName')"
              maxlength="20"
              clearable
              style="width:350px"
            />
          </el-form-item>
          <el-form-item :label="$t('biz.imgbox.group')">
            <el-select
              v-model="groupForm.attachFileGroupId"
              :placeholder="$t('biz.imgbox.selectTips')"
            >
              <el-option
                v-for="item in groupList"
                :key="item.attachFileGroupId"
                :label="item.name"
                :value="item.attachFileGroupId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span
            class="dialog-footer"
          >
            <el-button
              plain
              @click="changeNameVisible = false"
            >{{ $t("table.cancel") }}</el-button>
            <el-button
              type="primary"
              @click="submitImgName()"
            >{{ $t("table.confirm") }}</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- /修改图片名称 -->
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import ImageCompressor from 'compressorjs'
import { page as pageApi, save, updateFileName } from '@/api/biz/attach-file'
import { aswImgUpdate, getBatchPreSignUrl, pageFileGroup, saveFileGroup, updateFileGroup } from '@/api/biz/oss'
import { Debounce } from '@/utils/debounce'
const Data = reactive({
  fileList: [], // 图片列表
  images: [], // 已选图片
  fileIds: [], // 已选图片的fileId
  sizeFlag: 0, // 避免错误提示重复弹出
  dataForm: {
    policy: '',
    signature: '',
    key: '',
    ossaccessKeyId: '',
    dir: '',
    host: '',
    attachFileGroupId: ''
  },
  groupList: [], // 分组列表
  hideUploadEdit: false, // 上传按钮显示
  attachFiles: [],
  resourcesActionType: import.meta.env.VITE_APP_RESOURCES_TYPE,
  showGroupVisible: false, // 选择/创建分组弹窗
  showGroupType: 0, // 0选择分组 1创建分组 2修改分组
  groupForm: {
    attachFileGroupId: '', // 选择分组的值
    name: '' // 分组名称
  },
  fileType: 1, // 文件类型
  selectGroupName: '', // 选中的分组名称
  oriImgName: null, // 图片原名称
  options: {
    multiple: true, // 是否支持选取多个图片
    limit: 20, // 最多可选择图片数量
    maxSize: 512, // 最大尺寸（kb）
    activeTab: 'pick',
    enableUpload: false, // 是否启用图片上传
    callback: null
  },
  newImgName: '',
  ossList: null,
  isTrue: true,
  imageObject: null,
  changeNameVisible: false,
  type: 2,
  fileName: '',
  listType: 'picture',
  isLoading: true,
  visible: false,
  disabled: false,
  notImg: false,
  uploadSuccessCount: 0,
  imgRes: [],
  page: {
    current: 1,
    size: 15,
    total: 0
  },
  fileIndex: 0, // 图片位置索引，用于获取文件数组中当前上传文件的位置
  completeCount: 0, // 传输完成数量，用于控制文件全部上传成功才进入onSuccess方法
  uploadDisabled: false,
  uploadSubmitFlag: false
})

const { fileList, images, dataForm, groupList, showGroupVisible, hideUploadEdit, showGroupType, groupForm, selectGroupName, options, newImgName, imageObject, changeNameVisible, type, fileName, isLoading, visible, disabled, imgRes, page } = toRefs(Data)
const emit = defineEmits(['refreshPic'])

const rules = reactive({
  name: [
    { required: true, message: $t('biz.imgbox.groupEmpty'), trigger: 'blur' },
    { min: 1, max: 20, message: $t('biz.imgbox.groupBetween'), trigger: 'blur' }
  ]
})

const uploadRef = ref(null)
// 初始化
// type 1：单图  2：多图
const init = (type, limit) => {
  Data.visible = true
  Data.isLoading = false
  Data.images = []
  Data.fileIds = []
  Data.type = type
  if (type === 1) {
    Data.type = true
    Data.disabled = true
  } else {
    Data.type = false
    Data.limit = limit
  }
  if (uploadRef.value) {
    Data.fileList = []
  }
  // 获取产品数据 - 第一页的数据
  Data.page.current = 1
  loadImageGroup() // 分组
  loadListImage() // 图片列表
}

// 加载图片分组列表
const loadImageGroup = () => {
  pageFileGroup({ type: Data.fileType }).then((data) => {
    Data.groupList = data
  })
}

// 点击图片分组item
const clickOneGroup = (id) => {
  Data.page.current = 1
  Data.dataForm.attachFileGroupId = id
  Data.options.activeTab = 'pick'
  loadListImage()
}

// 打开选择/新建分组
// st 0选择分组 1创建/修改分组
// showGroupType 0选择分组 1创建分组 2修改分组
const selectOrCreateGroup = (st, groupId, gIdx) => {
  Data.showGroupType = st
  if (!groupId) {
    Data.groupForm.attachFileGroupId = ''
    Data.groupForm.name = ''
  }
  // 修改分组
  if (st && groupId) {
    if (st === 1) {
      Data.groupForm.name = Data.groupList[gIdx].name
      Data.groupForm.attachFileGroupId = groupId
      Data.showGroupType = 2 // 修改分组名称
    }
  }
  if (st === 0) { // 选择分组
    if (!Data.groupList.length) {
      ElMessage({
        message: $t('biz.imgbox.noGroupSelect'),
        duration: 1500
      })
      Data.showGroupVisible = false
      return
    }
  }
  Data.showGroupVisible = true
}

// 提交选择/创建/修改分组
const groupFormRef = ref(null)
const groupFormSubmit = () => {
  groupFormRef.value.validate(valid => {
    if (!valid) {
      return
    }
    if (!Data.groupForm.name.trim()) {
      ElMessage({
        message: $t('biz.imgbox.groupEmpty'),
        type: 'warning',
        duration: 1000
      })
      return
    }
    if (Data.showGroupType === 0) {
      if (!Data.groupForm.attachFileGroupId) {
        ElMessage({
          message: $t('biz.imgbox.pleaseSelectGroup'),
          type: 'warning',
          duration: 1000
        })
        return
      }
      Data.groupList.forEach(el => {
        if (Data.groupForm.attachFileGroupId === el.attachFileGroupId) {
          Data.groupForm.name = el.name
          Data.selectGroupName = el.name
        }
      })
      Data.showGroupVisible = false
      return
    }
    if (Data.showGroupType !== 0) {
      if (!Data.groupForm.name) {
        ElMessage({
          message: $t('biz.imgbox.groupEmpty'),
          type: 'warning',
          duration: 1000
        })
        return
      }
      const param = {
        attachFileGroupId: Data.groupForm.attachFileGroupId,
        name: Data.groupForm.name,
        type: Data.fileType
      }
      const request = Data.groupForm.attachFileGroupId ? updateFileGroup(param) : saveFileGroup(param)
      request.then(() => {
        ElMessage({
          message: $t('table.actionSuccess'),
          type: 'success',
          duration: 800,
          onClose: () => {
            Data.groupForm.attachFileGroupId = ''
            Data.showGroupVisible = false
            loadImageGroup()
          }
        })
      }).catch(() => {})
    }
  })
}

// 加载图片列表数据
const loadListImage = () => {
  Data.isLoading = true
  const param = {
    pageNum: Data.page.current ? Data.page.current : 1,
    pageSize: Data.page.size,
    fileName: Data.fileName ? Data.fileName : null,
    attachFileGroupId: Data.dataForm.attachFileGroupId || '',
    type: Data.fileType,
    sysType: 3
  }
  pageApi(param).then(response => {
    Data.imgRes = response.list
    Data.imgRes.forEach(img => {
      if (Data.fileIds.indexOf(img.fileId) !== -1) {
        img.selected = true
      }
    })
    Data.page.pages = response.pages
    Data.page.total = response.total
    Data.isLoading = false
  })
}

const onConfirm = Debounce(() => {
  if (Data.type) {
    emit('refreshPic', Data.images[0].filePath)
  } else {
    const imgPaths = Data.images.map(file => {
      return file.filePath
    }).join(',')
    emit('refreshPic', imgPaths)
  }
  Data.visible = false
}, 1000)

// 提交修改后的图片名称
const submitImgName = () => {
  if (!Data.isTrue) {
    return false
  }

  Data.isTrue = false
  const data = {
    fileId: Data.imageObject.fileId,
    fileName: Data.newImgName ? Data.newImgName : Data.oriImgName,
    attachFileGroupId: Data.groupForm.attachFileGroupId,
    sysType: 3
  }
  updateFileName(data).then(() => {
    Data.newImgName = ''
    Data.isTrue = true
    Data.changeNameVisible = false
    Data.loadListImage()
  }).catch(() => {
    Data.isTrue = true
  })
}

// 点击上传图片按钮
const uploadFileBtn = () => {
  Data.fileList = []
  Data.options.activeTab = 'upload'
  Data.groupForm.attachFileGroupId = Data.dataForm.attachFileGroupId || ''
  Data.images = []
  Data.fileIds = []
  Data.disabled = false
  Data.dataForm.attachFileGroupId = null
}

// 点击图片时选中或取消选中图片
// @param img object
const onClickListImage = (img) => {
  // 单选图片
  if (Data.type) {
    clearListSelected()
    Data.images = []
    Data.fileIds = []
    Data.disabled = false
  } else {
    // 多选图片-如果已选中则取消选中
    const imgIndex = selectedImageIndex(img)
    if (imgIndex >= 0) {
      // 取消图片已选状态
      img.selected = false
      Data.images.splice(imgIndex, 1)
      Data.fileIds.splice(imgIndex, 1)
      return
    }
  }
  if (!Data.type && Data.images.length >= Data.limit) {
    ElMessage($t('biz.imgbox.superiorLimit'))
    return false
  }
  Data.images.push(JSON.parse(JSON.stringify(img)))
  Data.fileIds.push(img.fileId)
  img.selected = true
}

// 清除所有已点击图片样式
const clearListSelected = () => {
  if (Data.type) {
    Data.imgRes.forEach(element => {
      element.selected = false
    })
  }
}

// 按图片名称搜索图片
const searchImg = () => {
  Data.page.current = 1
  loadListImage()
}

// 图片已选则返回下标，未选则返回-1
const selectedImageIndex = (img) => {
  for (let i = 0; i < Data.images.length; i++) {
    const selectedImg = Data.images[i]
    if (selectedImg.fileId === img.fileId) {
      return i
    }
  }
  return -1
}

// 分页页面变化时刷新数据
const onPageNumChange = (page) => {
  Data.page.current = page
  loadListImage()
}

// 移除图片
const onRemove = () => {
  // eslint-disable-next-line no-var, max-statements-per-line
  const time = setTimeout(() => {
    Data.hideUploadEdit = false
    clearTimeout(time)
  }, 1000)
  if (Data.uploadSubmitFlag) {
    Data.uploadDisabled = false
  } else {
    Data.uploadDisabled = true
    // eslint-disable-next-line no-var, max-statements-per-line
    const time1 = setTimeout(() => {
      Data.uploadDisabled = false
      clearTimeout(time1)
    }, 1000)
  }
}

const beforeRemove = () => {
  // 防止用户频繁点击导致删除过多
  return !Data.uploadDisabled
}

// 获取上传图片数据
const onUploadConfirm = () => {
  Data.uploadSubmitFlag = true
  // eslint-disable-next-line no-var, max-statements-per-line
  const time = setTimeout(() => {
    Data.uploadSubmitFlag = false
    clearTimeout(time)
  }, 1000)
  // 重置文件索引位置和完成文件记录数
  Data.fileIndex = 0
  Data.completeCount = 0
  Data.ossList = []
  Data.attachFiles = []
  Data.sizeFlag = 0

  const fileNum = Data.fileList.length
  const fileNames = Data.fileList?.map((item) => item.name).join(',')
  if (fileNum === 0) {
    return ElMessage({
      message: $t('product.plePictureToUpload'),
      type: 'warning'
    })
  }
  getBatchPreSignUrl({ fileNames }).then(response => {
    Data.ossList = response
    Data.notImg = true
    nextTick(() => {
      uploadRef.value.submit()
    })
  })
}

// 上传图片
const httpRequest = (event) => {
  if (Data.sizeFlag !== 0) {
    return
  }

  // 获取本次上传文件的位置
  const currentIndex = Data.fileIndex++

  const file = event.file
  const typeArray = file.type.split('/')
  if (typeArray[1] === 'jpeg') typeArray[1] = 'jpg'
  const attachFile = Object.assign({
    fileType: typeArray[1],
    fileName: file.name,
    fileSize: file.size,
    type: 1
  })

  if (Data.ossList.length <= 0) {
    ElMessage('数据异常，请刷新后重试')
  }

  // 文件上传

  attachFile.filePath = '/' + Data.ossList[currentIndex].dir + Data.ossList[currentIndex].fileName
  aswImgUpdate(Data.ossList[currentIndex].preSignUrl, file, event).then(() => {
    Data.attachFiles.push(attachFile)
    Data.completeCount++
    if (Data.completeCount === Data.ossList.length) {
      event.onSuccess()
    }
  }).catch(() => {
    Data.message($t('biz.imgbox.uploadBefore') + (currentIndex + 1) + $t('biz.imgbox.uploadAfter'), true)
    Data.completeCount++
    if (Data.completeCount === Data.ossList.length) {
      event.onSuccess()
    }
  })
}

// 上传图片前检查合法性
const beforeUpload = async (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isSize = file.size / 1024 < Data.options.maxSize
  if (!isImage) {
    if (Data.sizeFlag === 0) {
      ElMessage($t('biz.imgbox.onlyPictures'), true)
      Data.sizeFlag += 1
    }
    Data.notImg = false
    return Promise().reject()
  }
  if (!isSize) {
    // 0.5m~5m，从0.8开始循环。5m~10m，从0.6开始循环。10m以上就直接0.4。
    // 最低使用0.4
    let quality
    if (file.size / 1024 / 1024 < 5) {
      quality = 0.8
    } else if (file.size / 1024 / 1024 < 10) {
      quality = 0.6
    } else {
      quality = 0.4
    }
    try {
      let resultBlob
      let index = true
      while (index) {
        resultBlob = await ImageCompressorFn(file, quality)
        if (resultBlob.size / 1024 < 512 || quality <= 0.4) {
          index = false
        } else {
          quality = (quality * 10 - 2) / 10
        }
      }
      return new File([resultBlob], file.name, {
        type: file.type
      })
    } catch (error) {
      return Promise().reject()
    }
  }
  return true
}

const ImageCompressorFn = (file, quality) => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line no-new
    new ImageCompressor(file, {
      quality, // 压缩大小
      convertSize: 512000,
      success (result) {
        resolve(result)
      },
      error (err) {
        reject(err)
      }
    })
  })
}

const uploadNumberLimit = () => {
  if (!Data.options.multiple) {
    return 1
  }

  return Data.options.limit - Data.images.length
}

const uploadTypeTip = () => {
  return $t('biz.imgbox.onlySupported') + ' jpg/png/gif ' + $t('biz.imgbox.pic')
}

// const uploadSizeTip = () => {
//   return $t('biz.imgbox.notExceed') + '2M'
// }

const uploadTips = () => {
  const tips = [uploadTypeTip()]
  if (!Data.options.multiple) {
    return tips.join('，')
  }

  if (Data.fileNum > 0) {
    tips.push($t('biz.imgbox.alreadyExist') + Data.fileNum + $t('biz.imgbox.unit'))
  }
  const uploadFileNum = Data.fileList ? Data.fileList.length : 0
  if (uploadFileNum > 0) {
    tips.push($t('biz.imgbox.soonUpload') + uploadFileNum + $t('biz.imgbox.unit'))
  }

  tips.push($t('biz.imgbox.remainder') + (Data.options.limit - uploadFileNum) + $t('biz.imgbox.unit') + $t('biz.imgbox.upload'))

  return tips.join('，')
}
// 图片预上传 提示文字变更
// eslint-disable-next-line no-unused-vars
const handleAvatarChange = (file, fileList) => {
  if (fileList.length >= 20) {
    Data.hideUploadEdit = true
  }
  Data.fileNum = fileList.length
}

/**
 * 上传错误处理
 * @param err
 */
const onUploadError = (err) => {
  ElMessage($t('biz.imgbox.requestError'), true)
  throw err
}

/**
 * 上传成功处理，并提交图片数据
 * @param response
 * @param file
 * @param fileList
 * @returns {boolean}
 */
// eslint-disable-next-line no-unused-vars
const onUploadSuccess = (response, file, fileList) => {
  const filesNames = []
  fileList.forEach(file => {
    filesNames.push(file.name)
  })
  const uploadFile = []
  Data.attachFiles.forEach(file => {
    if (filesNames.indexOf(file.fileName) !== -1) {
      file.attachFileGroupId = Data.groupForm.attachFileGroupId
      file.sysType = 3
      uploadFile.push(file)
    }
  })
  if (uploadFile.length > 0) {
    save(uploadFile).then(() => {
      Data.attachFiles = []
      Data.options.activeTab = 'pick'
      Data.dataForm.attachFileGroupId = 0
      loadListImage()
    })
  }
  Data.disabled = true
  Data.fileList = []
  Data.page.current = 1
  Data.groupForm.name = ''
  Data.groupForm.attachFileGroupId = ''
  Data.selectGroupName = ''
  setTimeout(() => {
    Data.hideUploadEdit = false
  }, 1000)
}

/**
 * 选择上传文件超过限制文件个数提示
 */
const onUploadExceedTip = () => {
  ElMessage($t('biz.imgbox.maxSelect') + uploadNumberLimit() + $t('biz.imgbox.unit') + $t('biz.imgbox.upload'))
}

// 关闭dialog 清空数据
const closeDialog = () => {
  Data.options.activeTab = 'pick'
  Data.fileName = ''
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
@use "index";
</style>
