<script setup name="ProjectManageList">
import { getCurrentInstance, reactive, ref, toRefs,onMounted } from 'vue'
import { ElMessage,ElMessageBox } 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,
  checkProjectNum,
  addDataProject,
  deleteDataProject,
  updateDataProject
} 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 addLoading = ref(false)
// 显示新增对话框
const showAddDialog = () => {


    addLoading.value = true
    checkProjectNum().then(res=>{
      console.log('checkProjectNum',res)
      if(res.flag){
        currentProject.value = null
        dialogVisible.value = true
        // getdatascopeprojectlist().then(res=>{
        //    currentProject.value = null
        // dialogVisible.value = true
        // })
        addLoading.value = false
      }else{
        addLoading.value = false
      }
    }).catch(err=>{
      addLoading.value = false
    })
  // 





}

// 处理项目操作
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()
  sessionStorage.setItem('projectId',project.id)
  router.push({ path:'/indexManage/ItemManage',query: { projectId: project.id } })


}

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


// 删除项目
const handleDeleteProject = (val) => {
   ElMessageBox.confirm(
      `确定要删除项目「${val.project}」吗？此操作不可恢复。`,
      '删除确认',
      {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          callback: (action) => {
              if (action === 'confirm') {
                  // 执行删除操作
                  let parms = {
                    loginUser:loginUser,
                    project:val
                  }
                  deleteDataProject(parms).then(res=>{
                    if(res.flag){
                      ElMessage.success(`项目「${val.project}」已删除`);
                    }else{
                       ElMessage.info(res.msg);
                    }
                     
                  }).catch(err=>{
                     ElMessage.info(res.msg);
                  })
                 
              } else {
                  ElMessage.info('已取消删除');
              }
          }
      }
  );
}

// 导入项目
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 = {
      
      
      loginUser:loginUser,
      project:{
        edition_id: '',
        note: formData.remark,
        project: formData.name,
        projectType: "normal",
      },
      
      schemalist:formData.schemas,
      areaAndRuleList:formData.domains,
      dataSourceIdList:formData.databases.map(item =>(({
        id:item.tid,
        sysname:item.sysname,
        systemstyle:1,
        dbtype:item.dbtype
      })))
    }
    addDataProject(newProject).then(res=>{
      console.log(res)
      if(res.flag){
         ElMessage.success('新增项目成功')
         handleQuery()
      }
    })
    // tableList.value.push(newProject)
    // total.value++
    // ElMessage.success('新增项目成功')
  } else {
     const newProject = {
      
      
      loginUser:loginUser,
      project:{
        edition_id: '',
        note: formData.remark,
        project: formData.name,
        id:formData.id,
        projectType: "normal",
      },
      
      schemalist:formData.schemas,
      areaAndRuleList:formData.domains,
      dataSourceIdList:formData.databases.map(item =>(({
        id:item.tid,
        sysname:item.sysname,
        systemstyle:1,
        dbtype:item.dbtype
      })))
    }
    console.log('newProject',newProject)

    updateDataProject(newProject).then(res=>{
      console.log(res)
      if(res.flag){
         ElMessage.success('新增项目成功')
         handleQuery()
      }
    })
  }
}


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
          :loading="addLoading"
          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>