<template>
  <el-dialog v-model="visible" top="5vh" title="图片模型" width="80%" class="custom-dialog">
    <el-form :model="form" label-width="auto" style="max-width: 100%" inline>
      <!-- 第一行 -->
      <el-row :gutter="1">
        <!-- 文件ID -->
        <el-col :span="6">
          <el-form-item label="文件ID">
            <el-input v-model="form.fileId" style="width: 100%" />
          </el-form-item>
        </el-col>

        <!-- 文件名称 -->
        <el-col :span="6">
          <el-form-item label="文件名称">
            <el-input v-model="form.fileName" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <!-- 创建时间 -->
        <el-col :span="10">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="form.fileDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              size="default"
            />
            <!-- END -->
          </el-form-item>
        </el-col>

        <el-col :span="11">
          <el-button type="primary" @click="checkFileList">查询</el-button>
          <el-button type="info" @click="resetForm">重置</el-button>
        </el-col>

        <!-- 按钮 -->
        <el-col :span="3" v-if="isUpload">
          <!-- <el-form-item>
              <el-button type="success">上传</el-button>
            </el-form-item> -->

          <el-upload
            accept="image/*"
            :action="BASE_URL + '/fileStorage/saveFile'"
            :on-success="saveImageSuccess"
            :show-file-list="false"
            style="width: 100%; padding: 0 10px"
          >
            <el-button type="success">上传图片</el-button>
          </el-upload>
        </el-col>
      </el-row>
    </el-form>

    <el-table v-loading="elDialogLoading" :data="tableData" style="width: 100%; height: 395px">
      <el-table-column prop="id" label="文件ID" />
      <el-table-column prop="date" label="添加时间" />
      <el-table-column prop="name" label="文件名称" />
      <el-table-column prop="imgUrl" label="文件" width="180">
        <template #default="scope">
          <el-image
            style="width: 65px; height: 65px"
            :src="scope.row.imgUrl"
            :preview-src-list="[]"
            fit="cover"
            @click="showPreview(scope.row.imgUrl)"
          />
        </template>
      </el-table-column>

      <el-table-column v-if="isEdit || isDelete || isBinding" fixed="right" label="操作">
        <template #default="scope">
          <el-button
            v-if="isEdit"
            link
            type="primary"
            size="small"
            @click="transmitFileEditName(scope.row.name, scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-if="isDelete"
            link
            type="danger"
            size="small"
            @click="deleteFileById(scope.row.id)"
            >删除</el-button
          >
          <el-button
            v-if="isBinding"
            link
            type="success"
            size="small"
            @click="bindingImg(scope.row)"
            >绑定</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[4, 8, 12]"
        :pager-count="3"
        size="default"
        layout="total,sizes,-> ,prev, pager, next"
        :total="pageTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-dialog>

  <el-dialog v-model="elDialogLoading2" title="修改文件名称" width="500">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-input v-model="editFileName" />
      </el-col>
    </el-row>
    <br />

    <el-row :gutter="20">
      <el-col :span="20"></el-col>
      <el-col :span="4">
        <el-button type="primary" @click="fileEditName"> 提交 </el-button>
      </el-col>
    </el-row>
  </el-dialog>

  <!-- 独立的图片预览浮层 -->
  <el-image-viewer
    v-if="previewVisible"
    :url-list="[currentPreviewUrl]"
    :z-index="3000"
    @close="previewVisible = false"
  />
</template>

<script setup lang="ts">
import { reactive, computed, ref, onMounted } from 'vue';
import { modelApi, BASE_URL } from '@/utils/request';
import { ElDialog, ElButton, ElMessage } from 'element-plus';
import { formatFilePath, formatTimestamp } from '@/utils/dataFormatter';

const props = defineProps({
  dialogImageVisible: {
    type: Boolean,
    default: false
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  isDelete: {
    type: Boolean,
    default: false
  },
  isBinding: {
    type: Boolean,
    default: false
  },
  isUpload: {
    type: Boolean,
    default: false
  }
});

console.log('dialogImageVisible:', props.dialogImageVisible);

const emit = defineEmits(['updateDialogImageVisible', 'bindingImg']);

const bindingImg = (obj: any) => {
  emit('bindingImg', obj);
};

const visible = computed({
  get: () => props.dialogImageVisible,
  set: (val) => emit('updateDialogImageVisible', val)
});

const form = reactive({
  fileId: null,
  fileName: null,
  fileDate: null
});

// 预览相关状态
const previewVisible = ref(false);
const currentPreviewUrl = ref('');
let elDialogLoading = ref(false);
let elDialogLoading2 = ref(false);
let currentPage = ref(1);
let pageSize = ref(4);
let pageTotal = ref(0);
let editFileName = ref('');
let editFileId = ref('');
const tableData = ref<any[]>([]);

//修改文件名称
async function fileEditName() {
  let endJson = {
    id: editFileId.value,
    fileName: editFileName.value
  };
  const response = await modelApi.fileStorage_editFileNameById_post(endJson);
  response.code == 200
    ? ElMessage.success(response.data)
    : ElMessage.error(response.message + '，请联系管理员');
  loadFileList();

  //end
  elDialogLoading2.value = false;
  editFileName.value = '';
  editFileId.value = '';
}

// 删除文件
async function deleteFileById(fileId: string) {
  let endJson = {
    id: fileId
  };
  const response = await modelApi.fileStorage_deleteFileById_get(endJson);
  response.code == 200
    ? ElMessage.success(response.data)
    : ElMessage.error(response.message + '，请联系管理员');
  loadFileList();
}

function saveImageSuccess(response: any) {
  loadFileList();
  ElMessage({
    message: '文件存储成功',
    type: 'success'
  });
}

function checkFileList() {
  loadFileList();
}

function resetForm() {
  form.fileId = null;
  form.fileName = null;
  form.fileDate = null;
}

const handleSizeChange = (val: number) => {
  console.log('size点击:', `${val} items per page`);
  loadFileList();
};
const handleCurrentChange = (val: number) => {
  console.log('Current点击:', `current page: ${val}`);
  loadFileList();
};

//传递修改文件名称
function transmitFileEditName(fileName: string, fileId: string) {
  editFileName.value = fileName;
  editFileId.value = fileId;
  elDialogLoading2.value = true;
}

// 显示预览的方法
function showPreview(url: string) {
  currentPreviewUrl.value = url;
  previewVisible.value = true;
}

// 获取文件列表
async function loadFileList() {
  elDialogLoading.value = true;
  let endJson = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    id: form.fileId,
    fileName: form.fileName,
    startTime: form.fileDate ? new Date(form.fileDate[0]).getTime() : null,
    endTime: form.fileDate ? new Date(form.fileDate[1]).getTime() : null
  };
  console.log('endJson:', endJson);
  const response = await modelApi.fileStorage_file_list_post(endJson);
  tableData.value = [];
  if (!response.data) {
    elDialogLoading.value = false;
    return;
  }
  pageTotal.value = response.data.total;
  currentPage.value = response.data.current;
  pageSize.value = response.data.size;

  response.data.list.forEach((value: any) => {
    let date = formatTimestamp(value.addTime);
    let id = value.id;
    let name = value.fileName;
    let imgUrl = formatFilePath(BASE_URL, value.filePath);
    tableData.value.push({ date, id, name, imgUrl });
  });
  console.log('tableData:', tableData.value);
  elDialogLoading.value = false;
}
onMounted(() => {
  loadFileList();
});
</script>

<style scoped>
/* 为 el-dialog 添加边框 */
.custom-dialog {
  border: 2px solid #ffffff; /* 边框颜色和宽度 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  height: 620px;
}

/* 可选：调整对话框头部样式 */
.custom-dialog .el-dialog__header {
  background-color: #f5f7fa; /* 头部背景色 */
  border-bottom: 1px solid #e4e7ed; /* 头部分隔线 */
  padding: 15px 20px;
}

/* 可选：调整对话框内容区域样式 */
.custom-dialog .el-dialog__body {
  padding: 20px;
}
</style>
