<template>
  <div class="todo-detail-page custom-page">
    <div class="page-header">
      <div class="header-left">
        <el-button
          type="text"
          icon="el-icon-arrow-left"
          class="back-button"
          @click="handleBack"
        >
          返回
        </el-button>
        <div class="header-item">
          <span class="label">版本:</span>
          <span class="value">{{ detailData.version || 'V1.1.2' }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-button class="right-button" @click="handleImport">
          导入
        </el-button>
        <el-button class="right-button" @click="handleDownloadTemplate">
          下载导入模板
        </el-button>
        <el-button class="right-button" @click="handleRevert">
          退回
        </el-button>
        <el-button class="right-button" @click="handleSave">
          保存
        </el-button>
        <el-button class="right-button-primary" type="primary" @click="handleInitiateApproval">
          发起审批
        </el-button>
      </div>
    </div>

    <div class="detail-body">
      <!-- 左侧分类树 -->
      <div class="left-tree-panel">
        <el-input
          v-model="treeFilterText"
          size="small"
          placeholder="Q输入名称"
          clearable
          class="tree-search"
          @input="handleTreeFilter"
        />
        <el-tree
          ref="paramTree"
          :data="treeData"
          node-key="id"
          show-checkbox
          :default-checked-keys="checkedKeys"
          :default-expanded-keys="defaultExpandedKeys"
          :props="{ children: 'children', label: 'label' }"
          :filter-node-method="filterTreeNode"
          @check="handleTreeCheck"
        />
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-content">
        <div
          v-for="(section, sectionIndex) in parameterSections"
          :key="sectionIndex"
          class="section"
        >
          <div class="section-title">
            {{ section.title }}
          </div>
          <div class="parameter-table">
            <table class="param-table">
              <thead>
                <tr>
                  <th class="param-name-col">参数名称</th>
                  <th class="param-value-col">参数值</th>
                  <th class="param-unit-col">单位</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(param, paramIndex) in section.parameters" :key="paramIndex">
                  <td class="param-name-cell">{{ param.name }}</td>
                  <td class="param-value-cell">
                    <el-input
                      v-model="param.value"
                      size="small"
                      placeholder="请输入"
                      :disabled="!isEditable"
                    />
                  </td>
                  <td class="param-unit-cell">{{ param.unit }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'TodoDetail',
  props: {
    detailData: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      treeFilterText: '',
      isEditable: false,
      checkedKeys: [],
      defaultExpandedKeys: [],
      treeData: [],
      parameterSections: [
        {
          title: '基本规格',
          parameters: [
            { name: '合金材料', value: '', unit: '-' },
            { name: '轴瓦有无表面涂层或成薄层', value: '', unit: '-' },
            { name: '轴瓦有无表面涂层或成薄层', value: '', unit: '-' },
            { name: '表面涂层类型', value: '', unit: '-' },
            { name: '钢背材料', value: '', unit: '-' },
            { name: '轴瓦宽度', value: '', unit: 'mm' },
            { name: '壁厚', value: '', unit: '(1/1000inch)' },
            { name: '轴瓦内径mm', value: '', unit: 'mm' },
            { name: '唇口宽度mm', value: '', unit: 'mm' },
            { name: '唇口高度(径向)mm', value: '', unit: 'mm' },
            { name: '唇口长度(圆周方向)mm', value: '', unit: 'mm' },
            { name: '半瓦高mm', value: '', unit: 'mm' },
            { name: '配合间隙mm', value: '', unit: 'mm' },
            { name: '轴座孔径mm', value: '', unit: 'mm' },
            { name: '轴座材料', value: '', unit: '-' },
            { name: '设计意图', value: '', unit: '-' }
          ]
        },
        {
          title: '开发边界',
          parameters: [
            { name: '合金材料', value: '', unit: '-' },
            { name: '轴瓦有无表面涂层或成薄层', value: '', unit: '-' },
            { name: '轴瓦有无表面涂层或成薄层', value: '', unit: '-' },
            { name: '表面涂层类型', value: '', unit: '-' },
            { name: '钢背材料', value: '', unit: '-' },
            { name: '轴瓦宽度', value: '', unit: 'mm' },
            { name: '壁厚', value: '', unit: '(1/1000inch)' },
            { name: '轴瓦内径mm', value: '', unit: 'mm' },
            { name: '唇口宽度mm', value: '', unit: 'mm' },
            { name: '唇口高度(径向)mm', value: '', unit: 'mm' },
            { name: '唇口长度(圆周方向)mm', value: '', unit: 'mm' },
            { name: '半瓦高mm', value: '', unit: 'mm' },
            { name: '配合间隙mm', value: '', unit: 'mm' },
            { name: '轴座孔径mm', value: '', unit: 'mm' },
            { name: '轴座材料', value: '', unit: '-' },
            { name: '设计意图', value: '', unit: '-' }
          ]
        }
      ]
    }
  },
  mounted() {
    // 加载树数据
    this.loadTreeData()
  },
  methods: {
    handleBack() {
      this.$emit('close')
    },
    handleImport() {
      this.$message.info('导入功能')
    },
    handleDownloadTemplate() {
      this.$message.info('下载导入模板功能')
    },
    handleRevert() {
      this.$message.info('退回功能')
    },
    handleSave() {
      this.$message.info('保存功能')
    },
    handleInitiateApproval() {
      this.$message.info('发起审批功能')
    },
    handleTreeFilter(value) {
      this.$refs.paramTree.filter(value)
    },
    filterTreeNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleTreeCheck(data, checked) {
      console.log('树节点选择变化:', data, checked)
    },
    getAllNodeKeys(nodes) {
      let keys = []
      nodes.forEach(node => {
        keys.push(node.id)
        if (node.children && node.children.length > 0) {
          keys = keys.concat(this.getAllNodeKeys(node.children))
        }
      })
      return keys
    },
    // 加载树数据
    loadTreeData() {
      const request = {
        ...api.GET_PARAM_LIST,
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          // 处理接口返回的数据
          if (resp && resp.data) {
            // 接口返回的是对象格式：{ "父节点名": ["子节点1", "子节点2", ...] }
            const data = resp.data
            if (typeof data === 'object' && !Array.isArray(data)) {
              this.treeData = this.convertObjectToTree(data)
            } else if (Array.isArray(data)) {
              // 如果已经是数组格式，尝试格式化
              this.treeData = this.formatTreeData(data)
            } else {
              this.treeData = []
            }
            // 设置默认展开和选中的keys
            this.defaultExpandedKeys = this.getAllNodeKeys(this.treeData)
            this.checkedKeys = this.getAllNodeKeys(this.treeData)
          }
        })
        .asyncErrorCatch((err) => {
          console.error('获取参数列表失败:', err)
          this.$message.error('获取参数列表失败')
        })
    },
    // 将对象格式转换为树形结构
    // 输入格式: { "父节点名": ["子节点1", "子节点2", ...] }
    convertObjectToTree(data) {
      const treeData = []

      Object.keys(data).forEach((parentLabel, parentIdx) => {
        const parentId = `parent-${parentIdx}`
        const children = []

        // 处理子节点数组
        if (Array.isArray(data[parentLabel])) {
          data[parentLabel].forEach((childLabel, childIdx) => {
            children.push({
              id: `${parentId}-${childIdx}`,
              label: childLabel,
              tip: ''
            })
          })
        }

        treeData.push({
          id: parentId,
          label: parentLabel,
          tip: '',
          children: children
        })
      })

      return treeData
    },
    // 格式化树数据，确保每个节点有 id 和 label 属性
    formatTreeData(data) {
      return data.map((item, index) => {
        const node = {
          id: item.id || item.key || `node-${index}`,
          label: item.label || item.name || item.title || '',
          tip: item.tip || ''
        }
        if (item.children && item.children.length > 0) {
          node.children = this.formatTreeData(item.children)
        }
        return node
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.todo-detail-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #f5f7fa;

  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 56px;
    position: relative;
    width: 100%;
    min-height: 56px;
    background: #fff;
    border-bottom: 1px solid #ebeef5;
    padding: 0 20px;
    flex-shrink: 0;
    z-index: 10;

    .header-left {
      display: flex;
      align-items: center;
      gap: 10px;
      flex: 1;

      .back-button {
        padding: 0;
        margin-right: 8px;
        font-size: 14px;
        color: #409eff;
        cursor: pointer;
        pointer-events: auto;

        &:hover {
          color: #66b1ff;
        }

        i {
          margin-right: 4px;
        }
      }

      .header-item {
        display: flex;
        align-items: center;
        gap: 8px;

        .label {
          color: #303133;
          font-size: 14px;
        }

        .value {
          color: #303133;
          font-size: 14px;
          font-weight: 500;
        }
      }
    }

    .header-right {
      display: flex;
      gap: 8px;
    }
  }

  .detail-body {
    display: flex;
    flex: 1;
    min-height: 0;
    padding: 16px 20px 24px 20px;
    gap: 20px;
  }

  .left-tree-panel {
    width: 200px;
    background: #fff;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 12px;
    flex-shrink: 0;
    overflow-y: auto;

    .tree-search {
      margin-bottom: 12px;

      ::v-deep .el-input__inner {
        height: 32px;
        line-height: 32px;
      }
    }

    ::v-deep .el-tree {
      .el-tree-node__label {
        font-size: 14px;
        color: #303133;
      }

      .el-checkbox__input.is-checked .el-checkbox__inner {
        background-color: #409eff;
        border-color: #409eff;
      }
    }
  }

  .right-content {
    flex: 1;
    background: #fff;
    border-radius: 4px;
    overflow-y: auto;
    min-height: 0;
  }

  .section {
    padding: 20px;
    border-bottom: 1px solid #ebeef5;

    &:last-child {
      border-bottom: none;
    }
  }

  .section-title {
    font-weight: 600;
    font-size: 16px;
    color: #303133;
    margin-bottom: 16px;
  }

  .parameter-table {
    width: 100%;
    overflow-x: auto;
  }

  .param-table {
    width: 100%;
    border-collapse: collapse;
    border: 1px solid #ebeef5;

    thead {
      background: #f5f7fa;

      th {
        padding: 12px 16px;
        text-align: left;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        border-bottom: 1px solid #ebeef5;
        white-space: nowrap;

        &.param-name-col {
          width: 40%;
          min-width: 300px;
        }

        &.param-value-col {
          width: 40%;
          min-width: 300px;
        }

        &.param-unit-col {
          width: 20%;
          min-width: 120px;
        }
      }
    }

    tbody {
      tr {
        &:not(:last-child) {
          border-bottom: 1px solid #ebeef5;
        }

        &:hover {
          background-color: #f5f7fa;
        }
      }

      td {
        padding: 12px 16px;
        font-size: 14px;
        color: #606266;
        vertical-align: middle;

        &.param-name-cell {
          font-weight: 500;
          color: #303133;
        }

        &.param-value-cell {
          .el-input {
            width: 100%;

            ::v-deep .el-input__inner {
              height: 32px;
              line-height: 32px;
              border: 1px solid #dcdfe6;
              border-radius: 4px;

              &:focus {
                border-color: #409eff;
              }

              &:disabled {
                background-color: #f5f7fa;
                border-color: #e4e7ed;
                color: #606266;
              }
            }
          }
        }

        &.param-unit-cell {
          color: #909399;
          text-align: center;
        }
      }
    }
  }
}

.right-button {
  border: 1px solid #027aff !important;
  color: #027aff !important;

  &:hover {
    background: #ecf5ff;
    border-color: #66b1ff;
    color: #66b1ff;
  }
}

.right-button-primary {
  background: #027aff !important;
  border-color: #027aff !important;
  color: #fff !important;

  &:hover {
    background: #66b1ff !important;
    border-color: #66b1ff !important;
  }
}
</style>

