<template>
  <el-dialog
    style="padding: 0;"
    class="custom-dialog"
    v-model="dialogVisible"
    :show-close="false"
    destroy-on-close
    width="920px"
    :before-close="handleClose"
  >
    <template #header>
      <div class="custom-dialog-header">
        <div class="custom-dialog-title">
          {{ dialogTitle }}
        </div>
        <img class="custom-dialog-close" :src="dialogCloseLogo" alt="" @click="closeDialog">
      </div>
      
      
    </template>

    <!-- <el-divider class="dialog-divider"></el-divider> -->

    <div class="dialog-content">
      <!-- 左侧表单 -->
      <div class="form-container">
        <ItemTitle title="基本信息" />
        <!-- 第一步：基本信息 -->
        <div class="item-form-container">
          <el-form
            ref="basicInfoFormRef"
            :model="formData"
            :rules="formRules"
            label-width="90px"
            label-position="left"
            :inline="true"
          >
            <el-form-item label="项目名称" prop="name" required>
              <el-input
                v-model="formData.name"
                placeholder="请输入项目名称"
                @blur="validateFormTitle"
              />
            </el-form-item>

            <el-form-item label="项目备注" prop="remark">
              <el-input
                v-model="formData.remark"
                placeholder="请输入项目备注信息"
              />
            </el-form-item>


          </el-form>
        </div>

        <ItemTitle title="数据源配置" style="margin-top: 20px;" />

        <!-- 第二步：数据库配置 -->
        <div class="item-form-container">
          
          
          <!-- TreeSelect 组件 -->
           <div class="tree-select-container flex-container align-center" style="flex-wrap: nowrap;">
            <div class="step-title master" style="width: 90px;">数据库</div>
            <el-tree-select
              ref="treeSelectRef"
              v-model="selectedDbNodes"
              :data="treeData"
              :props="treeProps"
              :render-after-expand="false"
              show-checkbox
              node-key="tid"
              :filter-node-method="filterNode"
              placeholder="请选择数据源"
              multiple
              @check="handleTreeSelectCheck"
              :default-expand-all="false"
            >
              <template #default="{ node, data }">
                <span class="tree-node-label">
                  {{ data.sysname || data.text }}
                  <span v-if="data.dbtype" class="tree-node-type">({{ data.dbtype }})</span>
                </span>
              </template>
            </el-tree-select>
          </div>
        </div>

        <ItemTitle title="Schema选择" style="margin-top: 20px;"/>
        <!-- 第三步：Schema选择 -->
        <div class="item-form-container">
          <div v-if="selectedDbDetails.length === 0" class="flex-container align-center">
            请先选择数据库
          </div>
          <div class="flex-container align-center wrap" v-else>
            <div 
              v-for="(db, dbIndex) in selectedDbDetails" 
              :key="db.tid"
              class="datasource-item flex-container align-center"
            >
              <div style="width: 90px;">{{ db.sysname }}</div> 
              <el-select
                v-model="selectedSchemas[dbIndex]"
                multiple
                placeholder="请选择"
                style="width: 278px"
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
                @change="selectChangeSchema"
              >
                <el-option
                  v-for="schema in allSchemas[dbIndex]"
                  :key="schema.value"
                  :label="schema.text"
                  :value="schema.value"
                />
              </el-select>
            </div>
          </div>
          
        </div>

        <!-- 其他步骤内容保持不变 -->
       <ItemTitle title="规则选择" style="margin-top: 20px;"/>
       <!-- 第四步：数据域选择 -->
        <div class="item-form-container">
          <div class="tree-select-container flex-container align-center" style="flex-wrap: nowrap;">
            <div class="step-title master" style="width: 90px;">规则</div>
            <el-tree-select
              ref="treeSelectRuleRef"
              v-model="selectedRuleNode"
              node-key="id"
              :data="transformedDomainGroups"
              :props="treeRuleProps"
              placeholder="请选择规则"
              multiple
              :render-after-expand="false"
              show-checkbox
            >
              <template #default="{ node, data }">
                <span class="tree-node-label">
                  {{ data.dataarea || data.name }}
                </span>
              </template>
            </el-tree-select>
          </div>
        </div>
      </div>

      <!-- 右侧步骤条 -->
      <!-- <div class="steps-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step :title="stepTitles[0]" />
          <el-step :title="stepTitles[1]" />
          <el-step :title="stepTitles[2]" />
          <el-step :title="stepTitles[3]" />
        </el-steps>
      </div> -->
    </div>

    <template #footer>

        <el-button type="primary" color="rgba(33, 103, 217, 1)" @click="handleSubmit">确认</el-button>
        <el-button type="primary" plain @click="handleCancle">取消</el-button>

    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch,nextTick } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import dialogCloseLogo from '@/assets/images/dialogCloseLogo.png'

import {
  getdatascopeprojectlist,
  checkDatasystemName,
  checkDatasystem,
  queryByEditSort,
  selectProDataSource,
  queryShemas,
  getAllDataAreaAndRule,
  getDataProjectDetail
} from '@/api/project'

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

const appStore = useAppStore()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  projectData: {
    type: Object,
    default: () => ({
      name: '',
      remark: '',
      projectType: 'normal',
      databases: [],
      schemas: [],
      domains: []
    })
  },
  mode: {
    type: String,
    default: 'add',
    validator: (value) => ['add', 'edit'].includes(value)
  }
})

const emit = defineEmits(['update:visible', 'submit'])

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})
const formRules = ref({
 name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
})
// 初始化标志
const initialized = ref(false)

// 监听对话框显示状态变化
watch(dialogVisible, (newVal) => {
  if (newVal && !initialized.value) {
    // initDialog()
    //  fetchFirstLevelNodes()
    fetchAllDatabaseNodes()
     fetchRules()
  } else if (!newVal) {
    initialized.value = false
  }
}, { deep: true })

const fetchRules = () => {
  selectedRuleNode.value = []
    getAllDataAreaAndRule().then(res => {
    domainGroups.value = res.data
    // 如果是编辑模式，需要处理已选择的规则
    if (props.mode === 'edit' && areaAndRuleListRead.value.length > 0) {
      // processAreaAndRuleListForEdit(areaAndRuleListRead.value)
        // selectedRuleNode

        areaAndRuleListRead.value.forEach(element => {
          selectedRuleNode.value.push(element.rule_id)
        });
    }
  })
}
const treeRuleProps = reactive({
  label: 'dataarea',
  children: 'children'
});
const selectedRuleNode = ref([])
// 转换数据格式以适应el-tree-select
const transformedDomainGroups = computed(() => {
  return domainGroups.value.map(group => {
    // 复制组的基本信息
    const transformedGroup = {
      id: group.id,
      dataarea: group.dataarea,
      children: []
    };
    
    // 将list转换为children
    if (group.list && Array.isArray(group.list)) {
      transformedGroup.children = group.list.map(rule => ({
        ...rule,
        id: rule.id,
        name: rule.name,
        dataarea: rule.type, // 使用type作为数据域名称
        ruleexample: rule.ruleexample,
        isRule: true // 标记为规则节点
      }));
    }
    
    return transformedGroup;
  });
});

const treeData = ref([])
const selectedDbNodes = ref([])
const treeProps = ref({

  
  label: 'sysname',        // 显示文本的字段名
  children: 'children',  
  // disabled: (data) => !data.tid // 只有二级节点可以选择
})
// 获取树形数据

const fetchAllDatabaseNodes = async () => {
  try {
    // 获取所有一级节点
    const typeRes = await selectProDataSource({
      systemstyle: 1
    })
    
    if (typeRes.flag && typeRes.data) {
      const firstLevelNodes = typeRes.data.map(item => ({
        id: item.value,
        tid: item.value,
        text: item.text,
        value: item.value,
        sysname: item.text,
        disabled: true,
        isFirstLevel: true,
        children: [] // 初始化空children
      })).filter(item => item.value !== '0')
      
      // 为每个一级节点获取其二级节点
      const allNodes = await Promise.all(
        firstLevelNodes.map(async (firstNode) => {
          try {
            const secondRes = await queryByEditSort({
              projectId: '',
              dbtype: firstNode.text,
              loginUser: loginUser,
              flag: 1
            })
            
            if (secondRes.flag && secondRes.data) {
              firstNode.children = secondRes.data.map(db => ({
                ...db,
                parentName: firstNode.text,
                parentId: firstNode.id,
                text: db.sysname,
                isFirstLevel: false
              }))
            }
            
            return firstNode
          } catch (error) {
            console.error(`获取 ${firstNode.text} 的二级节点失败:`, error)
            return firstNode
          }
        })
      )
      
      treeData.value = allNodes
      console.log('treeData',treeData.value)


      if(props.mode === 'edit' && selectedDbNodes.value){
        selectedSchemas.value = []

        nextTick(() =>{
            if(treeSelectRef.value){
             
              treeSelectRef.value.setCheckedKeys(selectedDbNodes.value)
              selectedDbDetails.value = treeSelectRef.value.getCheckedNodes()
              console.log('selectedDbDetails',selectedDbDetails.value)
              fetchAllSchemas(selectedDbDetails.value)
               console.log('editschemalist',editschemalist.value)
              
              for (let index = 0; index < selectedDbDetails.value.length; index++) {
                let tid = selectedDbDetails.value[index].tid
                let list = editschemalist.value.filter(item =>item.osdsid === tid)
                console.log('list',list)
                let nameList = []
                list.forEach(element => {
                  nameList.push(element.schemaname)
                });
                console.log('nameList',nameList)
                if(nameList.length){
                  selectedSchemas.value.push(nameList)
                }


                
              }

              if(selectedSchemas.value.length > 0){
                selectChangeSchema()
              }
                console.log('selectedSchemas',selectedSchemas.value)
              // editschemalist
            }
          })



        //  selectedDbDetails.value = treeSelectRef.value.getCheckedNodes()
        //   console.log('=====',selectedDbDetails.value)
        //   fetchAllSchemas(selectedDbDetails.value)
      }
    }
  } catch (error) {
    console.error('获取数据库节点数据失败:', error)
    ElMessage.error('获取数据库节点数据失败')
  }
}

const treeSelectRef = ref(null)
// 处理树选择变化
const handleTreeSelectCheck = (checkedNode, { checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }) => {
  console.log('checkedNodes',checkedNodes)
  
  // 完全排除一级节点的选择，只保留有tid的二级节点
  const secondaryNodes = checkedNodes.filter(node => node.tid && !node.isFirstLevel && !node.children);
  // selectedDbDetails.value = secondaryNodes;
  
  // 更新选中节点的keys（只包含二级节点）
  selectedDbNodes.value = secondaryNodes.map(node => node.tid);
  
  // console.log('更新后的 selectedDbNodes:', selectedDbNodes.value);

};
watch(selectedDbNodes, (newVal) => {
  
  if(newVal) {
    console.log('============',newVal)
    selectedDbDetails.value = treeSelectRef.value.getCheckedNodes()

    fetchAllSchemas(selectedDbDetails.value)
  }
}, { deep: true })

// 过滤节点
const filterNode = (value, data) => {
  if (!value) return true
  return data.sysname?.toLowerCase().includes(value.toLowerCase()) || 
         data.text?.toLowerCase().includes(value.toLowerCase())
}



const reset = () => { 
  sourceTypeList.value = []
  formData.value = {}
  dbFilter.value.type = ''
  dbFilter.value.keyword = ''

  selectedDbs.value = []
}

const sourceTypeList = ref([])
// 表单数据
const formData = ref({
  id: '',
  name: '',
  remark: '',
  projectType: 'normal',
  databases: [],
  schemas: [],
  domains: [],
})


// 弹窗标题
const dialogTitle = computed(() => {
  return props.mode === 'add' ? '新增项目' : '编辑项目'
})

// 第二步：数据库配置相关
const dbFilter = ref({
  type: '',
  keyword: ''
})
const selectedDbDetails = ref([])
// 定义数据源相关变量
const availableDatabases = ref([]) // queryByEditSort返回的未选择数据源
const selectedDbs = ref([]) // 当前选择的数据库ID列表

const allSchemas = ref([])
const selectedSchemas = ref([])


// 第四步：数据域选择相关
const domainGroups = ref([])


const schemalist = ref([])





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


const basicInfoFormRef = ref(null)


// 第一步验证接口函数
const validateStep1 = async () => {
  return await checkDatasystemName({
    name: formData.value.name,
    id: formData.value.id
  })
}

const validateFormTitle = () =>{
  checkDatasystemName({
    name: formData.value.name,
    id: formData.value.id
  }).then(response=>{
    if (response.flag !== true){
      ElMessage.error(response.msg || '第一步验证失败')
      return
    }
  })
}



const handleSubmit = async ()=> {
  if(!formData.value.name || formData.value.name === ''){
    ElMessage.warning('请输入项目名称')
    return
  }

  
  const response = await validateStep1()
  if (response.flag !== true){
    ElMessage.error(response.msg || '第一步验证失败')
    return
  }


  if(!selectedDbNodes.value || selectedDbNodes.value.length === 0) {
    ElMessage.warning('请选择数据库')
    return
  }

  if(!selectedSchemas.value || selectedSchemas.value.length === 0) {
    ElMessage.warning('请选择Schema')
    return
  }
  if(!selectedRuleNode.value || selectedRuleNode.value.length === 0) {
    ElMessage.warning('请选择规则')
    return
  }



  // console.log('项目名称',formData.value.name)
  // console.log('项目备注',formData.value.remark)
  // console.log('项目数据源',selectedDbDetails.value)
  // console.log('Schema',schemalist.value)
  // console.log('rule',selectedRuleNode.value)

  // console.log('transformedDomainGroups',transformedDomainGroups)

    let list = []
    for (let index = 0; index < selectedRuleNode.value.length; index++) {
      const item = selectedRuleNode.value[index];

       transformedDomainGroups.value.forEach(element => {
        let data = element.children.find(x =>x.id === item)
        if(data){
          list.push(data)
        }
       });
      
    }

    formData.value.databases = selectedDbDetails.value
    formData.value.schemas = schemalist.value
    formData.value.domains = list.map(item =>({
      dataarea_id:item.dataarea_id,
      rule_id: item.id
    }))

    emit('submit', formData.value)

    setTimeout(() => {
      reset()
      dialogVisible.value = false
    }, 300)
}
const closeDialog = () => {
  ElMessageBox.confirm('确定要关闭吗？未保存的更改将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    dialogVisible.value = false
    reset()
    done()
  }).catch(() => {
    // 取消关闭
  })

}

const handleCancle = () =>{
    ElMessageBox.confirm('确定要取消吗？未保存的更改将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    dialogVisible.value = false
    reset()
    done()
  }).catch(() => {
    // 取消关闭
  })
}
// 关闭前处理
const handleClose = (done) => {
  ElMessageBox.confirm('确定要关闭吗？未保存的更改将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    reset()
    done()
  }).catch(() => {
    // 取消关闭
  })
}

const fetchAllSchemas = async (databases) => {
  try {
    allSchemas.value = []
    
    const results = await Promise.all(
      databases.map(db => 
        queryShemas({
          dbType: db.dbtype,
          dataSystemId: db.tid
        }).catch(error => {
          console.error(`获取数据库 ${db.sysname} 的Schema失败:`, error)
          return { 
            dataSystemId: db.tid,
            error: true,
            message: `获取数据库 ${db.sysname} 的Schema失败`
          }
        })
      )
    )
    
    const successResults = results.filter(r => !r.error)
    
    successResults.forEach(res => {
      if (res.data && Array.isArray(res.data)) {
        allSchemas.value.push(res.data)
      }
    })
    
    console.log('allSchemas', allSchemas.value)
  } catch (error) {
    console.error('获取Schema数据过程中出错:', error)
    ElMessage.error('获取Schema数据过程中出错')
  }
}

const selectChangeSchema = async () => { 
  console.log('selectedSchemas',selectedSchemas.value)
  let list = []
  selectedSchemas.value.forEach((element,elementIndex) => {
    element.forEach(item => {
      list.push({
        schemaname: item,
        dbtype: selectedDbDetails.value[elementIndex].dbtype,
        osdsid: selectedDbDetails.value[elementIndex].tid,
      })
    });
  });
  console.log(list)
  schemalist.value = list
}
const editschemalist = ref([])
const areaAndRuleListRead = ref([])
watch(() => props.projectData, (newVal) => {
  if (props.mode === 'edit' && newVal.id) {
    formData.value = { ...newVal }
    
    getDataProjectDetail({projectId: newVal.id}).then(res => { 
      if(res.flag) {
        let data = res.data
        if(!data) return
        formData.value.id = data.project.id
        formData.value.name = data.project.project
        formData.value.remark = data.project.note
        areaAndRuleListRead.value = data.areaAndRuleList
        if(data.dataSourceIdList && data.dataSourceIdList.length > 0){
          let list = []
          data.dataSourceIdList.forEach(element => {
            list.push(element.systemsource_id)
          });
         
          selectedDbNodes.value = list
           
          editschemalist.value = data.schemalist
          //  console.log('selectedDbNodes',selectedDbNodes.value)
          

            
         
        }

      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      ElMessage.error(err.msg)
    })
  }
}, { immediate: true, deep: true })






</script>
<style scoped lang="scss">
.dialog-content {
  display: flex;
  // min-height: 500px;
}

.form-container {
  flex: 1;
  .el-form-item--default{
    margin-bottom: 0px;
  }
  // padding-right: 30px;
}

.steps-container {
  width: 150px;
  padding-left: 30px;
  border-left: 1px solid #eee;
}

.step-title {
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 22px;
  color: rgba(148, 148, 148, 1);
}

/* 第二步样式 */
.filter-container {
  display: flex;
  margin-bottom: 15px;
  gap: 10px;
}

.filter-select {
  width: 120px;
}

.filter-input {
  flex: 1;
}

.db-select-container {
  display: flex;
  gap: 20px;
}

.db-list {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.db-list.selected {
  flex: 1;
}

.db-list-header {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.db-item {
  padding: 10px 15px;
  border-bottom: 1px solid #f5f5f5;
  &:hover{
    background-color: #aed8ff;
    cursor: pointer;
  }
}

.selected-db-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f5f5f5;
  &:hover{
    background-color: #aed8ff;
    cursor: pointer;
  }
}

.db-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.db-ip {
  color: #666;
  font-size: 13px;
  margin-bottom: 3px;
}

.db-username {
  color: #999;
  font-size: 12px;
}

/* 第三步样式 */
.schema-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.datasource-section, .schema-section {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f8f8f8;
}

.section-title {
  padding: 10px 15px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f5f5;
}

.datasource-list {
  padding: 5px 0;
}

.datasource-item {
  padding: 10px 15px;
  cursor: pointer;
  // border-bottom: 1px solid #f0f0f0;
}

.datasource-item:hover {
  // background-color: #f0f7ff;
}

.datasource-item.active {
  // background-color: #e6f7ff;
  color: #1890ff;
}

.schema-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 15px;
}

.schema-select-all {
  display: flex;
  align-items: center;
  gap: 10px;
}

.schema-count {
  color: #999;
  font-size: 13px;
}

.schema-item {
  padding: 10px 15px;
  border-bottom: 1px solid #f0f0f0;
}

/* 第四步样式 */
.domain-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.available-domains, .selected-domains {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px; 
  background-color: #f8f8f8;
  height: 500px;
  overflow-y: auto;
}

.section-header {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-weight: bold;
}

.selection-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.count {
  color: #1890ff;
  font-weight: bold;
}

.domain-group {
  margin-bottom: 20px;
}

.group-header {
  padding: 10px 15px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #e8e8e8;
}

.domain-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.domain-content {
  margin-left: 8px;
}

.domain-name {
  font-weight: 500;
}

.domain-desc {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.selected-domain-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.selected-domain-item .domain-name {
  font-weight: bold;
}

.selected-domain-item .domain-desc {
  color: #666;
  font-size: 13px;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-step__title) {
  font-size: 14px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  padding-bottom: 8px;
}
.item-form-container {
  margin-top: 14px;
  border-radius: 5px;
  background: rgba(247, 248, 250, 1);
  padding-top: 25px;
  padding-bottom: 27px;
  padding-left: 15px;
  padding-right: 15px;
  :deep(.el-form-item__label) {
    font-size: 14px;
    font-weight: 400;
    letter-spacing: 0px;
    color: rgba(148, 148, 148, 1);
  }
  :deep(.el-input__wrapper){
    width: 278px;
  }
}

/* 一级节点隐藏checkbox */
:deep(.first-level-node .el-checkbox) {
  display: none !important;
}

/* 确保一级节点仍然可以点击展开 */
:deep(.first-level-node .el-tree-node__expand-icon) {
  display: inline-block !important;
}

/* 二级节点正常显示checkbox */
:deep(.second-level-node .el-checkbox) {
  display: inline-block !important;
}
.flex-container { 
  display: flex;

}
.wrap {
  flex-wrap: wrap;
}
.align-center{
  align-items: center;
}
.justify-center {
  justify-content: center;
}
.master {
  &::before{
    color: var(--el-color-danger);
    content: "*";
    margin-right: 4px;
  }
     
}
</style>
