<template>
  <div>
    <!-- 搜索区域 -->
    <el-form inline>
      <el-form-item>
        <el-input v-model="searchInfo" placeholder="搜索关键字" clearable style="width: 300px;" />
        
        <!-- 文件夹筛选下拉菜单 -->
        <el-dropdown @command="handleFolderCommand" style="margin-right: 10px;">
          <el-button  icon="search" title="文件夹筛选">
            {{ selectedFolder || '文件夹筛选' }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="">全部文件夹</el-dropdown-item>
              <el-dropdown-item v-for="(folder, index) in folderList" :key="index" :command="folder">
                {{ folder }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <el-button type="primary" icon="search" @click="onSubmit" title="搜索">查询</el-button>
        <el-button type="primary" title="选择图片,文生图" @click="texttoimg" :loading="isLoading">文生图</el-button>
        <el-button type="primary" title="选择图片,图生图" @click="imgtoimg" :loading="isLoading">图生图</el-button>
      </el-form-item>
    </el-form>

    <!-- 文生图弹窗 -->
    <el-dialog v-model="txtimgDialogVisible" title="文生图" width="660px" top="10%">
      <el-form label-width="100px">
         <!-- <el-form-item label="提示词" prop="chinese_description">
          <el-input 
            v-model="form.chinese_description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入文生图描述"
          />
        </el-form-item> -->
        <el-form-item label="文生图模型">
          <div style="display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
            <el-radio-group v-model="txtimgselectedModel" @change="handleModelChange">
              <el-radio 
                v-for="item in txttoimg_modelList" 
                :key="item.id"
                :label="item.txttoimg">
                {{ item.txttoimg }} 
                <span v-if="item.id === usedIds.wenshengtu" style="color: #67C23A; margin-left: 5px;">(默认使用)</span>
              </el-radio>
            </el-radio-group>
            <el-button type="success"  @click="setActive('wenshengtu')"  :disabled="!selectedIds.wenshengtu || selectedIds.wenshengtu === usedIds.wenshengtu">
              设为默认使用模型
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="txtimgDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateTxtImg" :loading="isGenerating">生成文生图</el-button>
      </template>
    </el-dialog>

    <!-- 表格展示 -->
    <el-table
      ref="multipleTable"
      style="width: 100%; height: 62vh;"
      :row-style="{ height: '20px' }"
      :header-cell-style="{ padding: '0px' }"
      :cell-style="{ padding: '0px' }"
      :header-row-style="{ height: '20px' }"
      border tooltip-effect="dark"
      :data="tableData1"
      row-key="ID"
      highlight-current-row
      :cell-class-name="tableDataCellClass"
      @selection-change="SelectionChange"
      @row-dblclick="onRowDblClick"
      :show-overflow-tooltip="true"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" prop="id" width="70" />
      <el-table-column label="第一段" prop="chinese_description" width="300" />
      <el-table-column label="第二段" prop="english_description" width="300" />
      <el-table-column label="图片名称" prop="img_name" width="300" />
      <el-table-column label="原图" width="120">
        <template #default="{ row }">
          <el-image
            :src="formatImageUrl(row.old_image_url)"
            :preview-src-list="[formatImageUrl(row.old_image_url)]"
            style="width: 90px; height: 70px;"
            fit="contain"
            preview-teleported
          />
        </template>
      </el-table-column>
	  
	  
	  <el-table-column
	    v-if="tableData1.some(row => row.model === 'black-forest-labs/FLUX.1-kontext-pro')" 
	    label="FLUX.1" 
	    width="120">
	    <template #default="{ row }">
	      <el-image
	        v-if="row.model === 'black-forest-labs/FLUX.1-kontext-pro'"
	        :src="formatImageUrl(row.new_image_url)"
	        :preview-src-list="[formatImageUrl(row.new_image_url)]"
	        style="width: 90px; height: 70px;"
	        fit="contain"
	        preview-teleported
	      />
	      <span v-else>-</span>
	    </template>
	  </el-table-column>
	  <el-table-column
	    v-if="tableData1.some(row => row.model === 'dall-e-3')" 
	    label="dall-e-3" 
	    width="120">
	    <template #default="{ row }">
	      <el-image
	        v-if="row.model === 'dall-e-3'"
	        :src="formatImageUrl(row.new_image_url)"
	        :preview-src-list="[formatImageUrl(row.new_image_url)]"
	        style="width: 90px; height: 70px;"
	        fit="contain"
	        preview-teleported
	      />
	      <span v-else>-</span>
	    </template>
	  </el-table-column>
	  <el-table-column 
	    v-if="tableData1.some(row => row.model === 'gpt-image-1')" 
	    label="gpt-image-1" 
	    width="120">
	    <template #default="{ row }">
	      <el-image
	        v-if="row.model === 'gpt-image-1'"
	        :src="formatImageUrl(row.new_image_url)"
	        :preview-src-list="[formatImageUrl(row.new_image_url)]"
	        style="width: 90px; height: 70px;"
	        fit="contain"
	        preview-teleported
	      />
	      <span v-else>-</span>
	    </template>
	  </el-table-column>
	  <el-table-column
	    v-if="tableData1.some(row => row.model === 'MID_JOURNEY')" 
	    label="MID_JOURNEY" 
	    width="130">
	    <template #default="{ row }">
	      <el-image
	        v-if="row.model === 'MID_JOURNEY'"
	        :src="`https://chatapi.onechats.ai/mj/image/${row.taskId}`"  
	        :preview-src-list="[`https://chatapi.onechats.ai/mj/image/${row.taskId}`]"
	        style="width: 90px; height: 70px;"
	        fit="contain"
	        preview-teleported
	      />
	      <span v-else>-</span>
	    </template>
	  </el-table-column>
      
      <el-table-column label="图生图预览" width="120">
        <template #default="{ row }">
          <el-image
            :src="formatImageUrl(row.imgtoimg_url)"
            :preview-src-list="[formatImageUrl(row.imgtoimg_url)]"
            style="width: 90px; height: 70px;"
            fit="contain"
            preview-teleported
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="gva-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 30, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <el-dialog 
      v-model="editDialogVisible" 
      title="查看信息" 
      style="width: 70%; height: 80%;top: -6%;" 
      :modal="true">
      <el-scrollbar style="max-height: 60vh; overflow-y: auto;">
        <el-form :model="editFormData">
          <el-form-item label="ID" label-width="80px">
            <el-input v-model="editFormData.id" disabled />
          </el-form-item>
    
          <el-form-item label="文生图路径">
            <el-input v-model="editFormData.new_image_url" disabled />
          </el-form-item>
    
          <el-form-item label="图生图路径">
            <el-input v-model="editFormData.imgtoimg_url" disabled />
          </el-form-item>
    
          <el-form-item label="第一段">
            <el-input
              type="textarea"
              v-model="editFormData.chinese_description"
              :rows="6"
            />
          </el-form-item>
    
          <el-form-item label="第二段">
            <el-input
              type="textarea"
              v-model="editFormData.english_description"
              :rows="6"
            />
          </el-form-item>
    
          <el-form-item label="图片名称">
            <el-input v-model="editFormData.img_name" />
          </el-form-item>
        </el-form>
      </el-scrollbar>
    
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog v-model="dialogVisible" title="图片预览" width="70%" top="5vh" destroy-on-close>
      <div style="text-align: center;">
        <el-image :src="currentImageUrl" style="max-width: 100%; max-height: 70vh;" fit="contain" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRaw, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getTable, imageToText, Template_ids,txttoimg_moxing,GetHttpUrl,txttoimg_update, getSide } from '@/api/mes/job'
import { useUserStore } from '@/pinia/modules/user'
import { ArrowDown } from '@element-plus/icons-vue'

//获取登录用户信息
const userStore = useUserStore()
const _username = ref('')
_username.value = userStore.userInfo.userName + '/' + userStore.userInfo.nickName
console.log('获取用户信息',_username.value)
console.log('获取用户名称',userStore.userInfo.nickName)

//获取服务器地址
const baseUrl = ref('')
const port = ref('')
const full_url = ref('')
// 从接口获取服务器地址
const fetchServerUrl = async () => {
  try {
    const res = await GetHttpUrl()
    if (res.code === 0 && res.data && res.data.full_url) {
      full_url.value = res.data.full_url
      baseUrl.value = res.data.baseUrl
      port.value = res.data.port
	  console.log('获取服务器地址',full_url.value)
	  console.log('IP地址',baseUrl.value)
	  console.log('端口',port.value)
    }
  } catch (error) {
    console.error('获取服务器地址失败:', error)
  }
}
fetchServerUrl();

const searchInfo = ref('')
const tableData1 = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(50)
const dialogVisible = ref(false)
const currentImageUrl = ref('')
const width = ref('')
const height = ref('')
const isLoading = ref(false)
const txttotxt_selectedOption = ref('gemini-2.0-flash')
const selectedOption = ref('dall-e-3')
const num = ref(1)
const _parh = ref([])
const folderList = ref([])
const selectedFolder = ref('')

const editDialogVisible = ref(false)
const editFormData = reactive({
  id: '',
  chinese_description: '',
  english_description: '',
  new_image_url: '',
  imgtoimg_url: '',
  img_name: ''
})

// 定义文生图表单对象
const form = reactive({
  chinese_description: ''
})

const formatImageUrl = (path) => {
  if (!path) return ''
  return `${full_url.value}/${path.replace(/^public\//, '')}`
}

const txttoimg_modelList = ref([]); // 存储所有模型数据
const txtimgselectedModel = ref(''); // 当前选中的模型名称
const usedId = ref(null); // 当前使用的模型ID（兼容旧代码）
const selectedId = ref(null); // 用户选择的模型ID（兼容旧代码）
const txtimgDialogVisible = ref(false); // 文生图弹窗可见性
const isGenerating = ref(false); // 文生图生成中状态
const usedIds = ref({}); // 当前使用的模型ID集合
const selectedIds = ref({}); // 用户选择的模型ID集合

// 获取文生图模型列表
const fetchTxtImgModels = async () => {
  try {
    const response = await txttoimg_moxing();
    txttoimg_modelList.value = response.data.models.wenshengtu;
    // 获取当前使用的模型ID
    usedIds.value = response.data.used_ids;
    const currentUsedId = usedIds.value.wenshengtu;
    
    // 设置默认选中的模型
    const defaultModel = txttoimg_modelList.value.find(item => item.id === currentUsedId);
    if (defaultModel) {
      txtimgselectedModel.value = defaultModel.txttoimg;
      usedId.value = defaultModel.id;
      selectedId.value = defaultModel.id; 
      selectedIds.value.wenshengtu = defaultModel.id;
      selectedOption.value = defaultModel.txttoimg;
    }
    
    console.log('文生图模型列表:', txttoimg_modelList.value);
    console.log('当前使用的模型ID:', currentUsedId);
    console.log('默认选中的模型:', defaultModel);
  } catch (error) {
    console.error('获取文生图模型列表失败:', error);
    ElMessage.error('获取模型列表失败');
  }
}
fetchTxtImgModels();

const getTableData = async () => {
    const res = await getTable({
      search: searchInfo.value,
      limit: pageSize.value,
      page: page.value,
      folder: selectedFolder.value
    })
    tableData1.value = res.data.list
    total.value = res.data.total
    
    // 更新文件夹列表
    if (res.data.folder) {
      folderList.value = res.data.folder
    }

    // const res_Template = await Template_ids({path:row['old_image_url']});
    // height.value = res_Template.data.height
    // width.value = res_Template.data.width
}


// 当选择模型变化时
const handleModelChange = (modelName) => {
  const model = txttoimg_modelList.value.find(item => item.txttoimg === modelName);
  if (model) {
    selectedId.value = model.id;
    selectedIds.value.wenshengtu = model.id;
    selectedOption.value = model.txttoimg;
    console.log('选择的模型ID:', model.id);
  }
}
// 设置默认模型
const setActive = async (type) => {
  const id = selectedIds.value[type]
  if (id) {
    try {
      // 调用API设置默认模型
      const res = await txttoimg_update({ id: id,type:"wenshengtu"})
      if (res.code === 0) {
        usedIds.value[type] = id
        ElMessage.success('默认模型设置成功')
      } else {
        ElMessage.error(res.msg || '设置默认模型失败')
      }
    } catch (error) {
      console.error('设置默认模型失败', error)
      ElMessage.error('设置默认模型失败')
    }
  }
}


// 处理文件夹选择
const handleFolderCommand = (command) => {
  selectedFolder.value = command
  onSubmit()
}

const onSubmit = () => {
  page.value = 1
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  page.value = 1
  getTableData()
}

const SelectionChange = (rows) => {
  _parh.value = rows.map(item => item.old_image_url)
}


// 文生图生成函数
const generateTxtImg = () => {
  txtimgDialogVisible.value = false
  processImages(toRaw(_parh.value), '文生图', form.chinese_description)
}

const texttoimg = async () => {
  if (_parh.value.length === 0) {
    ElMessage.warning('请先选择要处理的图片')
    return
  }
  // 获取模型列表
  await fetchTxtImgModels()
  // 显示弹窗
  txtimgDialogVisible.value = true
}

const imgtoimg = () => {
  processImages(toRaw(_parh.value), '图生图')
}

// 是否执行几何图（默认不执行）
const executeKeywords = ref(false)

const processImages = async (files, type, prompt = '') => {
  if (!Array.isArray(files) || files.length === 0) {
    ElMessage.warning('请选择要处理的图片')
    return
  }

  const pathGroups = {}
  _parh.value.forEach(path => {
    const dir = path.replace(/\/[^\/]*$/, '')
    if (!pathGroups[dir]) pathGroups[dir] = []
    pathGroups[dir].push(path)
  })

  isLoading.value = true
  const failList = []

  for (const [dir, images] of Object.entries(pathGroups)) {
    const payload = {
      old_image_file: dir,
      type,
      selectedOption: selectedOption.value,
      txttotxt_selectedOption: txttotxt_selectedOption.value,
      batch: images,
      num: num.value,
      width: width.value,
      height: height.value,
      executeKeywords:executeKeywords.value,
    }

    // console.log(payload);
    // await new Promise(resolve => setTimeout(resolve, 2000));
    // isLoading.value = false;
    // return;

    try {
      await imageToText(payload)
      ElMessage.success(`处理目录：${dir}，共 ${images.length} 张 * ${num.value} 次`)
    } catch (e) {
      console.warn('处理失败:', dir, e)
      images.forEach((_, i) => failList.push(`目录 ${dir} 第 ${i + 1} 张`))
    }
  }

  if (failList.length > 0) {
    ElMessage.warning('部分图片处理失败，请查看控制台')
  }

  await new Promise(resolve => setTimeout(resolve, 3000))
  isLoading.value = false
}

const previewImage = (url) => {
  currentImageUrl.value = url
  dialogVisible.value = true
}

const onRowDblClick = (row) => {
  editFormData.id = row.id
  editFormData.chinese_description = row.chinese_description
  editFormData.english_description = row.english_description
  editFormData.img_name = row.img_name
  editFormData.new_image_url = row.new_image_url
  editFormData.imgtoimg_url = row.imgtoimg_url
  editDialogVisible.value = true
}

const submitEdit = async () => {
  try {
    const { id, chinese_description, english_description, img_name } = editFormData;

    const payload = {
      id,
      chinese_description,
      english_description,
      img_name
    };

    await getSide(payload);
    ElMessage.success('修改成功');
    editDialogVisible.value = false;
    getTableData();
  } catch (error) {
    console.error('修改失败：', error);
    ElMessage.error('修改失败，请稍后重试');
  }
};

onMounted(() => {
  getTableData()
})
</script>

<style scoped>
:deep(.el-table td .cell) {
  line-height: 22px !important;
}
:deep(.el-dialog__body) {
  padding: 10px 20px;
}
.gva-pagination {
  margin-top: 10px;
  text-align: right;
}
:deep(.el-table__body tr.current-row) > td {
  background: #ff80ff !important;
}
</style>