<script setup name="ProjectManageList">
import { getCurrentInstance, reactive, ref, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import QueryForm from './QueryForm.vue'
import ProjectEditDialog from './ProjectEditDialog.vue'
import DownloadPluginDialog from './DownloadPluginDialog.vue'
import ExportDialog from './ExportDialog.vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const emit = defineEmits(['page'])
const { proxy } = getCurrentInstance()

function onReset(formQuery) {
  console.log('onReset')
  formQuery.resetFields()
  handleQuery()
}
function onQuery() {
  handleQuery()
}
// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 8,
    projectName: '',
    remark: ''
   
  }
})
// 表格数据
const { queryParams } = toRefs(data)


const tableList = ref([
  {
    id: '1',
    projectName: '若依配测系统1',
    datasource: 'MySQL', 
    domain: '电商',
    findRule: '自动发现'
  },
  {
    id: '2',
    projectName: '若依配测系统2',
    datasource: 'Oracle',
    domain: '金融',
    findRule: '手动配置'
  },
  {
    id: '3',
    projectName: '若依配测系统3',
    datasource: 'SQL Server',
    domain: '医疗',
    findRule: '规则匹配'
  }
])

const total = ref(3)
const loading = ref(false)
// 查询列表
function getList() {
  loading.value = true


  setTimeout(() => {
      loading.value = false
  }, 3000);

}


// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref('add')
const currentProject = ref(null)

// 显示新增对话框
const showAddDialog = () => {
  dialogMode.value = 'add'
  currentProject.value = null
  dialogVisible.value = true
}

// 处理项目操作
const handleCommandProject = (command, project) => {
  switch(command) {
    case '1': // 进入
      handleEnterProject(project)
      break
    case '2': // 编辑
      handleEditProject(project)
      break
    case '3': // 删除
      handleDeleteProject(project)
      break
    case '4': // 导入
      handleImportProject(project)
      break
    case '5': // 导出
      handleExportProject(project)
      break
    case '6': // 下载插件
      handleDownloadPlugin(project)
      break
    default:
      console.warn('未知命令:', command)
  }
}

// 具体操作方法
const handleEnterProject = (project) => {
  console.log('进入项目:', project)
  // // ElMessage.success(`进入项目 ${project.projectName}`)
  //   emit('page', 'detail', { projectId: project.id})
  router.push({ path:'/project',query: { projectId: project.id } })


}

const handleEditProject = (project) => {
  dialogMode.value = 'edit'
  currentProject.value = { ...project }
  dialogVisible.value = true
}


// 删除项目
const handleDeleteProject = (project) => {

}

// 导入项目
const handleImportProject = (project) => {
  ElMessage.info('导入功能待实现')
}
// 导出项目
const handleExportProject = (project) => {
  // ElMessage.success(`开始导出项目 "${project.projectName}"`)
  openExportDialog(project)
}
// 下载插件
const handleDownloadPlugin = (project) => {
  // ElMessage.success(`开始下载 "${project.projectName}" 的插件`)
  currentProjectId.value = project.id // 假设项目对象中有id字段
  downloadDialogVisible.value = true
  console.log(123)
}
// 处理确认操作
const handleDownloadConfirm = (data) => {
  console.log('确认下载插件:', data)
  // 这里可以处理保存操作或调用API
}
// 提交表单
const handleSubmit = (formData) => {
  if (dialogMode.value === 'add') {
    // 模拟新增
    const newProject = {
      id: tableList.value.length + 1,
      projectName: formData.projectName,
      datasource: '待配置',
      domain: '待配置',
      findRule: '待配置'
    }
    tableList.value.push(newProject)
    total.value++
    ElMessage.success('新增项目成功')
  } else {
    // 模拟编辑
    const index = tableList.value.findIndex(p => p.id === currentProject.value.id)
    if (index !== -1) {
      tableList.value[index].projectName = formData.projectName
      ElMessage.success('编辑项目成功')
    }
  }
}


const downloadDialogVisible = ref(false)
const currentProjectId = ref('')





const exportDialogVisible = ref(false)
const currentExportProjectId = ref('')

// 打开导出弹窗
const openExportDialog = (project) => {
  currentExportProjectId.value = project.id
  exportDialogVisible.value = true
}

// 处理导出确认
const handleExportConfirm = (data) => {
  console.log('导出数据:', data)

}

// 处理加密规则备份
const handleBackup = (projectId) => {
  console.log('备份项目:', projectId)

}

</script>

<template>
  <div class="app-container scroller">
    <PageTitle @back="$emit('page', 'list')">
      <template #title>
        项目管理
      </template>
      <template #buttons>
        <el-button
          type="primary"
          icon="Plus"
          @click="showAddDialog"
        > 
          新增
        </el-button>
      </template>
    </PageTitle>
    
    <div class="app-container__body">
      <div>
        <query-form
          ref="QueryFormRef"
          v-model="queryParams"
          @query="onQuery"
          @reset="onReset"/>
        <el-row :gutter="20">
          <el-col class="table-item" :span="6" v-for="(item, index) in tableList" :key="index">
            <el-card shadow="always"> 
              <template #header>
                <div class="flex-container justify-between align-center">
                  {{ item.projectName }}
                  <el-dropdown placement="bottom-end" @command="(command) => handleCommandProject(command, item)">
                    <el-button type="primary" icon="Operation">
                      操作
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="1">进入</el-dropdown-item>
                        <el-dropdown-item command="2">编辑</el-dropdown-item>
                        <el-dropdown-item command="3">删除</el-dropdown-item>
                        <el-dropdown-item command="4">导入</el-dropdown-item>
                        <el-dropdown-item command="5">导出</el-dropdown-item>
                        <el-dropdown-item command="6">下载插件</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
              
              <div class="item-content flex-container align-center">
                <div class="label">数据源：</div>
                <div class="value flex1">{{ item.datasource }}</div>
              </div>
              <div class="item-content flex-container align-center">
                <div class="label">数据域：</div>
                <div class="value flex1">{{ item.domain }}</div>
              </div>
              <div class="item-content flex-container align-center">
                <div class="label">发现规则：</div>
                <div class="value flex1">{{ item.findRule }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
          
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <ProjectEditDialog
      v-model:visible="dialogVisible"
      :mode="dialogMode"
      :project-data="currentProject"
      @submit="handleSubmit"
    />

    <DownloadPluginDialog
      v-model:visible="downloadDialogVisible"
      :project-id="currentProjectId"
      @confirm="handleDownloadConfirm"
    />

    <ExportDialog
      v-model:visible="exportDialogVisible"
      :project-id="currentExportProjectId"
      @confirm="handleExportConfirm"
      @backup="handleBackup"
    />
  </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;
}
</style>