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

import { useRouter,useRoute } 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'
import find from '@/assets/images/find.png'
import jiankong from '@/assets/images/jiankong.png'
import findResult from '@/assets/images/findResult.png'
import { 
  queryDiscoverList,
  delDiscoverTask,
  executetask,
  initExecute
} from '@/api/discover/index'

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

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

onMounted(()=>{
  handleQuery()
})

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

function onQuery() {
  handleQuery()
}

// 搜索按钮操作
function handleQuery() {
  console.log('queryParams',queryParams.value)
  queryParams.value.pageno = 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: {
    pageno: 1,
    pagesize: 10,
    project: sessionStorage.getItem('projectName') || '',
    projectid: sessionStorage.getItem('projectId') || ''
  }
})

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

// 查询列表
function getList() {
  loading.value = true
  queryDiscoverList(queryParams.value).then(res=>{
    console.log(res)
    if(res.flag){
      tableData.value = res.data.list.map(item => ({
        ...item,
          id: item.id,
          taskName: item.tname,
          result: item.countResult,
          dbType: item.dbtype,
          operator: item.username,
          createTime: item.createtime,
          updateTime: item.updatetime,
          remark: item.note
      }))
      loading.value = false
    }else{
      tableData.value = []
      loading.value = false
      ElMessage.error(res.msg)
    }
  }).catch((err) => {
    tableData.value = []
    loading.value = false
    console.log(err)
  })
}

function pageProjectManage() {
  changeRoute()

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

/**
 * 新增发现任务
 */
function handleAdd(){
  console.log('新增发现任务')
  console.log(route)

  appStore.setQueryData({
    icon: route.meta.icon,
    type: 'add'
  });



  emit('page', 'addEditDiscovery', { listItem: null, addEditType: 'add'})
}
// 操作处理函数
const handleEdit = (row) => {
  console.log('编辑:', row)


  appStore.setQueryData({
    type: 'edit',
    data: JSON.stringify(row),
    icon: route.meta.icon,
    breadPathData: [
      {
        path: route.path,
        label: route.meta.title
      },
      {
        label: "发现配置"
      }
    ]
  });
  emit('page', 'addEditDiscovery', { listItem: row, addEditType: 'edit'})

}

const handleDiscover = (row) => {
  console.log('发现:', row)


    ElMessageBox.confirm('确认执行发现任务吗？'+ `[${row.taskName}]`, '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        executetask({
          taskid: row.id,
          version: '',
          datasystemid: row.datasystemid,
          taskname: row.tname,
          projectid: sessionStorage.getItem('projectId'),
          project: sessionStorage.getItem('projectName')
        }).then(res => { 
          if(res.flag){
            appStore.setQueryData({
              taskid: row.id,
              btnStatus: '1',
              resultid: row.resultid,
              datasystemid: row.datasystemid,
              discoverTaskName: row.tname,
              icon: route.meta.icon,
              breadPathData: [
                {
                  path: route.path,
                  label: route.meta.title
                },
                {
                  label: "发现进度"
                }
              ]
            });
            emit('page', 'discoverProcess', { listItem: row})
          }else{
            ElMessage.error(res.msg)
          }
        })
      })
}
/**
 * 监控
 * @param row 
 */
const handleMonitor = (row) => {
  appStore.setQueryData({
    taskid: row.id,
    btnStatus: row.taskstatus,
    resultid: row.resultid,
    datasystemid: row.datasystemid,
    discoverTaskName: row.tname,
    icon: route.meta.icon,
    breadPathData: [
      {
        path: route.path,
        label: route.meta.title
      },
      {
        label: "发现进度"
      }
    ]
  });
  emit('page', 'discoverProcess', { listItem: row})

}
const smartDiscoveryDialogRef = ref()
const smartData = ref(null)
const handleMoreCommand = (command, row) => {
  switch (command) {
    case 'smartDiscover':
      smartData.value = row
       handleSmartDiscover(row)
      break
    case 'viewHistory':

      ElMessage.info(`查看历史: ${row.taskName}`)
      emit('page','discoverHistory',{listItem:row})
      
      break
    case 'viewResult':
      appStore.setQueryData({
        taskid: row.id,
        resultid: row.resultid,
        datasystemid: row.datasystemid,
        discoverTaskName: row.tname,
        icon: route.meta.icon,
        breadPathData: [
          {
            path: route.path,
            label: route.meta.title
          },
          {
            label: "查看结果"
          }
        ]
      });

        emit('page','discoverResult',{ listItem: null,type: 'list'})
      break
    case 'delete':

      ElMessageBox.confirm('删除后无法恢复，是否确认删除？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        delDiscoverTask({
          dataSystemName: 'orcl202',
          taskid: row.id
        }).then(res => { 
          if(res.flag){
            ElMessage.success(res.msg)
            handleQuery()
          }else{
            ElMessage.error(res.msg)
          }
        })
      })

 
      break
  }
}

const smartDiscoveryDialogVisible = ref(false)

const AIDIscoverVersionListDialog = ref({
  status: false,
  cacheData: {},
  columnsData: [
    {
      title: '发现版本',
      key: 'name',
      align: 'left'
    },
    {
      title: "操作",
      slot: "action",
      key: "action",
      align: "center",
      width: 150
    }
  ],
  tableData: []
})
// 打开智能发现弹窗
const handleSmartDiscover = (row) => {
   ElMessage.info(`暂未开放`)
   return
initExecute({
  taskid: row.id, 
  projectid: sessionStorage.getItem('projectId')
}).then(res => {
  const {task_version, project_version, all_version} = res.data
  const allVersionList = [];
  AIDIscoverVersionListDialog.value.status = true
  AIDIscoverVersionListDialog.value.cacheData = row

  if (JSON.stringify(all_version) !== '{}') {
    allVersionList.push({
      ...project_version,
      version: all_version.versionname,
      type: 'all_version',
      versionname: `全局版本：${all_version.versionname}`
    })
  }

  if (JSON.stringify(project_version) !== '{}') {
    allVersionList.push({
      ...project_version,
      version: project_version.versionname,
      type: 'project_version',
      versionname: `项目版本：${project_version.versionname}`
    })
  }

  task_version.map(item => {
    item.version = item.versionname;
    item.type = item.filename;
    item.versionname = `任务版本：${item.versionname}`;
    allVersionList.push(item);
  })

  AIDIscoverVersionListDialog.value.tableData = allVersionList.map(item => {
    return {
      ...item,
      name: item.versionname,
      icon: [
        {
          ...appStore.tableButtonIcons.discover,
          key: 'action',
          name: 'handleDiscover',
          label: '智能发现',
        }
      ]
    }
  })
})
  
   // 优先使用ref方式
  if (smartDiscoveryDialogRef.value?.openDialog) {
    smartDiscoveryDialogRef.value.openDialog()
  } 
  // 备用：使用v-model方式
  else {
    smartDiscoveryDialogVisible.value = true
  }
}
const disCoverSmart = (val) => {
  console.log(val) 
   emit('page', 'discoverProcess', { listItem: smartData.value})
}

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

</script>

<template>
  <div class="app-container scroller">
    <PageTitle  backProject @handleBackProject="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"
          @add="handleAdd"/>
    
        <el-table
          :data="tableData"
          stripe
          style="width: 100%"
        >
        <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
            fixed
          />
          <!-- 发现任务名称列（左侧浮动） -->
          <el-table-column 
            prop="taskName" 
            label="发现任务名称" 
            min-width="180"
            align="left"
            fixed
          >
            <template #default="{ row }">
              <span>{{ row.taskName }}</span>
            </template>
          </el-table-column>

          <!-- 梳理结果列 -->
          <el-table-column 
            prop="result" 
            label="梳理结果" 
            min-width="120"
          >
            <template #default="{ row }">
              <span>{{ 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 >{{ row.createTime }}</span>
            </template>
          </el-table-column>

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

          <!-- 备注列 -->
          <el-table-column 
            prop="remark" 
            label="备注" 
            width="120"
          >
            <template #default="{ row }">
              <span>{{ 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="danger" 
                  size="small" 
                  icon="edit"
                  @click="handleEdit(row)"
                  class="op-btn"
                >
                  编辑
                </el-button>

                <!-- 发现按钮 -->
                <el-button 
                  link 
                  type="danger" 
                  size="small" 
                  @click="handleDiscover(row)"
                  class="op-btn"
                >
                 <img  :src="find" alt="" class="btn-logo"> 发现
                </el-button>

                <!-- 监控按钮 -->
                <el-button 
                  link 
                  type="danger" 
                  size="small" 
                  @click="handleMonitor(row)"
                  class="op-btn"
                >
                   <img  :src="jiankong" alt="" class="btn-logo">监控
                </el-button>

                <!-- 更多操作下拉菜单 -->
                <el-dropdown 
                  @command="(command) => handleMoreCommand(command, row)"
                  trigger="click"
                >
                  <el-button 
                    link 
                   type="danger" 
                    size="small"
                    class="more-btn"
                    icon="MoreFilled"
                  >
                  <!-- <el-icon><MoreFilled /></el-icon> -->
                    <!-- 更多
                    <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-button 
                          link 
                          type="danger" 
                          size="small" 
                          class="op-btn"
                        >
                          <img  :src="findResult" alt="" class="btn-logo">查看结果
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item command="delete">
                        <el-button 
                          link 
                          type="danger" 
                          size="small" 
                          class="op-btn"
                          icon="delete"
                        >
                        删除
                        </el-button>
                        <!-- <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.pageno"
          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;
}
.btn-logo {
  height: 10px;
  width: 10px;
}
.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-size: 14px;
  font-weight: 400;
  color: rgba(53, 64, 79, 1);
}

.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;
    }
  }
}
:deep(.el-button--danger){
  --el-button-text-color: rgba(33, 103, 217, 1);
  --el-button-hover-text-color: rgba(33, 103, 217, 1);
  --el-button-hover-bg-color: rgba(33, 103, 217, 1);
  --el-button-hover-border-color:rgba(33, 103, 217, 1);
  --el-button-hover-link-text-color:rgba(33, 103, 217, 1);
}
</style>