<template>
  <ContentWrap>
<!--     搜索工作栏-->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="照片id" prop="Id" label-width="100px" >
        <el-input
          v-model="queryParams.id"
          placeholder="照片id"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
<!--      <el-form-item label="照片存储路径" prop="photoUrl">-->
<!--        <el-input-->
<!--          v-model="queryParams.photoUrl"-->
<!--          placeholder="请输入照片存储路径"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="上传时间" prop="createdAt">
        <el-date-picker
          v-model="queryParams.createdAt"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="选择上传时间"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create',zuid)"
          v-hasPermi="['museums:photos:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增照片
        </el-button>

        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['museums:photos:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 批量导出照片
        </el-button>
      </el-form-item>
    </el-form>

  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="id" align="center" prop="id" width="55" />
<!--      <el-table-column label="照片id" align="center" prop="groupId" />-->
      <el-table-column label="照片" align="center" prop="photoUrl" >
        <template #default="{ row }">
          <el-image
            lazy
            class="h-80px w-80px"
            :src="row.photoUrl"
            :preview-src-list="[row.photoUrl]"
            preview-teleported
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :initial-index="4"
            fit="cover"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="上传时间"
        align="center"
        prop="createdAt"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="success"
            @click="handleDownload(scope.row.photoUrl)"
          >
            下载
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['museums:photos:delete']"
          >
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PhotosForm ref="formRef" @success="getList" />

</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { PhotosApi, } from '@/api/museums/photos'
import PhotosForm from './PhotosForm.vue'
import {ref} from "vue";
import { useRoute} from 'vue-router';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
/** 博物馆照片 列表 */
defineOptions({ name: 'Photos' })
const {query} = useRoute() // 查询参数
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  id: undefined ,
  pageNo: 1,
  pageSize: 10,
  groupId: query.groupId,
  photoUrl: undefined,
  createdAt: undefined,
  createTime: []
})
const zuid =ref( queryParams.groupId)

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const selectedPhotos = ref<any[]>([]) // 选中的照片

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PhotosApi.getPhotosPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  console.log('id',id)
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PhotosApi.deletePhotos(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 处理选中变化 */
const handleSelectionChange = (selection: any[]) => {
  selectedPhotos.value = selection
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true

    if (selectedPhotos.value.length === 0) {
      message.warning('请选择要导出的照片')
      return
    }

    const zip = new JSZip();
    const promises = selectedPhotos.value.map(async (photo) => {
      const response = await fetch(photo.photoUrl);
      const blob = await response.blob();
      zip.file(`${photo.id}.jpg`, blob);
    });

    await Promise.all(promises);

    const content = await zip.generateAsync({ type: 'blob' });
    saveAs(content, '选中的照片.zip');
  } catch {
    message.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}
/** 下载图片 */
const handleDownload = async (photoUrl: string) => {
  try {
    const response = await fetch(photoUrl)
    const blob = await response.blob()
    saveAs(blob, '照片.jpg')
  } catch {
    message.error('下载失败')
  }
}

/** 初始化 **/
onMounted(() => {
  getList()

})


</script>


<style scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>
