<template>
  <div class="panel-container">
    <div class="selection-card">
      <!-- 房型配置 -->
      <div v-if="selectedProject" class="room-config">
        <div class="section-title">
          <el-icon><OfficeBuilding /></el-icon>
          <span>房型配置</span>
          <el-button type="primary" size="small" @click="addRoomType" plain style="margin-left:10px">
            <el-icon><Plus /></el-icon>添加房型
          </el-button>
        </div>

        <div class="tree-layout">
          <!-- 左侧树形列表 -->
          <div class="tree-container">
            <el-tree ref="roomTreeRef" :data="treeData" size="small" node-key="id" :props="treeProps"
                     default-expand-all="true" :expanded-keys="expandedKeys" :expand-on-click-node="true"
                     :highlight-current="true" @node-click="handleNodeClick">
              <template #default="{ node, data }">
                <div class="tree-node">
                  <span class="node-label" v-if="!data.editing" @dblclick="startEditing(data)">
                    <el-icon v-if="data.type === 'room'"><House /></el-icon>
                    <el-icon v-else><Menu /></el-icon>
                    {{ node.label }}
                  </span>
                  <el-input v-else v-model="data.newLabel" size="small" @blur="finishEditing(data)"
                            @keyup.enter="finishEditing(data)" autofocus />
                  <span class="node-actions">
                    <el-button type="text" size="small" @click.stop="startEditing(data)" v-if="!data.editing" link plain>
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button v-if="data.type === 'room'" type="primary" size="small" @click.stop="addPanel(data)" link plain>
                      <el-icon><Plus /></el-icon>
                    </el-button>
                    <el-button v-else size="small" link plain>
                      <el-icon></el-icon>
                    </el-button>
                    <el-button type="danger" size="small" @click.stop="removeNode(data)" link plain v-if="isAllowDel(data)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                    <el-button v-else size="small" link plain>
                      <el-icon></el-icon>
                    </el-button>
                  </span>
                </div>
              </template>
            </el-tree>
          </div>

          <!-- 右侧面板配置 -->
          <div class="panel-config" v-if="currentPanel">
            <!-- 步骤条 -->
            <el-steps :active="currentStep"
                      finish-status="success"
                      simple
                      align-center>
              <el-step title="选择面板" />
              <el-step title="配置面板" />
              <el-step title="生成预览" />
              <el-step title="保存配置" />
            </el-steps>

            <!-- 步骤1: 选择系列和模型 -->
            <div v-show="currentStep === 0" class="step-content">
              <div class="model-selectors">
                <div class="selector-row">
                  <!-- 系列选择表格 -->
                  <div class="form-group">
                    <label>系列</label>
                    <el-table :data="seriesList"
                              highlight-current-row
                              @current-change="handleFileChange"
                              style="width: 100%">
                      <el-table-column prop="Series" label="系列名称">
                        <template #default="{ row }">
                          {{ formatName(row.Series) + '_' + row.Version }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>

                  <!-- 模型选择表格 -->
                  <div class="form-group" v-if="currentPanel.selectedFileId">
                    <label>模型</label>
                    <el-table :data="modelsList"
                              highlight-current-row
                              @current-change="handleModelChange"
                              style="width: 100%">
                      <el-table-column prop="ModelName" label="模型名称">
                        <template #default="{ row }">
                          {{ formatNameFront1(row.ModelName) }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </div>

            <!-- 步骤2: 配置单体 -->
            <div v-show="currentStep === 1" class="step-content">
              <div class="pattern-selectors" v-if="currentPanel.selectedModelId">
                <div class="pattern-selector-group">
                  <div class="form-group" v-for="(_, index) in currentPanel.patternCount" :key="index">
                    <label>
                      <span class="status-indicator" :class="{'status-complete': currentPanel.selectedPatternIds[index], 'status-incomplete': !currentPanel.selectedPatternIds[index]}"></span>
                      单体 {{ index + 1 }}
                    </label>

                    <!-- 单体选择表格 -->
                    <el-table :data="patternsList"
                              highlight-current-row
                              @current-change="(row) => handlePatternChange(row.ID, index)"
                              style="width: 100%">
                      <el-table-column prop="PatternName" label="单体名称">
                        <template #default="{ row }">
                          {{ formatName(row.PatternName) }}
                        </template>
                      </el-table-column>
                    </el-table>

                    <el-button type="primary"
                               size="small"
                               @click="openPatternEditor(index)"
                               style="margin-top: 5px;"
                               :disabled="!currentPanel.selectedPatternIds[index]">
                      <el-icon><Edit /></el-icon>编辑位置
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 步骤3: 生成预览 -->
            <div v-show="currentStep === 2" class="step-content">
              <div class="preview-image-container">
                <div class="preview-placeholder">
                  <img src="../../../public/pic/预览图测试.png" style="height: 250px;" />
                </div>
              </div>
            </div>

            <!-- 步骤4: 保存配置 -->
            <div v-show="currentStep === 3" class="step-content">
              <div class="confirmation-section">
                <h3>配置总结</h3>
                <p><strong>项目:</strong> {{ selectedProject.projectName }}</p>
                <p><strong>房型:</strong> {{ currentRoom.label }}</p>
                <p><strong>面板:</strong> {{ currentPanel.label }}</p>
                <p><strong>系列:</strong> {{ selectedSeriesName }}</p>
                <p><strong>模型:</strong> {{ selectedModelName }}</p>

                <div class="pattern-summary" v-for="(patternId, index) in currentPanel.selectedPatternIds" :key="index">
                  <p><strong>单体 {{ index + 1 }}:</strong> {{ getPatternName(patternId) }}</p>
                </div>
              </div>
            </div>

            <!-- 步骤导航按钮 -->
            <div class="step-navigation">
              <el-button v-if="currentStep > 0"
                         @click="currentStep--"
                         size="small">
                上一步
              </el-button>

              <el-button v-if="currentStep < 3"
                         type="primary"
                         @click="nextStep"
                         size="small"
                         :disabled="!canProceedToNextStep">
                下一步
              </el-button>

              <el-button v-if="currentStep === 3"
                         type="success"
                         @click="saveConfiguration"
                         size="small">
                保存配置
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div v-if="!selectedProject" style="width:85%;text-align:right">
        <el-text size="large" type="primary">请先在上方选择项目<el-icon size="40px"><Top /></el-icon></el-text>

      </div>
      <div class="action-buttons">
        <el-button type="primary" size="small" @click="saveConfiguration" v-if="isFormValid">
          <el-icon><DocumentAdd /></el-icon>
          保存配置
        </el-button>
      </div>
    </div>
  </div>

  <!-- 预览图弹窗 -->
  <el-dialog v-model="previewDialogVisible" title="面板预览" width="900px">
    <div class="preview-image-container">
      <!-- 图片占位区 -->
      <div class="preview-placeholder">
        <img src="../../../public/pic/预览图测试.png" style="height: 250px;" />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="previewDialogVisible = false">返回编辑</el-button>
        <el-button type="primary" @click="savePreview">确定保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref, onMounted, computed, watch, inject } from 'vue';
  import { createAxiosInstance } from '../../axios.js'
  import { ElMessage } from 'element-plus'
  import { Promotion, Refresh, Menu, OfficeBuilding, Location, Document, Plus, Delete, Edit, House, Loading, Check, Close, Picture } from '@element-plus/icons-vue'

  const cloudHttp = inject('cloudHttp')
  const localHttp = inject('localHttp')
  const projectList = inject('projectList')
  const selectedProjectId = inject('selectedProjectId')
  const selectedProject = inject('selectedProject')
  const formatDate = inject('formatDate')

  // 数据引用
  const seriesList = ref([]);
  const modelsList = ref([]);
  const patternsList = ref([]);
  /*  const projectList = ref([]);
    const selectedProjectId = ref(null);
    const selectedProject = ref(null);*/
  const expandedKeys = ref([]);
  const roomConfigs = ref([]);
  const currentPanel = ref(null);
  const currentPreviewPatternIndex = ref(null); // 新增：当前预览的单体索引
  const previewDialogVisible = ref(false); // 预览弹窗显示状态
  // 新增状态
  const currentStep = ref(0);
  const currentRoom = ref(null)
  // 新增状态：当前编辑的单体索引
  const currentEditingPatternIndex = ref(null);
  // 监听当前面板变化
  watch(currentPanel, (newPanel) => {
    if (newPanel) {
      currentStep.value = 0;
    }
  });
  // 计算属性：是否可以进入下一步
  const canProceedToNextStep = computed(() => {
    switch (currentStep.value) {
      case 0: // 选择系列和模型
        return currentPanel.value?.selectedModelId;
      case 1: // 配置单体
        return currentPanel.value?.selectedPatternIds.every(id => id);
      case 2: // 生成预览
        return true;
      default:
        return true;
    }
  });
  // 新增计算属性：项目选择是否被锁定
  const isProjectLocked = computed(() => {
    return currentPanel.value && currentPanel.value.selectedFileId;
  });

  // 树形结构数据
  const treeData = computed(() => {
    return roomConfigs.value.map(room => ({
      id: room.id,
      label: room.label,
      type: 'room',
      panels: room.panels,
      editing: room.editing,
      newLabel: room.newLabel,
      children: room.panels.map(panel => ({
        id: panel.id,
        label: panel.label,
        type: 'panel',
        ...panel
      }))
    }));
  });

  const treeProps = { children: 'children', label: 'label' };

  const initPanelConfig = () => ({
    id: `panel-${Date.now()}`,
    label: `面板组合1`,
    selectedFileId: null,
    selectedModelId: null,
    patternCount: 0,
    selectedPatternIds: [],
    loading: false,
    modelDataLoaded: false,
    locationLists: [],
    txtList: [],
    txtEnList: [],
    iconList: [],
    locationSelections: [],
    editing: false,
    newLabel: '',
    direction: '横向'
  });

  // 下一步处理
  const nextStep = () => {
    if (currentStep.value === 0 && currentPanel.value?.selectedModelId) {
      currentStep.value++;
    } else if (currentStep.value === 1 && currentPanel.value?.selectedPatternIds.every(id => id)) {
      currentStep.value++;
    } else if (currentStep.value === 2) {
      currentStep.value++;
    }
  };

  // 获取单体图片路径
  const getPatternImage = (patternId) => {
    if (!patternId) return '';

    // 在单体列表中查找对应的单体
    const pattern = patternsList.value.find(p => p.ID === patternId);
    if (!pattern) return '';

    // 格式化单体名称
    const patternName = formatName(pattern.PatternName);

    // 构建图片路径
    return `/pic/${patternName}.jpg`;
  }

  // 简化数据获取调用
  const getSeries = async () => seriesList.value = await fetchData('PanelSelection/SeriesQuery', {});
  const getModels = async (fileId) => modelsList.value = await fetchData('PanelSelection/ModelQuery', { FID: fileId });
  const getPatterns = async (fileId) => patternsList.value = await fetchData('PanelSelection/PatternQuery', { FID: fileId });
  const getLocationls = async (patternId) => await fetchData('PanelSelection/LocationQuery', { PID: patternId });
  const getTxt = async (fileId) => await fetchData('PanelSelection/TxtQuery', { FID: fileId });
  const getTxtEn = async (fileId) => await fetchData('PanelSelection/TxtEnQuery', { FID: fileId });
  const getIcon = async (fileId) => await fetchData('PanelSelection/IconQuery', { FID: fileId });
  const getFont = async () => await fetchData('PanelSelection/FontQuery', {});

  // 保存配置
  const saveConfiguration = async () => {
    if (!isFormValid.value) {
      ElMessage.warning('请先完成配置');
      return;
    }

    try {
      const configData = {
        projectId: selectedProject.value.id,
        roomConfigs: roomConfigs.value.map(room => ({
          id: room.id,
          label: room.label,
          panels: room.panels.map(panel => ({
            id: panel.id,
            label: panel.label,
            selectedFileId: panel.selectedFileId,
            selectedModelId: panel.selectedModelId,
            patternCount: panel.patternCount,
            selectedPatternIds: panel.selectedPatternIds,
            locationSelections: panel.locationSelections
          }))
        }))
      };

      const rs = await localHttp.post('PanelSelection/SaveConfiguration', JSON.stringify(configData));
      rs.data.success ? ElMessage.success('配置保存成功') : ElMessage.error('配置保存失败');
    } catch (error) {
      console.error('保存配置失败:', error);
      ElMessage.error('保存配置失败');
    }
  };

  // 获取项目列表
  const getProject = async () => {
    try {
      const rs = await cloudHttp.post('AasProjectInfoes/Get_ProjectByStatusCode');
      projectList.value = rs.data.response.sort((a, b) => b.id - a.id);
    } catch (error) {
      console.error('获取项目列表失败:', error);
      ElMessage.error('获取项目列表失败');
    }
  }

  // 删除节点权限检查
  const isAllowDel = (data) => {
    return (data.type === 'room' && roomConfigs.value.length > 1) ||
      (data.type === 'panel' && getRoomByPanel(data).panels.length > 1)
  }

  // 安全获取房型的方法
  const getRoomByPanel = (panelNode) => {
    if (!panelNode || !panelNode.id) {
      console.warn('面板节点无效');
      return roomConfigs.value[0] || null;
    }

    for (const room of roomConfigs.value) {
      if (room.panels && room.panels.find(p => p.id === panelNode.id)) {
        return room;
      }
    }

    console.warn('未找到面板所属的房型');
    return roomConfigs.value[0] || null;
  };
  // 安全保存方法
  const safeSaveRoomName = async (roomId, newName) => {
    if (!roomId || !newName) {
      console.warn('房型ID或名称为空');
      return;
    }

    try {
      const rs = await localHttp.post('PanelSelection/SaveRoomName', {
        roomId: roomId,
        newName: newName
      });

      if (!rs.data.isok) {
        throw new Error(rs.data.message || '保存房型名称失败');
      }
    } catch (error) {
      console.error('保存房型名称失败:', error);
      throw error;
    }
  };

  // 删除节点
  const removeNode = (node) => {
    if (node.type === 'room') {
      const index = roomConfigs.value.findIndex(r => r.id === node.id);
      if (index !== -1 && roomConfigs.value.length > 1) {
        roomConfigs.value.splice(index, 1);
      }
    } else if (node.type === 'panel') {
      const room = getRoomByPanel(node);
      if (room) {
        const panelIndex = room.panels.findIndex(p => p.id === node.id);
        if (panelIndex !== -1 && room.panels.length > 1) {
          if (currentPanel.value?.id === node.id) currentPanel.value = null;
          room.panels.splice(panelIndex, 1);
        }
      }
    }
  }

  // 添加房型
  const addRoomType = () => {
    const newRoomId = `room-${Date.now()}`;
    const newRoom = {
      id: newRoomId,
      label: `房型 ${roomConfigs.value.length + 1}`,
      panels: [initPanelConfig()],
      editing: false,
      newLabel: ''
    };
    roomConfigs.value.push(newRoom);
    expandedKeys.value.push(newRoomId);
  }

  // 添加面板
  const addPanel = (roomNode) => {
    const room = roomConfigs.value.find(r => r.id === roomNode.id);
    if (room) {
      const newPanel = initPanelConfig();
      newPanel.label = `面板 ${room.panels.length + 1}`;
      room.panels.push(newPanel);
      if (!expandedKeys.value.includes(roomNode.id)) {
        expandedKeys.value.push(roomNode.id);
      }
    }
  }
  watch(selectedProjectId, (newPanel) => {
    if (newPanel) {
      handleProjectChange(newPanel)
    }
  });
  // 处理项目变更
  const handleProjectChange = async (projectId) => {
    if (!projectId) {
      selectedProject.value = null;
      roomConfigs.value = [];
      currentPanel.value = null;
      currentRoom.value = null;
      expandedKeys.value = [];
      return;
    }

    selectedProject.value = projectList.value.find(p => p.id === projectId);
    if (!selectedProject.value) {
      ElMessage.warning('未找到选中的项目');
      return;
    }

    try {
      // 传递正确的参数格式
      const rs = await localHttp.post('PanelSelection/GetProjectConfiguration', {
        projectId: parseInt(projectId)
      });

      if (rs.data.isok && rs.data.response) {
        // 确保响应是有效的JSON
        const responseData = rs.data.response === "[]" ? [] : JSON.parse(rs.data.response);
        roomConfigs.value = responseData;

        // 如果有配置数据，设置当前房型和面板
        if (roomConfigs.value.length > 0) {
          currentRoom.value = roomConfigs.value[0];
          if (currentRoom.value.panels && currentRoom.value.panels.length > 0) {
            currentPanel.value = currentRoom.value.panels[0];
          }
        } else {
          // 没有配置数据，初始化默认配置
          initializeDefaultRoomConfigs();
        }
      } else {
        // 后端返回成功但没有数据，初始化默认配置
        initializeDefaultRoomConfigs();
      }
    } catch (error) {
      console.error('加载项目配置失败:', error);
      ElMessage.error('加载项目配置失败: ' + (error.message || '未知错误'));
      // 出错时也初始化默认配置
      initializeDefaultRoomConfigs();
    }
  };

  // 初始化默认房型配置
  const initializeDefaultRoomConfigs = () => {
    roomConfigs.value = [];

    // 确保 selectedProject.value 存在
    if (!selectedProject.value || !selectedProject.value.id) {
      console.error('无法初始化房型配置：项目信息不完整');
      ElMessage.error('项目信息不完整，无法初始化配置');
      return;
    }

    const roomTypeCount = selectedProject.value.roomTypeCount || 1;

    for (let i = 0; i < roomTypeCount; i++) {
      // 使用更安全的ID生成方式
      const roomId = `room-${selectedProject.value.id}-${i}-${Date.now()}`;
      const panelId = `panel-${roomId}-0`;

      roomConfigs.value.push({
        id: roomId,
        label: `房型 ${i + 1}`,
        panels: [{
          ...initPanelConfig(),
          id: panelId
        }],
        editing: false,
        newLabel: ''
      });
    }

    // 设置默认的当前房型和面板
    if (roomConfigs.value.length > 0) {
      currentRoom.value = roomConfigs.value[0];
      if (currentRoom.value.panels && currentRoom.value.panels.length > 0) {
        currentPanel.value = currentRoom.value.panels[0];
      }
    }
  };

  // 节点点击事件 - 更新当前房型
  const handleNodeClick = (data) => {
    if (data.type === 'panel') {
      currentPanel.value = data;

      // 安全地查找当前面板所属的房型
      const room = roomConfigs.value.find(r =>
        r.panels && r.panels.some(p => p.id === data.id)
      );

      if (room) {
        currentRoom.value = room;
      } else {
        console.warn('未找到面板所属的房型，使用第一个房型');
        currentRoom.value = roomConfigs.value[0] || null;
      }

      currentPreviewPatternIndex.value = null;
      currentEditingPatternIndex.value = null;
    } else if (data.type === 'room') {
      currentRoom.value = data;
      const index = expandedKeys.value.indexOf(data.id);
      if (index > -1) {
        expandedKeys.value.splice(index, 1);
      } else {
        expandedKeys.value.push(data.id);
      }
    }
  };

  // 开始编辑节点
  const startEditing = (node) => {
    node.editing = true;
    node.newLabel = node.label;
  }

  // 获取当前选择的系列名称
  const selectedSeriesName = computed(() => {
    if (!currentPanel.value?.selectedFileId) return '';
    const series = seriesList.value.find(s => s.ID === currentPanel.value.selectedFileId);
    return series ? formatName(series.Series) + '_' + series.Version : '';
  });

  // 获取当前选择的模型名称
  const selectedModelName = computed(() => {
    if (!currentPanel.value?.selectedModelId) return '';
    const model = modelsList.value.find(m => m.ID === currentPanel.value.selectedModelId);
    return model ? formatNameFront1(model.ModelName) : '';
  });

  // 获取单体名称
  const getPatternName = (patternId) => {
    if (!patternId) return '';
    const pattern = patternsList.value.find(p => p.ID === patternId);
    return pattern ? formatName(pattern.PatternName) : '';
  };

  // 修改节点名称后立即保存
  const finishEditing = async (node) => {
    if (!node) {
      console.error('节点为空，无法完成编辑');
      return;
    }

    if (node.newLabel?.trim()) {
      const originalLabel = node.label;
      node.label = node.newLabel.trim();

      try {
        if (node.type === 'room') {
          await safeSaveRoomName(node.id, node.label);
        } else if (node.type === 'panel') {
          const room = getRoomByPanel(node);
          if (room) {
            await safeSavePanelName(room.id, node.id, node.label);
          } else {
            console.warn('未找到房型，无法保存面板名称');
          }
        }
      } catch (error) {
        // 保存失败，恢复原始名称
        node.label = originalLabel;
        console.error('保存名称失败:', error);
        ElMessage.error('保存名称失败: ' + error.message);
      }
    }
    node.editing = false;
  };

  // 选择系列后立即保存
  const handleFileChange = async (file) => {
    if (!file || !currentPanel.value) return;

    currentPanel.value.selectedFileId = file.ID;
    currentPanel.value.loading = true;

    try {
      // 保存系列选择
      await saveSeriesSelection(currentRoom.value.id, currentPanel.value.id, file.ID);

      // 加载模型和图案
      await getModels(file.ID);
      await getPatterns(file.ID);
    } catch (error) {
      console.error('处理系列变更失败:', error);
      ElMessage.error('处理系列变更失败');
    } finally {
      currentPanel.value.loading = false;
    }
  };

  // 选择模型后立即保存
  const handleModelChange = async (model) => {
    if (!model || !currentPanel.value) return;

    currentPanel.value.selectedModelId = model.ID;
    currentPanel.value.loading = true;

    try {
      // 保存模型选择
      await saveModelSelection(currentRoom.value.id, currentPanel.value.id, model.ID);

      // 重置单体相关数据
      currentPanel.value.patternCount = model?.PanelCount || 0;
      currentPanel.value.selectedPatternIds = Array(currentPanel.value.patternCount).fill(null);
      currentPanel.value.locationLists = Array(currentPanel.value.patternCount).fill([]);
      currentPanel.value.locationSelections = Array(currentPanel.value.patternCount).fill([]);
      currentPreviewPatternIndex.value = null;
      currentEditingPatternIndex.value = null;

      // 设置布局方向
      currentPanel.value.direction = model?.Direction || '横向';

      // 使用系列ID获取文本和图标
      const fileId = currentPanel.value.selectedFileId;
      if (fileId) {
        currentPanel.value.txtList = await getTxt(fileId);
        currentPanel.value.txtEnList = await getTxtEn(fileId);
        currentPanel.value.iconList = await getIcon(fileId);
      }

      // 重置模型数据加载状态
      currentPanel.value.modelDataLoaded = false;
    } catch (error) {
      console.error('处理模型变更失败:', error);
      ElMessage.error('处理模型变更失败');
    } finally {
      currentPanel.value.loading = false;
    }
  };

  // 选择单体后立即保存
  const handlePatternChange = async (patternId, index) => {
    if (!currentPanel.value || !patternId) return;

    currentPanel.value.loading = true;

    try {
      // 保存单体选择
      await savePatternSelection(
        currentRoom.value.id,
        currentPanel.value.id,
        index,
        patternId
      );

      // 加载位置信息
      const locations = await getLocationls(patternId);

      // 存储位置信息
      currentPanel.value.locationLists[index] = locations;

      // 初始化位置选择配置
      currentPanel.value.locationSelections[index] = locations.map(location => ({
        locationId: location.ID,
        txtId: null,
        iconId: null
      }));

      // 检查是否所有单体都已选择并加载位置信息
      const allPatternsLoaded = currentPanel.value.selectedPatternIds.every(p => p) &&
        currentPanel.value.locationLists.every(list => list.length > 0);

      if (allPatternsLoaded) {
        currentPanel.value.modelDataLoaded = true;
      }
    } catch (error) {
      console.error('处理单体变更失败:', error);
      ElMessage.error('处理单体变更失败');
    } finally {
      currentPanel.value.loading = false;
    }
  };

  // 用_分割字符串，取第2段
  const formatName = (name) => {
    if (!name) return '';
    const parts = name.split('_');
    return parts.length > 1 ? parts[1] : name;
  }

  // 去除第一段
  const formatNameFront1 = (name) => {
    if (!name) return '';
    const parts = name.split('_')
    return parts.slice(1).join('_')
  }

  // 去除前二段
  const formatNameFront2 = (name) => {
    if (!name) return '';
    const parts = name.split('_')
    return parts.slice(2).join('_')
  }

  // 发送绘图需求
  const SendDrawingRequirement = async () => {
    /*    if (!isFormValid.value) {
          ElMessage.warning('请先完成配置');
          return;
        }
    */
    try {
      ElMessage.success('正在生成面板设计图，请稍候...');
      const d = new Date();
      const panel = currentPanel.value;

      // 获取当前选中的模型
      const model = modelsList.value.find(m => m.ID === panel.selectedModelId);
      if (!model) {
        ElMessage.error('未找到模型信息');
        return;
      }

      // 获取当前选中的系列
      const series = seriesList.value.find(s => s.ID === panel.selectedFileId);
      if (!series) {
        ElMessage.error('未找到系列信息');
        return;
      }

      // 构建PatternList
      const patternList = [];
      for (let i = 0; i < panel.selectedPatternIds.length; i++) {
        const patternId = panel.selectedPatternIds[i];
        const pattern = patternsList.value.find(p => p.ID === patternId);
        if (!pattern) {
          ElMessage.error(`未找到单体${i + 1}的信息`);
          continue;
        }

        // 构建该单体的位置列表
        const locationList = [];
        const locations = panel.locationLists[i];
        const selections = panel.locationSelections[i];

        // 确保位置列表和选择列表存在且长度相同
        if (locations && selections && locations.length === selections.length) {
          for (let j = 0; j < locations.length; j++) {
            const location = locations[j];
            const selection = selections[j];
            let shapeNumber = '';

            // 根据位置类型获取替换内容的ShapeNumber
            if (location.Type === 1 || location.Type === 4) {
              // 图标或Logo
              const icon = panel.iconList.find(icon => icon.ID === selection.iconId);
              if (icon) {
                shapeNumber = icon.ShapeNumber;
              }
            } else if (location.Type === 2) {
              // 中文字
              const txt = panel.txtList.find(txt => txt.ID === selection.txtId);
              if (txt) {
                shapeNumber = txt.ShapeNumber;
              }
            } else if (location.Type === 3) {
              // 英文字
              const txtEn = panel.txtEnList.find(txt => txt.ID === selection.txtId);
              if (txtEn) {
                shapeNumber = txtEn.ShapeNumber;
              }
            }

            // 添加到位置列表
            locationList.push({
              IndexNumber: location.IndexNum.toString(), // 使用位置的IndexNum字段
              ShapeNumber: shapeNumber
            });
          }
        }
        var indexNum = i + 1;
        patternList.push({
          IndexNumber: indexNum.toString(), // 使用单体的IndexNum字段
          ShapeNumber: pattern.ShapeNumber,
          LocationList: locationList
        });
      }

      // 生成图片编号：酒店名称+当前UTC秒级时间戳
      const utcTimestamp = new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14);
      const pictureNum = `${selectedProject.value.projectName.replace(/\s+/g, '_')}_${utcTimestamp}`;
      const QueryDate = {
        User: 'admin',
        Process: 0,
        PictureNum: pictureNum,
        ProjectName: selectedProject.value.projectName,
        ProjectId: selectedProject.value.projectCode,
        MaterialLibraryName: series.FileName, // 使用系列的FileName字段
        TemplateName: model.ModelName, // 使用格式化后的模型名称
        TemplateNameIndex: model.ShapeNumber,
        PatternList: patternList,
      };

      console.log('发送绘图请求:', QueryDate);
      //return
      const rs = await localHttp.post('PanelSelection/SendToCDR', JSON.stringify(QueryDate));
      rs.data.isok ? ElMessage.success('面板设计图生成成功！') : ElMessage.error('面板设计图生成失败');
    } catch (error) {
      console.error('生成面板设计图失败:', error);
      ElMessage.error('生成面板设计图时出错');
    }
  }

  // 重置表单
  const resetForm = () => {
    selectedProjectId.value = null;
    selectedProject.value = null;
    roomConfigs.value = [];
    currentPanel.value = null;
    currentEditingPatternIndex.value = null;
    currentPreviewPatternIndex.value = null;
  }

  // 表单验证
  const isFormValid = computed(() => {
    return selectedProject.value && roomConfigs.value.length > 0 &&
      roomConfigs.value.every(room => room.panels.length > 0 &&
        room.panels.every(panel =>
          panel.selectedModelId &&
          panel.selectedPatternIds.length === panel.patternCount &&
          panel.selectedPatternIds.every(p => p) &&
          panel.locationLists.every(list => list.length > 0) &&
          panel.locationSelections.every(selections =>
            selections && selections.length > 0
          )
        )
      );
  })

  // 打开单体编辑器
  const openPatternEditor = (patternIndex) => {
    currentEditingPatternIndex.value = patternIndex;
    currentPreviewPatternIndex.value = patternIndex; // 设置预览索引为当前编辑的单体
  }

  // 关闭单体编辑器
  const closePatternEditor = () => {
    currentEditingPatternIndex.value = null;
    // 保留预览图片
  }

  // 保存单体编辑
  const savePatternEdits = () => {
    ElMessage.success('单体编辑已保存');
    currentEditingPatternIndex.value = null;
  }

  // 格式化位置类型
  const formatLocationType = (type) => {
    switch (type) {
      case 1: return '图标';
      case 2: return '中文字';
      case 3: return '英文字';
      case 4: return 'Logo';
      default: return '未知类型';
    }
  }

  // 检查选项是否禁用
  const isOptionDisabled = (option, type, currentIndex) => {
    if (!currentPanel.value || currentEditingPatternIndex.value === null) return false;

    // 获取当前单体的位置选择
    const selections = currentPanel.value.locationSelections[currentEditingPatternIndex.value];

    // 遍历所有位置选择
    for (let i = 0; i < selections.length; i++) {
      // 跳过当前行
      if (i === currentIndex) continue;

      const selection = selections[i];
      const location = currentPanel.value.locationLists[currentEditingPatternIndex.value][i];

      // 检查是否同类型
      if (location.Type === type) {
        // 检查图标类型
        if ((type === 1 || type === 4) && selection.iconId === option.ID) {
          return true;
        }
        // 检查文本类型
        if ((type === 2 || type === 3) && selection.txtId === option.ID) {
          return true;
        }
      }
    }

    return false;
  }

  // 检查所有单体是否已配置完成
  const isAllPatternsConfigured = computed(() => {
    if (!currentPanel.value || !currentPanel.value.modelDataLoaded) {
      return false;
    }

    // 检查所有单体位置是否都已配置
    for (let i = 0; i < currentPanel.value.locationSelections.length; i++) {
      const selections = currentPanel.value.locationSelections[i];
      const locationList = currentPanel.value.locationLists[i];

      if (!selections || selections.length !== locationList.length) {
        return false;
      }

      for (let j = 0; j < selections.length; j++) {
        const selection = selections[j];
        const location = locationList[j];

        if (location.Type === 1 || location.Type === 4) {
          // 图标类型
          if (!selection.iconId) return false;
        } else if (location.Type === 2 || location.Type === 3) {
          // 文本类型
          if (!selection.txtId) return false;
        }
      }
    }

    return true;
  });

  // 封装数据获取方法
  const fetchData = async (endpoint, query) => {
    try {
      let rs;
      if (query) {
        rs = await localHttp.post(endpoint, JSON.stringify(query));
      } else {
        rs = await localHttp.post(endpoint);
      }
      return JSON.parse(rs.data.response);
    } catch (error) {
      console.error(`获取${endpoint}数据失败:`, error);
      ElMessage.error(`获取${endpoint}数据失败`);
      return [];
    }
  };

  // 新增API调用方法
  const saveRoomName = async (roomId, newName) => {
    try {
      if (!currentRoom.value) {
        console.error('currentRoom.value is null');
        return;
      }

      const rs = await localHttp.post('PanelSelection/SaveRoomName', JSON.stringify({
        roomId,
        newName
      }));

      if (!rs.data.isok) {
        throw new Error(rs.data.message || '保存房型名称失败');
      }
    } catch (error) {
      throw error;
    }
  };

  const savePanelName = async (roomId, panelId, newName) => {
    try {
      const rs = await localHttp.post('PanelSelection/SavePanelName', JSON.stringify({
        roomId,
        panelId,
        newName
      }));
      if (!rs.data.isok) {
        throw new Error(rs.data.message || '保存面板名称失败');
      }
    } catch (error) {
      throw error;
    }
  };

  const saveSeriesSelection = async (roomId, panelId, seriesId) => {
    try {
      const rs = await localHttp.post('PanelSelection/SaveSeriesSelection', JSON.stringify({
        roomId,
        panelId,
        seriesId
      }));
      if (!rs.data.isok) {
        throw new Error(rs.data.message || '保存系列选择失败');
      }
    } catch (error) {
      throw error;
    }
  };

  const saveModelSelection = async (roomId, panelId, modelId) => {
    try {
      const rs = await localHttp.post('PanelSelection/SaveModelSelection', JSON.stringify({
        roomId,
        panelId,
        modelId
      }));
      if (!rs.data.isok) {
        throw new Error(rs.data.message || '保存模型选择失败');
      }
    } catch (error) {
      throw error;
    }
  };

  const savePatternSelection = async (roomId, panelId, patternIndex, patternId) => {
    try {
      const rs = await localHttp.post('PanelSelection/SavePatternSelection', JSON.stringify({
        roomId,
        panelId,
        patternIndex,
        patternId
      }));
      if (!rs.data.isok) {
        throw new Error(rs.data.message || '保存单体选择失败');
      }
    } catch (error) {
      throw error;
    }
  };


  // 打开预览对话框
  const openPreviewDialog = () => {
    SendDrawingRequirement()
    previewDialogVisible.value = true;
  }

  // 保存预览图（暂未实现）
  const savePreview = () => {
    ElMessage.info('保存预览图功能暂未实现');
    previewDialogVisible.value = false;
  }

  onMounted(async () => {
    await Promise.all([
      //getProject(),
      getSeries()
    ]);
  });
</script>

<style scoped>
  .panel-container {
    margin: 0 auto;
    height: 100%;
    padding: 5px;
    font-size: 0.9rem;
  }

  .step-content {
    margin-top: 20px;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    background-color: #f8fafc;
  }

  .step-navigation {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 10px;
  }

  .confirmation-section {
    padding: 15px;
    background-color: white;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .pattern-summary {
    margin-top: 10px;
    padding-left: 15px;
    border-left: 3px solid #409eff;
  }

  .selection-card {
    height: 100%;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 8px;
    margin-bottom: 8px;
    transition: box-shadow 0.3s ease;
  }

    .selection-card:hover {
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
    }

  .card-title {
    font-size: 0.9rem;
    border-bottom: 1px solid #eaeef5;
    display: flex;
    align-items: center;
  }

    .card-title .el-icon {
      margin-right: 8px;
      color: #409eff;
      font-size: 0.9rem;
    }

  .form-group {
    margin-bottom: 0px;
  }

    .form-group label {
      display: block;
      margin-bottom: 6px;
      font-weight: 500;
      color: #5a6c84;
      font-size: 0.85rem;
    }

  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 12px;
    background-color: #f8fafc;
    border-radius: 6px;
    margin: 12px 0;
    font-size: 0.9rem;
  }

  .loading-icon {
    margin-right: 8px;
    animation: rotate 2s linear infinite;
    color: #409eff;
    font-size: 0.9rem;
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(360deg);
    }
  }

  .pattern-editor {
    margin-top: 12px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    padding: 10px;
    background-color: #f8fafc;
  }

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-size: 0.9rem;
    font-weight: 600;
  }

    .section-title .el-icon {
      margin-right: 8px;
      font-size: 0.9rem;
    }

  .action-buttons {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    gap: 12px;
  }

  .details {
    margin-top: 4px;
    border-radius: 6px;
    overflow: hidden;
    font-size: 0.85rem;
  }

  .room-config {
    margin-top: 15px;
  }

  .tree-layout {
    display: flex;
    gap: 15px;
    margin-top: 15px;
  }

  .tree-container {
    height: 50vh;
    width: 15%;
    overflow-y: auto;
    border: 1px solid #ebeef5;
  }

  .panel-config {
    width: 85%;
  }

  .tree-node {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 4px 0;
  }

  .node-label {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.9rem;
  }

  .node-actions {
    display: flex;
    gap: 4px;
  }

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
    padding-bottom: 4px;
    border-bottom: 1px solid #eaeaea;
  }

  .panel-title {
    font-size: 0.9rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  /* 模型配置容器 */
  .model-config-container {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;
  }

  .model-selectors {
    flex: 1;
  }

  /* 单体图片预览 */
  .pattern-image-preview {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    overflow: hidden;
    background-color: #f8fafc;
    width: auto; /* 宽度自适应 */
  }

  .preview-title {
    padding: 8px;
    background-color: #409eff;
    color: white;
    font-size: 0.85rem;
    text-align: center;
  }

  .image-container {
    height: 320px; /* 固定高度 */
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    width: auto; /* 宽度自适应 */
  }

    .image-container img {
      max-height: 100%; /* 高度固定为320px */
      width: auto; /* 宽度自适应 */
      object-fit: contain;
    }

  .model-selectors {
    margin-bottom: 15px;
  }

  .selector-row {
    display: flex;
    gap: 15px;
    margin-bottom: 12px;
  }

  .pattern-selectors {
    display: table-cell;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 12px;
  }

  .pattern-selector-group {
    display: flex;
  }

    /* 竖向布局样式 */
    .pattern-selector-group.vertical-layout {
      flex-direction: column;
      gap: 0;
    }

    .pattern-selector-group .form-group {
      border: 1px solid #DCDFE6;
      border-radius: 0;
      padding: 10px;
      background-color: #fff;
      min-width: 180px;
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      border-right: none;
    }

      /* 横向布局下的第一个元素 */
      .pattern-selector-group .form-group.first-item {
        border-top-left-radius: 6px;
        border-bottom-left-radius: 6px;
        border-left: 1px solid #DCDFE6;
      }

      /* 横向布局下的最后一个元素 */
      .pattern-selector-group .form-group.last-item {
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
        border-right: 1px solid #DCDFE6;
      }

    /* 竖向布局下的第一个元素 */
    .pattern-selector-group.vertical-layout .form-group.vertical-first-item {
      border-top-left-radius: 6px;
      border-top-right-radius: 6px;
      border-top: 1px solid #DCDFE6;
    }

    /* 竖向布局下的最后一个元素 */
    .pattern-selector-group.vertical-layout .form-group.vertical-last-item {
      border-bottom-left-radius: 6px;
      border-bottom-right-radius: 6px;
      border-bottom: 1px solid #DCDFE6;
    }

    /* 竖向布局下的中间元素 */
    .pattern-selector-group.vertical-layout .form-group:not(.vertical-first-item):not(.vertical-last-item) {
      border-top: none;
      border-bottom: none;
    }

    .pattern-selector-group .form-group > * {
      width: 100%;
      margin-bottom: 5px;
    }

      .pattern-selector-group .form-group > *:last-child {
        margin-bottom: 0;
      }

  .status-indicator {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 6px;
  }

  .status-complete {
    background-color: #67c23a;
  }

  .status-incomplete {
    background-color: #e6a23c;
  }

  :deep(.el-collapse) {
    --el-collapse-header-height: none;
  }

  /* 新增样式：单体编辑区域布局 */
  .editor-content {
    display: flex;
    gap: 15px;
    width: 100%;
  }

  .editor-table {
    flex: 1;
    width: calc(100% - 600px); /* 表格宽度限制 */
  }

  .editor-preview {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    overflow: hidden;
    background-color: #f8fafc;
    width: 600px; /* 固定宽度 */
  }

    .editor-preview .preview-title {
      padding: 8px;
      background-color: #409eff;
      color: white;
      font-size: 0.85rem;
      text-align: center;
    }

    .editor-preview .image-container {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px;
    }

      .editor-preview .image-container img {
        max-height: 100%;
        max-width: 100%;
        object-fit: contain;
      }

  /* 预览图占位区 */
  .preview-placeholder {
    width: 860px;
    height: 400px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    color: #909399;
    font-size: 14px;
  }

    .preview-placeholder .el-icon {
      font-size: 48px;
      margin-bottom: 15px;
      color: #c0c4cc;
    }
</style>
