<template>
  <div class="analysis-container">
    <el-row :gutter="20">
      <!-- 左侧主操作区 -->
      <el-col :span="16">
        <el-card class="upload-section">
          <div class="input-method-select" v-if="inputMethod != 'done'">
            <el-radio-group v-model="inputMethod">
              <el-radio-button value="upload">文件上传</el-radio-button>
              <el-radio-button value="input">在线输入</el-radio-button>
            </el-radio-group>
          </div>

          <div v-if="inputMethod === 'upload'" class="upload-area">
            <!-- 节点文件上传 -->
            <el-upload class="file-upload" :on-change="handleNodeFileChange" :auto-upload="false"
              :show-file-list="false">
              <el-button type="primary" style="width: 120px; margin-right: 20px" plain>
                <el-icon>
                  <Upload />
                </el-icon>
                选择节点文件
              </el-button>
              <div class="file-info">
                {{ nodeFile ? nodeFile.name : '未选择文件' }}
                <span v-if="nodeFile">({{ formatSize(nodeFile.size) }})</span>
              </div>
            </el-upload>

            <!-- 边文件上传 -->
            <el-upload class="file-upload" :on-change="handleEdgeFileChange" :auto-upload="false"
              :show-file-list="false">
              <el-button type="primary" style="width: 120px; margin-right: 20px" plain>
                <el-icon>
                  <Upload />
                </el-icon>
                选择边文件
              </el-button>
              <div class="file-info">
                {{ edgeFile ? edgeFile.name : '未选择文件' }}
                <span v-if="edgeFile">({{ formatSize(edgeFile.size) }})</span>
              </div>
            </el-upload>

            <!-- 上传按钮和进度 -->
            <el-button type="success" :disabled="!canUpload" @click="handleUpload" class="upload-button">
              开始上传验证
            </el-button>
          </div>
          <!-- 在线输入节点与边 -->


          <div v-if="inputMethod === 'input'" class="upload-area">
            <div class="online-input">
              <el-row :gutter="20">
                <!-- 节点输入列 -->
                <el-col :span="12">
                  <div class="input-section">
                    <h4>输入节点</h4>
                    <div v-for="(node, index) in nodes" :key="index" class="input-row">
                      <el-row :gutter="10" align="middle">
                        <el-col :span="4">
                          <div class="node-id">ID:{{ node.id }}</div>
                        </el-col>
                        <el-col :span="6">
                          <el-select v-model="node.type" placeholder="选择类型" @change="handleNodeTypeChange(index)">
                            <el-option label="S" value="S" />
                            <el-option label="D" value="D" />
                            <el-option label="I" value="I" />
                          </el-select>
                        </el-col>
                        <el-col :span="10">
                          <el-input v-model="node.name" placeholder="输入节点名称" />
                        </el-col>
                        <el-col :span="4">
                          <el-button v-if="index < nodes.length - 1" @click="deleteNode(index)" type="danger" plain
                            size="small">
                            删除
                          </el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </el-col>

                <!-- 边输入列 -->
                <el-col :span="12">
                  <div class="input-section">
                    <h4>输入边</h4>
                    <div v-for="(edge, index) in edges" :key="index" class="input-row">
                      <el-row :gutter="10" align="middle">
                        <el-col :span="4">
                          <div class="node-id">ID:{{ index + 1 }}</div>
                        </el-col>
                        <!-- 起始节点 -->
                        <el-col :span="8">
                          <el-select v-model="edge.from" placeholder="起始节点" :disabled="nodeOptions.length === 0"
                            @change="handleEdgeChange(index)">
                            <el-option v-for="node in nodeOptions" :key="node.id"
                              :label="`ID:${node.id}-${node.name || '未命名'}`" :value="node.id" />
                          </el-select>
                        </el-col>

                        <!-- 终止节点 -->
                        <el-col :span="8">
                          <el-select v-model="edge.to" placeholder="终止节点" :disabled="nodeOptions.length === 0"
                            @change="handleEdgeChange(index)">
                            <el-option v-for="node in nodeOptions" :key="node.id"
                              :label="`ID:${node.id}-${node.name || '未命名'}`" :value="node.id" />
                          </el-select>
                        </el-col>

                        <!-- 删除按钮 -->
                        <el-col :span="4">
                          <el-button v-if="index < edges.length - 1" @click="deleteEdge(index)" type="danger" plain
                            size="small">
                            删除
                          </el-button>
                        </el-col>
                      </el-row>
                    </div>

                  </div>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" @click="handleValidation" class="validate-button">
              开始输入验证
            </el-button>
          </div>
          <div v-else >
            <router-view></router-view>
          </div>

        </el-card>

        <!-- 历史文件列表 -->
        <el-card class="history-section">
          <h3>历史上传记录</h3>
          <el-table :data="fileHistory" style="width: 100%">
            <el-table-column label="" width="40">
              <template #default="scope">
                <el-button v-if="scope.row.content == 'node'" type="primary"
                  style="width: 20px; height:20px; padding: 2px;">N</el-button>
                <el-button v-if="scope.row.content == 'edge'" type="warning"
                  style="width: 20px; height:20px; padding: 2px;">E</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="fileName" label="文件名" width="180" />
            <el-table-column prop="uploadTime" label="上传时间" width="180" />
            <el-table-column prop="fileSize" label="文件大小">
            </el-table-column>

            <el-table-column label="分析记录">
              <template #default="{ row }">
                <el-dropdown>
                  <span class="analysis-records">
                    查看记录<el-icon><arrow-down /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-for="(record, index) in row.records" :key="index">
                        {{ record.time }} - {{ record.type }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="danger" size="small" @click="handleDeleteFile(row)" plain>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧说明 -->
      <el-col :span="8">
        <el-card class="instruction-section">
          <h3>文件格式说明</h3>
          <div class="instruction-content">
            <div class="file-format">
              <el-tag type="success" class="format-tag">节点文件格式</el-tag>
              <el-divider />
              <div class="format-example">
                <p>节点编号 节点类型 节点描述 节点名称</p>
                <p class="example-text">示例：</p>
                <pre>001 User "普通用户" 张三
            002 Product "电子产品" 手机
            003 Category "商品类目" 数码</pre>
              </div>
            </div>

            <div class="file-format">
              <el-tag type="warning" class="format-tag">边文件格式</el-tag>
              <el-divider />
              <div class="format-example">
                <p>起始节点 终止节点</p>
                <p class="example-text">示例：</p>
                <pre>001 002
            002 003
            003 001</pre>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, inject } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, ArrowDown, Plus } from '@element-plus/icons-vue'
import { getData, postData, deleteData, postFile } from '@/api/axios.js'


// Store数据
const useAnalyzeInfo = inject('analyzeInfo')

// 响应式数据
const inputMethod = ref('upload')
// 上传的节点和边文件
const nodeFile = ref(null)
const edgeFile = ref(null)
// 在线输入的节点和边
const nodes = ref([{ id: 1, type: '', name: '' }])
const edges = ref([{ from: '', to: '' }])

const fileHistory = ref([])
const router = useRouter()



// 计算属性
// 是否允许上传文件
const canUpload = computed(() => {
  return nodeFile.value && edgeFile.value
})
// 在线输入边时节点的可选项
const nodeOptions = computed(() => {
  return nodes.value
    .filter(node => node.type !== '')
    .map(node => ({
      id: node.id,
      name: node.name || '未命名',
      type: node.type
    }))
})

// 方法

// 在线输入自动添加节点
const handleNodeTypeChange = (index) => {
  // 当最后一个节点选择类型后自动添加新行
  if (index === nodes.value.length - 1) {
    nodes.value.push({ id: nodes.value.length + 1, type: '', name: '' })
  }
}

// 删除节点
const deleteNode = (index) => {
  // 保存原始ID列表
  const originalIds = nodes.value.map(n => n.id)
  const deletedId = originalIds[index]
  // 删除关联边
  edges.value = edges.value.filter(edge =>
    edge.from !== deletedId && edge.to !== deletedId
  )
  // 删除节点并创建新数组
  const newNodes = [...nodes.value]
  newNodes.splice(index, 1)

  // 创建ID映射表（旧ID -> 新ID）
  const idMap = new Map()
  newNodes.forEach((node, i) => {
    const newId = i + 1
    idMap.set(node.id, newId)  // 记录原始ID到新ID的映射
    node.id = newId            // 更新节点ID
  })

  // 更新节点数组
  nodes.value = newNodes

  // 更新边数据中的ID引用
  edges.value = edges.value.map(edge => ({
    from: idMap.get(edge.from),
    to: idMap.get(edge.to)
  }))
  // 确保至少保留一个空行
  if (nodes.value.length === 0) {
    nodes.value.push({ id: 1, type: '', name: '' })
  }
}

// 获取有效节点ID列表
const validNodeIds = computed(() => {
  return nodes.value
    .filter(node => node.type !== '')
    .map(node => node.id)
})

// 在线输入自动添加边
const handleEdgeChange = (index) => {
  const currentEdge = edges.value[index]
  // 当最后一个边填写完整后自动添加新行
  if (index === edges.value.length - 1 && currentEdge.from && currentEdge.to) {
    edges.value.push({ from: '', to: '' })
  }
}

// 删除边
const deleteEdge = (index) => {
  edges.value.splice(index, 1)
}

// 验证在线输入
const handleValidation = async () => {
  const errors = []
  const edgeSet = new Set()


  // 检查边数据
  // 因为始终有空行，所有没有输入的时候长度为1
  if (edges.value.length == 1) {
    errors.push(`没有输入边`)
  }
  if (nodes.value.length == 1) {
    errors.push(`没有输入节点`)
  }
  edges.value.slice(0, -1).forEach((edge, index) => {
    // 检查节点是否存在
    if (!validNodeIds.value.includes(edge.from)) {
      errors.push(`边 ${index + 1}: 起始节点 ${edge.from} 不存在`)
    }
    if (!validNodeIds.value.includes(edge.to)) {
      errors.push(`边 ${index + 1}: 终止节点 ${edge.to} 不存在`)
    }

    // 自环边检查
    if (edge.from === edge.to) {
      errors.push(`边 ${index + 1}: 不允许连接自身（自环边）`)
    }
    // 归一化两个方向的边
    const [min, max] = [edge.from, edge.to].sort()
    // 默认检查无向边
    const checkDirection = false
    const edgeKey = checkDirection
      ? `${edge.from},${edge.to}`
      : `${min},${max}`

    // 检查重复边
    if (edgeSet.has(edgeKey)) {
      errors.push(`发现重复边: ${edge.from} → ${edge.to}`)
    } else {
      edgeSet.add(edgeKey)
    }
  })

  // 处理验证结果
  if (errors.length > 0) {
    ElMessage.error({
      message: `发现 ${errors.length} 个错误:<br>${errors.join('<br>')}`,
      duration: 5000,
      dangerouslyUseHTMLString: true, // 启用 HTML 解析
      customClass: 'error-message'    // 可选：添加自定义样式类
    })
    return
  }

  // 构造上传数据
  const uploadData = {
    nodes: nodes.value
      .filter(node => node.type !== '')
      .map(node => ({
        id: node.id,
        type: node.type,
        name: node.name
      })),
    edges: edges.value
      .filter(edge => edge.from && edge.to)
      .map(edge => ({
        source: edge.from,
        target: edge.to
      }))
  }

  // 执行上传
  try {
    const response = await postData('/inputFile/', uploadData)
    ElMessage.success('输入数据验证通过，上传成功')
    preparePlan(response)
  } catch (error) {
    ElMessage.error('输入数据上传失败: ' + error.message)
  }
}

// 上传文件处理

const handleNodeFileChange = (file, fileList) => {
  if (fileList.length > 1) {
    fileList.splice(0, 1);
  }
  nodeFile.value = fileList[0].raw
}

const handleEdgeFileChange = (file, fileList) => {
  if (fileList.length > 1) {
    fileList.splice(0, 1);
  }
  edgeFile.value = fileList[0].raw
}

const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}


const handleUpload = async () => {
  try {
    // 上传文件
    console.log(nodeFile)
    const formData = new FormData();
    formData.append('nodeFileName', nodeFile.value.name)
    formData.append('edgeFileName', edgeFile.value.name)
    formData.append('nodes', nodeFile.value)
    formData.append('edges', edgeFile.value)
    formData.append('type', 'csv')
    formData.append('usage', 'input')

    const response = await postFile('/uploadfile/', formData);
    if (response.status == 'success') {
      ElMessage.success('文件上传成功')
      nodeFile.value = null;
      edgeFile.value = null;
      preparePlan(response)
    } else {
      ElMessage.error("上传文件出错")
      console.log(response)
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('文件验证失败: ' + error.response.data.message)
    nodeFile.value = null;
    edgeFile.value = null;
  }
}


// 上传文件和输入得到的响应结果相同，使用同一函数跳转到规划页面
const preparePlan = (response) => {
  // 保存上传的文件信息
  response.data.forEach(file => {
    if (file.content === 'node') {
      useAnalyzeInfo.analyzeInfo.value.nodeFile.id = file.id
      useAnalyzeInfo.analyzeInfo.value.nodeFile.num = file.ndoes
      useAnalyzeInfo.analyzeInfo.value.nodeFile.sNodes = file.sNodes
      useAnalyzeInfo.analyzeInfo.value.nodeFile.dNodes = file.dNodes
      useAnalyzeInfo.analyzeInfo.value.nodeFile.iNodes = file.iNodes
    }
    if (file.content === 'edge') {
      useAnalyzeInfo.analyzeInfo.value.edgeFile.id = file.id
      useAnalyzeInfo.analyzeInfo.value.edgeFile.num = file.edges
    }
    // 获取创建的分析任务ID
    if (file.content === 'mission') {
      useAnalyzeInfo.analyzeInfo.value.mission.id = file.id
      useAnalyzeInfo.analyzeInfo.value.mission.name = file.name
    }
  })
  // 跳转到规划页面
  inputMethod.value = "done";
  console.log(useAnalyzeInfo.analyzeInfo.value)
  router.push(`/dashboard/analyze/plan`)

  updateUploadHistory()
}


const handleDeleteFile = (file) => {
  ElMessageBox.confirm(
    `确定要删除文件 ${file.fileName} 吗？此操作不可恢复。`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteData('/uploadfile/', { id: file.id }).then(response => {
      if (response.status == 'success') {
        ElMessage.success('文件已删除')
        updateUploadHistory()
      } else {
        ElMessage.error('文件删除失败' + response.message)
      }
    })
      .catch(error => {
        ElMessage.error('文件删除失败');
        console.log(error)
      })
  }).catch(() => { })
}

const updateUploadHistory = () => {
  getData('/uploadfile/')
    .then(response => {
      fileHistory.value = []
      response.data.reverse().forEach(item => {
        fileHistory.value.push({
          id: item.id,
          content: item.content,
          fileName: item.name,
          uploadTime: item.uploadTime.split('.')[0].replace('T', ' '),
          fileSize: item.size,
          records: []
        })
      })
      // history.forEach(element => {
      //   console.log(element.uploadTime.replace('T', ' ').aplit('.')[0])
      // });
      console.log(fileHistory.value)
    })
    .catch(error => {
      ElMessage.error('获取上传历史失败')
      console.log(error)
    })
}

onMounted(() => {
  updateUploadHistory();
})
</script>

<style lang="scss" scoped>
.analysis-container {
  padding: 20px;
  height: calc(100vh - 60px);
  overflow-y: auto;

  .upload-section {
    margin-bottom: 20px;

    .input-method-select {
      margin-bottom: 20px;
    }

    .upload-area {
      display: flex;
      flex-direction: column;
      gap: 15px;

      .file-upload {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 15px;
        border: 1px dashed var(--el-border-color);
        border-radius: 8px;

        .file-info {
          color: var(--el-text-color-secondary);
          font-size: 0.9em;
        }
      }

      .upload-button {
        margin-top: 15px;
        width: 200px;
        align-self: center;
      }

      .progress-bar {
        margin-top: 10px;
      }
    }
  }

  .history-section {
    h3 {
      margin-bottom: 15px;
      color: var(--el-text-color-primary);
    }

    .analysis-records {
      cursor: pointer;
      color: var(--el-color-primary);
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }

  .instruction-section {
    height: 100%;

    h3 {
      margin-bottom: 15px;
    }

    .instruction-content {
      .file-format {
        margin-bottom: 25px;

        .format-tag {
          margin-bottom: 10px;
        }

        .format-example {
          background: var(--el-fill-color-light);
          padding: 10px;
          border-radius: 6px;

          pre {
            margin: 0;
            font-family: monospace;
          }

          .example-text {
            color: var(--el-text-color-secondary);
            margin: 8px 0;
          }
        }
      }
    }
  }
}

.online-input {
  padding: 15px;

  .input-section {
    border: 1px solid var(--el-border-color);
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;

    h4 {
      margin-bottom: 15px;
      color: var(--el-text-color-primary);
    }

    .input-row {
      margin-bottom: 12px;

      .node-id {
        padding: 8px 12px;
        background: var(--el-fill-color-light);
        border-radius: 4px;
        text-align: center;
      }
    }
  }
}

.el-message.error-message {
  white-space: pre-line;
  line-height: 1.6;
  padding: 15px 20px;
}
</style>