<script setup name="ProjectManageList">
import { getCurrentInstance, reactive, ref, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { useRouter } from 'vue-router'
import useAppStore from '@/store/modules/app'
import usePermissionStore from '@/store/modules/permission'
import { changeRoute } from '@/utils/switchRoute'

import QueryForm from './QueryForm.vue'
import AddDiscoveryDialog from './modules/AddDiscoveryDialog.vue' // 引入新增发现任务弹窗
import SmartDiscoveryDialog from './modules/SmartDiscoveryDialog.vue'

const appStore = useAppStore()
const permissionStore = usePermissionStore()
const router = useRouter()
const emit = defineEmits(['page'])
const { proxy } = getCurrentInstance()

// 新增发现任务弹窗引用
const addDiscoveryDialogRef = ref()

function onReset(formQuery) {
  console.log('onReset')
  formQuery.resetFields()
  handleQuery()
}

function onQuery() {
  handleQuery()
}

// 搜索按钮操作
function handleQuery() {
  console.log('queryParams',queryParams.value)
  queryParams.value.pageNum = 1
  getList()
}
// 表格数据
const tableData = ref([
  {
    id: 1,
    taskName: '22',
    result: '0/225',
    dbType: 'MYSQL',
    operator: 'admin',
    createTime: '2025-08-21 16:55:30',
    updateTime: '2025-08-21 16:55:30',
    remark: '',
    projectid: "ec132fb8-04f0-4c0f-8460-c2a0ac4015d5",
    resultid: "R_1755845361051",
    datasystemid: "ff80818198986db40198c5933e5902e7",
  },
  {
    id: 2,
    taskName: '小王',
    result: '2/225',
    dbType: 'MYSQL',
    operator: 'admin',
    createTime: '2025-08-21 16:55:30',
    updateTime: '2025-08-21 16:55:30',
    remark: ''
  }
])
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 8
  }
})

// 表格数据
const { queryParams } = toRefs(data)
const total = ref(3)
const loading = ref(false)

// 查询列表
function getList() {
  loading.value = true
  setTimeout(() => {
      loading.value = false
  }, 3000)
}

function pageProjectManage() {
  changeRoute()

  router.push({
    path: '/project/Project'
  })
}

/**
 * 新增发现任务
 */
function handleAdd(){
console.log('新增发现任务')
  addDiscoveryDialogRef.value.openDialog()
}
// 操作处理函数
const handleEdit = (row) => {
  console.log('编辑:', row)
  addDiscoveryDialogRef.value.openDialog(row) 
  ElMessage.info(`编辑任务: ${row.taskName}`)
}

const handleDiscover = (row) => {
  console.log('发现:', row)
  ElMessage.success(`开始发现任务: ${row.taskName}`)
    emit('page', 'discoverProcess', { discoverProcessData: row})
  // router.push({
  //   path: '/user/discoverProcess',
  //   query: {
  //     taskid: row.id,
  //     resultid: row.resultid,
  //     datasystemid: row.datasystemid,
  //     discoverTaskName: row.tname,
  //     btnStatus: '1'
  //   }
  // })

}

const handleMonitor = (row) => {
  console.log('监控:', row)
  ElMessage.warning(`监控任务: ${row.taskName}`)
    emit('page', 'discoverProcess', { discoverProcessData: row})
}
const smartDiscoveryDialogRef = ref()
const smartData = ref(null)
const handleMoreCommand = (command, row) => {
  switch (command) {
    case 'smartDiscover':
      smartData.value = row
       handleSmartDiscover(row)
      ElMessage.info(`智能发现: ${row.taskName}`)
      break
    case 'viewHistory':
      ElMessage.info(`查看历史: ${row.taskName}`)
      break
    case 'viewResult':
      ElMessage.info(`查看结果: ${row.taskName}`)
        console.log('查看详细结果')
        emit('page','discoverResult')
      break
    case 'delete':
      ElMessage.error(`删除任务: ${row.taskName}`)
      break
  }
}

const smartDiscoveryDialogVisible = ref(false)
// 打开智能发现弹窗
const handleSmartDiscover = (row) => {
  // 可以传入特定的发现版本数据
  const discoveryData = [
    { version: row.resultid || '12123' } // 使用任务的结果ID或默认值
  ]
  
   // 优先使用ref方式
  if (smartDiscoveryDialogRef.value?.openDialog) {
    smartDiscoveryDialogRef.value.openDialog()
  } 
  // 备用：使用v-model方式
  else {
    smartDiscoveryDialogVisible.value = true
  }
}
const disCoverSmart = (val) => {
  console.log(val) 
   emit('page', 'discoverProcess', { discoverProcessData: smartData.value})
}

const handleAddEditConfirm = (submitData, isEditMode) =>{
  console.log('提交数据:', submitData)
  console.log('是否是编辑模式:', isEditMode)
  ElMessage.success(`${isEditMode ? '编辑' : '添加'}任务成功`)
}

</script>

<template>
  <div class="app-container scroller">
    <PageTitle :back="true" @back="pageProjectManage">
      <template #title>
        返回项目管理
      </template>
      <template #buttons>
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
        > 
          新增发现任务
        </el-button>
      </template>
    </PageTitle>
    
    <div class="app-container__body">
      <div>
        <query-form
          ref="QueryFormRef"
          v-model="queryParams"
          @query="onQuery"
          @reset="onReset"/>
    
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <!-- 发现任务名称列（左侧浮动） -->
          <el-table-column 
            prop="taskName" 
            label="发现任务名称" 
            min-width="180"
            align="left"
            fixed
          >
            <template #default="{ row }">
              <span class="task-name">{{ row.taskName }}</span>
            </template>
          </el-table-column>

          <!-- 梳理结果列 -->
          <el-table-column 
            prop="result" 
            label="梳理结果" 
            min-width="120"
          >
            <template #default="{ row }">
              <span class="result-text">{{ row.result }}</span>
            </template>
          </el-table-column>

          <!-- 数据库类型列 -->
          <el-table-column 
            prop="dbType" 
            label="数据库类型" 
            width="110"
          >
            <template #default="{ row }">
              <el-tag type="primary">{{ row.dbType }}</el-tag>
            </template>
          </el-table-column>

          <!-- 操作人列 -->
          <el-table-column 
            prop="operator" 
            label="操作人" 
            min-width="120"
          >
            <template #default="{ row }">
              <span>{{ row.operator }}</span>
            </template>
          </el-table-column>

          <!-- 创建时间列 -->
          <el-table-column 
            prop="createTime" 
            label="创建时间" 
            min-width="200"
          >
            <template #default="{ row }">
              <span class="time-text">{{ row.createTime }}</span>
            </template>
          </el-table-column>

          <!-- 修改时间列 -->
          <el-table-column 
            prop="updateTime" 
            label="修改时间" 
            min-width="200"
          >
            <template #default="{ row }">
              <span class="time-text">{{ row.updateTime }}</span>
            </template>
          </el-table-column>

          <!-- 备注列 -->
          <el-table-column 
            prop="remark" 
            label="备注" 
            width="120"
          >
            <template #default="{ row }">
              <span class="remark-text">{{ row.remark || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 操作列（右侧浮动） -->
          <el-table-column 
            label="操作" 
            width="320"
            fixed="right"
            align="center"
          >
            <template #default="{ row }">
              <div class="operation-buttons">
                <!-- 编辑按钮 -->
                <el-button 
                  link 
                  type="primary" 
                  size="small" 
                  @click="handleEdit(row)"
                  class="op-btn"
                >
                  编辑
                </el-button>

                <!-- 发现按钮 -->
                <el-button 
                  link 
                  type="success" 
                  size="small" 
                  @click="handleDiscover(row)"
                  class="op-btn"
                >
                  发现
                </el-button>

                <!-- 监控按钮 -->
                <el-button 
                  link 
                  type="warning" 
                  size="small" 
                  @click="handleMonitor(row)"
                  class="op-btn"
                >
                  监控
                </el-button>

                <!-- 更多操作下拉菜单 -->
                <el-dropdown 
                  @command="(command) => handleMoreCommand(command, row)"
                  trigger="click"
                >
                  <el-button 
                    link 
                    type="info" 
                    size="small"
                    class="more-btn"
                  >
                    更多
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="smartDiscover">
                        <span class="dropdown-item smart-discover">智能发现</span>
                      </el-dropdown-item>
                      <el-dropdown-item command="viewHistory">
                        <span class="dropdown-item">查看历史</span>
                      </el-dropdown-item>
                      <el-dropdown-item command="viewResult">
                        <span class="dropdown-item">查看结果</span>
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        <span class="dropdown-item delete-item">删除</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </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"
        />
      </div>
    </div>
    
    <!-- 新增/编辑发现任务弹窗 -->
    <AddDiscoveryDialog ref="addDiscoveryDialogRef" @confirm="handleAddEditConfirm" />
    <SmartDiscoveryDialog
      v-model="smartDiscoveryDialogVisible"
      ref="smartDiscoveryDialogRef"
      @discover="disCoverSmart"
    />

  </div>
</template>

<style lang="scss" scoped>
.table-item {
  margin-top: var(--container-pd);
  margin-bottom: 20px;
}

.item-content {
  margin: 8px 0;
  .label {
    width: 80px;
    color: #888;
  }
}

.flex-container { 
  display: flex;
}

.align-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.flex1 {
  flex: 1;
}
.flex-wrap {
  flex-direction: wrap;
}

.discovery-table-container {
  width: 100%;
  background: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  :deep(.el-table) {
    .el-table__header-wrapper {
      th {
        background: #f0f7ff !important;
        font-weight: 600;
      }
    }
    
    .el-table__body-wrapper {
      .el-table__row {
        &:nth-child(even) {
          background-color: #fafafa;
        }
        
        &:hover {
          background-color: #f5f7fa !important;
        }
      }
    }
  }
}

.task-name {
  font-weight: 500;
  color: #303133;
}

.result-text {
  color: #e6a23c;
  font-weight: 500;
}

.time-text {
  color: #909399;
  font-size: 12px;
}

.remark-text {
  color: #909399;
  font-style: italic;
}

.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  
  .op-btn {
    padding: 4px 8px;
    font-size: 12px;
    min-height: auto;
    
    &:hover {
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }
  
  .more-btn {
    padding: 4px 8px;
    font-size: 12px;
    min-height: auto;
    
    &:hover {
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }
}

.dropdown-item {
  font-size: 12px;
  padding: 4px 0;
  
  &.smart-discover {
    color: #67c23a;
    font-weight: 500;
  }
  
  &.delete-item {
    color: #f56c6c;
  }
}

:deep(.el-dropdown-menu__item) {
  padding: 8px 16px;
  
  &:hover {
    background-color: #f5f7fa;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .discovery-table-container {
    overflow-x: auto;
    
    :deep(.el-table) {
      min-width: 1000px;
    }
  }
  
  .operation-buttons {
    flex-wrap: wrap;
    gap: 2px;
    
    .op-btn, .more-btn {
      padding: 2px 4px;
      font-size: 11px;
    }
  }
}
</style>