<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="80px">
      <el-form-item label="用戶ID" prop="username">
        <el-input
            v-model="queryParams.userId"
            placeholder="請輸入用戶ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所屬用戶" prop="username">
        <el-input
            v-model="queryParams.username"
            placeholder="請輸入所屬用戶"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜尋</el-button>
        <el-button icon="Refresh" @click="resetQuery">重設</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button 
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展開/折疊</el-button>
      </el-col>
    </el-row>
    <el-table 
      v-if="refreshTable"
      v-loading="loading" 
      :data="treeData" 
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      row-key="id"
      :default-expand-all="isExpandAll"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所屬用戶" prop="userName" width="200" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="row.isParent" class="parent-user-name">{{ row.userName || row.userId || '-' }}</span>
          <span v-else>{{ row.userName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用戶id" prop="userId" width="120" align="center"/>
      <el-table-column label="圖片" prop="url" width="120" align="center">
        <template #default="{ row }">
          <image-preview v-if="!row.isParent && row.url" :src="getImageUrl(row.url)" :width="80" :height="80"/>
          <span v-else-if="!row.isParent" style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="圖片時間" prop="createDate" align="center" />
      <el-table-column label="操作" align="center" width="140" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-tooltip content="查看" placement="top" v-if="!row.isParent">
            <el-button link type="primary" icon="View" @click.stop="handleView(row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form"  label-width="80px">
        <el-form-item label="用戶id" prop="userId">
          <el-input v-model="form.userId" placeholder="請輸入用戶id" />
        </el-form-item>
        <el-form-item label="所屬用戶" prop="userName">
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item label="圖片" prop="url">
          <image-preview v-if="form.url" :src="getImageUrl(form.url)" :width="100" :height="100"/>
<!--          <image-upload :limit="1" v-model="form.url"/>-->
        </el-form-item>
        <el-form-item label="圖片時間" prop="createDate">
          <el-input v-model="form.createDate" placeholder="請輸入圖片時間" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, getCurrentInstance, onMounted, nextTick} from 'vue'
import {getImagePageList} from '@/api/system/image.js'
import { isExternal } from '@/utils/validate'

// 获取文件路径前缀
const filePath = import.meta.env.VITE_APP_FILE_PATH || ''

const imageList = ref([])
const treeData = ref([])
const total = ref(0)
const title = ref("")
const open = ref(false)
const form = ref({})
const formRef = ref()
const loading = ref(true)
const queryFormRef = ref()
const isExpandAll = ref(false)
const refreshTable = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: null,
  userId:null,
})

// 将扁平数据转换为树形结构
const convertToTree = (data) => {
  if (!data || !Array.isArray(data)) {
    return []
  }
  const treeMap = new Map()
  const result = []
  
  // 先按userName和userId分组
  data.forEach(item => {
    const key = `${item.userName || ''}_${item.userId || ''}`
    if (!treeMap.has(key)) {
      treeMap.set(key, {
        id: `parent_${key}`,
        userName: item.userName || item.userId || '未知用户',
        userId: item.userId,
        isParent: true,
        children: []
      })
    }
    // 添加子节点
    treeMap.get(key).children.push({
      ...item,
      id: item.id || `child_${key}_${treeMap.get(key).children.length}`
    })
  })
  
  // 转换为数组
  treeMap.forEach(value => {
    result.push(value)
  })
  
  return result
}

// 获取完整的图片URL
const getImageUrl = (url) => {
  if (!url) return ''
  // 如果是外部链接，直接返回
  if (isExternal(url)) {
    return url
  }
  // 如果已经包含文件路径前缀，直接返回
  if (filePath && url.startsWith(filePath)) {
    return url
  }
  // 如果 filePath 是完整URL（以 http:// 或 https:// 开头），在前面加上文件路径前缀
  // 这样返回的URL会被 ImagePreview 组件识别为外部链接，不会再添加 VITE_APP_BASE_API
  if (filePath && isExternal(filePath)) {
    // 确保 filePath 以 / 结尾，url 不以 / 开头
    const normalizedFilePath = filePath.endsWith('/') ? filePath : filePath + '/'
    const normalizedUrl = url.startsWith('/') ? url.substring(1) : url
    return normalizedFilePath + normalizedUrl
  }
  // 如果 filePath 不是完整URL，直接返回原始URL，让 ImagePreview 组件自己处理
  // 因为 ImagePreview 会添加 VITE_APP_BASE_API
  return url
}

onMounted(()=>{
  getList()
})
// 表单重设
const reset = () => {
  form.value = {
    id: null,
    url: null,
    createDate: null,
    userId: null
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const getList = () => {
  loading.value = true
  const params = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    userName: queryParams.username,
    userId: queryParams.userId,
  }
  getImagePageList(params).then(response => {
    // 处理不同的API返回格式
    // response 可能是 { code: 200, msg: "操作成功", data: [...] } 或直接是数组
    let data = []
    let totalCount = 0
    
    if (Array.isArray(response)) {
      // 如果response直接是数组
      data = response
      totalCount = data.length
    } else if (Array.isArray(response.data)) {
      // 如果data是数组
      data = response.data
      totalCount = data.length
    } else if (response.data && Array.isArray(response.data.records)) {
      // 如果是分页格式 { records: [], total: ... }
      data = response.data.records
      totalCount = response.data.total || data.length
    }
    
    // 如果数据已经是树形结构（包含isParent和children），直接使用
    if (data.length > 0 && (data[0].isParent !== undefined || data[0].children !== undefined)) {
      treeData.value = data
      imageList.value = data.flatMap(item => item.children || [])
      total.value = totalCount
    } else {
      // 否则转换为树形结构
      imageList.value = data
      treeData.value = convertToTree(data)
      total.value = totalCount
    }
    loading.value = false
  }).catch((error) => {
    console.error('获取图片列表失败:', error)
    loading.value = false
  })
}

/** 查看按钮操作 */
const handleView = (row) => {
  reset()
  form.value = {...row}
  open.value = true
  title.value = "查看圖片資訊"
  nextTick(() => {
    if (formRef.value) formRef.value.clearValidate && formRef.value.clearValidate()
  })
}
// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}
</script>
<style scoped lang="scss">
.parent-user-name {
  color: #409EFF;
  font-weight: 500;
  font-size: 14px;
}
</style>