<script setup name="ProjectManageList">
import { getCurrentInstance, reactive, ref, toRefs,onMounted } 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'
import {changeRoute}  from '@/utils/switchRoute'
import {
  selectDataProject
} from '@/api/project'

import useAppStore from '@/store/modules/app'

const appStore = useAppStore()
const projectAttr = ['数据源', '数据域', '发现规则'];

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



const loginUser = {
  tsysUser: {
    id: appStore.userInfo.user.id,
    username: appStore.userInfo.user.username
  }
} 


function onReset(formQuery) {
  console.log('onReset')
  formQuery.resetFields()
  handleQuery()
}
function onQuery() {
  handleQuery()
}
// 搜索按钮操作
function handleQuery() {
  queryParams.value.page = 1
  getList()
}
const data = reactive({
  queryParams: {
    page: 1,
    everypage: 8,
    proName: '',
    note: ''
   
  }
})


      


// 表格数据
const { queryParams } = toRefs(data)


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

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


  selectDataProject({
    loginUser:loginUser,
    everypage:queryParams.value.everypage,
    note:queryParams.value.note,
    page:queryParams.value.page,
    proName:queryParams.value.proName,
  }).then(res=>{
    
    tableList.value = res.data.map(item => {
      let arrs = []
      projectAttr.forEach((name, index) => {
        if (index === 0) {
          arrs.push({
            label: name,
            value: item.list[0].s
          })
        } else if (index === 1){
          arrs.push({
            label: name,
            value: item.list[3].s
          })
        } else if (index === 2) {
          arrs.push({
            label: name,
            value: item.list[6] && item.list[6].s ? item.list[6].s : 0
          })
        }
      })
      item.list = arrs
      return item;
    });
    total.value = res.totalCount;
    loading.value = false
    console.log('tableList.value',tableList.value)
  })

  // 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)
  changeRoute()
  router.push({ path:'/indexManage/ItemManage',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.proName}"`)
  openExportDialog(project)
}
// 下载插件
const handleDownloadPlugin = (project) => {
  // ElMessage.success(`开始下载 "${project.proName}" 的插件`)
  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,
      proName: formData.proName,
      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].proName = formData.proName
      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)

}
onMounted(()=>{
  handleQuery()
})
</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.project }}
                  <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" v-for="(x,y) in item.list">
                <div class="label">{{x.label}}：</div>
                <div class="value flex1">{{x.value}}</div>
              </div>

            </el-card>
          </el-col>
        </el-row>
          
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.everypage"
          @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>