<template>
  <div style="padding: 20px">

    <!-- VueFlow 主画布 -->
    <VueFlow style="width: 100%; height: 600px">
      <template #node-default="{ id, data }">
        <div class="custom-node">
          <div class="node-content">
            <!-- 图标显示 -->
            <div style="font-size: 30px">
              <img
                v-if="data.stepIcon && data.stepIcon.startsWith('http')"
                :src="data.stepIcon"
                :alt="data.stepTitleShort"
                style="width: 40px; height: 40px; object-fit: contain"
              />
              <span v-else>{{ data.stepIcon || '📋' }}</span>
            </div>
            <div style="font-weight: bold; font-size: 14px">
              {{ data.stepTitleShort || '无标题' }}
            </div>
            <div style="font-size: 25px">
              {{ String.fromCharCode(9311 + (data.stepIndex || 1)) }}
            </div>
          </div>

          <!-- 四个连接点 -->
          <Handle type="target" position="top" :id="`${id}-top`" class="handle handle-top" />
          <Handle
            type="source"
            position="bottom"
            :id="`${id}-bottom`"
            class="handle handle-bottom"
          />
          <Handle type="target" position="left" :id="`${id}-left`" class="handle handle-left" />
          <Handle type="source" position="right" :id="`${id}-right`" class="handle handle-right" />
        </div>
      </template>
    </VueFlow>

    <!-- 节点表单内容 -->
    <div
      v-if="showForm && selectedNodeId"
      style="margin-top: 20px; padding: 20px; border: 1px solid #ccc"
    >
      <h3>节点配置（{{ selectedNodeId }}）</h3>
      <div style="display: flex; gap: 20px">
        <el-form label-width="155px">
          <el-form-item label="图标">
            <el-popover placement="bottom" trigger="click" width="230">
              <!-- 图标选择面板 -->
              <div style="display: flex; flex-wrap: wrap; gap: 8px">
                <div
                  v-for="icon in iconOptions"
                  :key="icon.value"
                  @click="() => selectIcon(formData, icon.value)"
                  :style="{
                    border:
                      formData.stepIcon === icon.value ? '2px solid #409EFF' : '1px solid #ccc',
                    borderRadius: '4px',
                    padding: '2px',
                    cursor: 'pointer'
                  }"
                >
                  <img
                    :src="icon.value"
                    :alt="icon.name"
                    style="width: 28px; height: 28px; object-fit: contain"
                  />
                </div>
              </div>

              <!-- 触发元素：当前图标或按钮 -->
              <template #reference>
                <div style="cursor: pointer; display: inline-block">
                  <img
                    v-if="formData.stepIcon"
                    :src="formData.stepIcon"
                    style="width: 32px; height: 32px; border-radius: 4px; border: 1px solid #ccc"
                  />
                  <el-button v-else type="primary" size="small">选择图标</el-button>
                </div>
              </template>
            </el-popover>
          </el-form-item>

          <el-form-item label="标题">
            <el-input
              v-model="formData.stepTitle"
              placeholder="标题"
              size="small"
              @blur="handleFormChange"
            />
          </el-form-item>

          <el-form-item label="标题缩写">
            <el-input
              v-model="formData.stepTitleShort"
              placeholder="标题缩写"
              size="small"
              @blur="handleFormChange"
            />
          </el-form-item>

          <el-form-item label="确认方式">
            <el-select
              v-model="formData.confirmType"
              placeholder="请选择确认方式"
              @change="handleFormChange"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYS_STEP_CONFIRMTYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="确认角色" v-if="formData.confirmType == '2'">
            <el-select
              v-model="formData.confirmRoleCode"
              placeholder="请选择确认角色"
              @change="handleFormChange"
              filterable
              clearable
              @clear="handleRoleClear(formData)"
            >
              <el-option
                v-for="dict in RoleOptions"
                :key="dict.code"
                :label="dict.name"
                :value="dict.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="确认人员" v-if="formData.confirmType == '2'">
            <el-select
              v-model="formData.confirmUser"
              placeholder="请选择确认人员"
              @change="handleFormChange"
              filterable
              clearable
            >
              <el-option
                v-for="dict in UserOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="步骤功能">
            <div class="step-function-container">
              <div v-if="formData.enableCancelJob" class="function-item">

                <el-input
                  v-model="formData.cancelJobValue"
                  placeholder="取消作业"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>
              <!-- 设置锁定人 -->
              <div v-if="formData.enableSetLocker" class="function-item">
                <el-input
                  v-model="formData.setLockerValue"
                  placeholder="设置锁定人"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>

              <!-- 设置共锁人 -->
              <div v-if="formData.enableSetColocker" class="function-item">
                <el-input
                  v-model="formData.setColockerValue"
                  placeholder="设置共锁人"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>
              <!-- 添加共锁人 -->
              <div v-if="formData.enableAddColocker" class="function-item">

                <el-input
                  v-model="formData.addColockerValue"
                  placeholder="添加共锁人"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>

              <!-- 添加共锁人后跳转步骤 -->
              <div v-if="formData.enableAddColocker && formData.gotoStepAfterAddingColocker" class="function-item">

                <el-input-number
                  v-model="formData.gotoStepAfterAddingColocker"
                  :min="1"
                  size="small"
                  placeholder="添加共锁人后跳转步骤"
                  disabled
                  style="width: 120px"
                />
              </div>

              <!-- 减少共锁人 -->
              <div v-if="formData.enableReduceColocker" class="function-item">
                <el-input
                  v-model="formData.reduceColockerValue"
                  placeholder="减少共锁人"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>

              <!-- 上锁 -->
              <div v-if="formData.enableLock" class="function-item">
                <el-input
                  v-model="formData.lockValue"
                  placeholder="上锁"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>

              <!-- 共锁 -->
              <div v-if="formData.enableColock" class="function-item">
                <el-input
                  v-model="formData.colockValue"
                  placeholder="共锁"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>

              <!-- 解除共锁 -->
              <div v-if="formData.enableReleaseColock" class="function-item">
                <el-input
                  v-model="formData.releaseColockValue"
                  placeholder="解除共锁"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>

              <!-- 解锁 -->
              <div v-if="formData.enableUnlock" class="function-item">
                <el-input
                  v-model="formData.unlockValue"
                  placeholder="解锁"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>

              <!-- 结束作业 -->
              <div v-if="formData.enableEndJob" class="function-item">
                <el-input
                  v-model="formData.endJobValue"
                  placeholder="结束作业"
                  disabled
                  size="small"
                  style="width: 200px"
                />
              </div>

            </div>
          </el-form-item>

        </el-form>

        <!-- 右侧富文本 -->
        <div style="flex: 1">
          <label style="font-weight: bold; display: block; margin-bottom: 8px">步骤操作说明</label>
          <TinyMCE
            v-model:value="formData.stepDescription"
            :height="700"
            placeholder="请输入内容..."
            @change="handleFormChange"
            @update:value="handleContentChange"
          />
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, nextTick } from 'vue'
import { VueFlow, useVueFlow, Position, addEdge, Handle } from '@vue-flow/core'
import '@vue-flow/core/dist/style.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import TinyMCE from '@/components/TinyMCE/index.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getIsSystemAttributeByKey } from '@/api/basic/configuration/index'
import {
  getSopWorkflowStepPage,
  updateSopWorkflowStep,
} from '@/api/sop/sopStep'

import { getRolePage } from '@/api/system/role'
import { getRoleUser } from '@/api/system/user'

const route = useRoute()
const {
  addNodes,
  addEdges,
  onNodeClick,
  onNodeContextMenu,
  zoomTo,
  updateNode,
  onConnect,
} = useVueFlow()
const props = defineProps({
  sopId: {
    type: [String, Number],
    default: null
  },


})
const selectedNodeId = ref<string | null>(null)
const showForm = ref(false)
const nodeIdCounter = ref(1)
const nodes = ref([])
const edges = ref([]) // 存储连接线
const iconOptions = ref([])
const RoleOptions = ref([])
const UserOptions = ref([])

// 默认数据结构
const formData = reactive({
  sopId: route.query.sopId || props.sopId,
  stepTemplateId: undefined,
  stepIndex: 0,
  stepName: undefined,
  stepTitle: undefined,
  stepTitleShort: undefined,
  stepDescription: undefined,
  confirmType: undefined,
  confirmRoleCode: undefined,
  confirmUser: undefined,
  enableCancelJob: undefined,
  enableSetLocker: undefined,
  enableSetColocker: undefined,
  enableAddColocker: undefined,
  gotoStepAfterAddingColocker: undefined,
  enableReduceColocker: undefined,
  enableLock: undefined,
  enableColock: undefined,
  enableReleaseColock: undefined,
  enableUnlock: undefined,
  enableEndJob: undefined,
  id: undefined,
  stepIcon: undefined
})

// 防抖函数
const debounce = (func, wait) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}
// 表格图标切换
const selectIcon = (formData, iconUrl) => {
  formData.stepIcon = iconUrl
  saveFormData(formData) // 你已有的接口保存方法
}

// 初始化步骤数据并渲染节点
const initTableData = async () => {
  try {
    if (props.sopId || route.query.sopId) {
      const data = await getSopWorkflowStepPage({
        pageNo: 1,
        pageSize: -1,
        sopId: route.query.sopId || props.sopId
      })

      if (Array.isArray(data.list) && data.list.length > 0) {
        // 按 stepIndex 从小到大排序
        const sortedData = data.list.sort((a, b) => {
          const aIndex = a.stepIndex || 0
          const bIndex = b.stepIndex || 0
          return aIndex - bIndex
        })

        console.log(
          '初始化数据完成，已按 stepIndex 排序:',
          sortedData.map((row) => row.stepIndex)
        )

        // 渲染节点
        renderNodesFromData(sortedData)

        // 渲染连接线
        renderEdgesFromData(sortedData)
        // 默认选中第一个节点（高亮显示）
        if (sortedData.length > 0) {
          const firstNode = sortedData[0];
          if(firstNode) {
            // 设置选中节点ID
            selectedNodeId.value = `node-${firstNode.id}`;
            // 显示表单
            showForm.value = true;

            // 更新表单数据
            if (firstNode) {
              Object.assign(formData, firstNode);
            } else {
              formData.stepIcon = firstNode.stepIcon || '';
              formData.stepTitleShort = firstNode.stepTitleShort || '';
              formData.stepIndex = firstNode.stepIndex || 1;
            }

            // 使用Vue Flow内置方法选中首个节点
            const { addSelectedNodes } = useVueFlow();
            addSelectedNodes([`node-${firstNode.id}`]);

            // 更新节点样式为选中状态
            updateNode(`node-${firstNode.id}`, (node) => {
              node.style = {
                ...node.style,
                backgroundColor: '#ffec99', // 黄色背景
                borderColor: '#f0c040', // 黄色边框
                borderWidth: '2px'
              };
            });

            console.log('默认选中第一个节点并高亮:', `node-${firstNode.id}`);
          }
        }
      }
    }
  } catch (error) {
    console.error('初始化表格数据失败:', error)
    ElMessage.error('加载步骤数据失败')
  }
}

// 初始化数据渲染节点 - 修正版本
const renderNodesFromData = (data) => {
  // 清空现有节点
  nodes.value = []

  data.forEach((item, index) => {
    const nodeId = `node-${item.id || Date.now() + index}`

    const newNode = {
      id: nodeId,
      position: {
        x: 100 + index * 200,
        y: 100
      },
      width: 100,
      height: 150,
      data: {
        stepIcon: item.stepIcon,
        stepTitleShort: item.stepTitleShort,
        stepIndex: item.stepIndex || index + 1, // 使用 stepIndex
        index: item.stepIndex || index + 1, // 保持兼容性
        // 保存完整的数据用于表单编辑
        stepData: item
      },
      style: {
        width: '130px',
        height: '180px',
        borderRadius: '12px',
        border: '1px solid #999',
        textAlign: 'center',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '10px',
        backgroundColor: '#fff'
      },
      draggable: true
    }

    addNodes(newNode)
    nodes.value.push(newNode)
  })
}

// 渲染连接线 - 新增函数
const renderEdgesFromData = (data) => {
  // 清空现有连接线
  edges.value = []

  // 根据 stepIndex 顺序创建连接线
  for (let i = 0; i < data.length - 1; i++) {
    const currentStep = data[i]
    const nextStep = data[i + 1]

    const sourceNodeId = `node-${currentStep.id}`
    const targetNodeId = `node-${nextStep.id}`

    // 创建连接线，从右侧连接到左侧
    const edge = {
      id: `edge-${currentStep.id}-${nextStep.id}`,
      source: sourceNodeId,
      target: targetNodeId,
      sourceHandle: `${sourceNodeId}-right`, // 从右侧连接点出发
      targetHandle: `${targetNodeId}-left`, // 连接到左侧连接点
      type: 'smoothstep',
      style: { stroke: '#333', strokeWidth: 2 },
      markerEnd: {
        type: 'arrowclosed',
        width: 20,
        height: 20,
        color: '#333'
      }
    }

    addEdges(edge)
    edges.value.push(edge)

    console.log('创建连接线:', edge)
  }
}


// 表单变化处理（防抖） - 修正版本
const handleFormChange = debounce(async () => {
  if (selectedNodeId.value) {
    // 更新节点显示
    updateNode(selectedNodeId.value, (node) => {
      node.data.stepIcon = formData.stepIcon
      node.data.stepTitleShort = formData.stepTitleShort
      node.data.stepIndex = formData.stepIndex // 同步 stepIndex
    })

    // 更新本地节点数组
    const localNode = nodes.value.find((n) => n.id === selectedNodeId.value)
    if (localNode) {
      localNode.data.stepIcon = formData.stepIcon
      localNode.data.stepTitleShort = formData.stepTitleShort
      localNode.data.stepIndex = formData.stepIndex // 同步 stepIndex
    }

    // 保存数据
    await saveFormData(formData)
  }
}, 1000)

// 自动保存单行数据
const saveFormData = async (row) => {
  try {
    if (!row) return
      await updateSopWorkflowStep(row)
      ElMessage.success(`更新步骤成功`)

  } catch (error) {
    console.error('保存步骤失败', error)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 节点点击处理 - 修正版本
onNodeClick(({ node }) => {
  // 清除所有节点的选中样式
  nodes.value.forEach(n => {
    updateNode(n.id, (nodeItem) => {
      nodeItem.style = {
        ...nodeItem.style,
        backgroundColor: '#fff',
        borderColor: '#999',
        borderWidth: '1px'
      };
    });
  });

  if (selectedNodeId.value === node.id) {
    showForm.value = false
    selectedNodeId.value = null
  } else {
    selectedNodeId.value = node.id
    showForm.value = true

    // 设置当前节点为选中样式
    updateNode(node.id, (nodeItem) => {
      nodeItem.style = {
        ...nodeItem.style,
        backgroundColor: '#ffec99', // 黄色背景
        borderColor: '#f0c040', // 黄色边框
        borderWidth: '2px'
      };
    });

    // 更新表单数据
    const nodeData = node.data
    if (nodeData.stepData) {
      // 如果有完整数据，使用完整数据
      Object.assign(formData, nodeData.stepData)
    } else {
      // 否则使用节点显示数据
      formData.stepIcon = nodeData.stepIcon || ''
      formData.stepTitleShort = nodeData.stepTitleShort || ''
      formData.stepIndex = nodeData.stepIndex || 1 // 同步 stepIndex
    }
  }
})

onNodeContextMenu(({ node, event }) => {
  event.preventDefault()
  selectedNodeId.value = node.id
  showForm.value = true
})


// 角色获取
const InitRole = async () => {
  try {
    const data = await getRolePage({ pageNo: 1, pageSize: -1 })
    RoleOptions.value = data.list
  } catch (error) {
    console.error('获取角色数据失败:', error)
  }
}
// 人员获取
const InitUser = async () => {
  try {
    const data = await getRoleUser(formData.confirmRoleCode)
    UserOptions.value = data.map((item) => {
      return {
        label: item.nickname,
        value: item.id
      }
    })
  } catch (error) {
    console.error('获取角色数据失败:', error)
  }
}
// 获取图标选项
const loadIconOptions = async () => {
  try {
    const icons = await getIcons()
    if (icons && icons.length > 0) {
      iconOptions.value = icons
      console.log('图标选项已加载:', iconOptions.value)
    }
  } catch (error) {
    console.error('加载图标选项失败:', error)
  }
}

// 获取步骤基础图标
const getIcons = async () => {
  try {
    const sysAttrKey1 = 'icon.step.all'
    const iconRes = await getIsSystemAttributeByKey(sysAttrKey1)
    console.log(iconRes, '获取到的图标配置')

    if (iconRes && iconRes.sysAttrValue) {
      const iconKeys = iconRes.sysAttrValue.split(',')
      console.log('图标键值列表:', iconKeys)

      const iconValues = await getIconValues(iconKeys)
      console.log('所有图标值:', iconValues)

      return iconValues
    }
  } catch (error) {
    console.error('获取图标失败:', error)
  }
}

// 批量获取图标值
const getIconValues = async (iconKeys) => {
  const iconValues = []

  for (const key of iconKeys) {
    try {
      const iconData = await getIsSystemAttributeByKey(key.trim())
      if (iconData && iconData.sysAttrValue) {
        iconValues.push({
          id: iconData.id,
          key: key.trim(),
          value: iconData.sysAttrValue,
          name: iconData.sysAttrName || key.trim()
        })
      }
    } catch (error) {
      console.error(`获取图标 ${key} 失败:`, error)
    }
  }

  return iconValues
}

// 内容变化
const handleContentChange = (content: string) => {
  console.log('内容变化:', content)
  handleFormChange() // 触发保存
}

// 节点连接线 - 修正版本
onConnect((params) => {
  console.log('连接参数:', params)

  // 创建新的连接线，确保使用正确的 sourceHandle 和 targetHandle
  const newEdge = {
    id: `e-${params.source}-${params.target}`,
    source: params.source,
    target: params.target,
    sourceHandle: params.sourceHandle, // 使用实际的 sourceHandle
    targetHandle: params.targetHandle, // 使用实际的 targetHandle
    type: 'smoothstep',
    style: { stroke: '#333', strokeWidth: 2 },
    markerEnd: {
      type: 'arrowclosed',
      width: 20,
      height: 20,
      color: '#333'
    }
  }

  console.log('创建连接线:', newEdge)
  addEdges(newEdge)
  edges.value.push(newEdge)
})


// 组件挂载时初始化
onMounted(async () => {
  // 并行执行初始化
  await Promise.all([loadIconOptions(), InitRole(), initTableData()])
})
// 确认角色清空操作
const handleRoleClear = (formData) => {
  formData.confirmRoleCode = ''
  formData.confirmUser = ''
}
// 监听 confirmRoleCode 的变化
watch(
  () => formData.confirmRoleCode,
  async (newRoleCode) => {
    if (newRoleCode) {
      await InitUser(newRoleCode)
    }
  },
  { immediate: true } // immediate: true 表示在组件挂载时立即执行一次
)
</script>

<style scoped lang="scss">
.custom-node {
  position: relative;
  width: 125px;
  height: 180px;
  background-color: #fff;
  background: transparent;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  box-sizing: border-box;
}

.node-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

// 连接点样式
.handle {
  width: 12px;
  height: 12px;
  background-color: #1a192b;
  border: 2px solid #fff;
  border-radius: 50%;
  cursor: crosshair;
  position: absolute;
  z-index: 10;
}

.handle:hover {
  background-color: #555;
  transform: scale(1.2);
}

.handle-top {
  top: -8px;
  left: 50%;
  transform: translateX(-50%);
}

.handle-bottom {
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
}

.handle-left {
  left: -8px;
  top: 50%;
  transform: translateY(-50%);
}

.handle-right {
  right: -8px;
  top: 50%;
  transform: translateY(-50%);
}

// 全局样式，确保连接点可见
:deep(.vue-flow__handle) {
  width: 12px;
  height: 12px;
  background-color: #1a192b;
  border: 2px solid #fff;
  border-radius: 50%;
  cursor: crosshair;
}

:deep(.vue-flow__handle:hover) {
  background-color: #555;
  transform: scale(1.2);
}

// 连接线样式
:deep(.vue-flow__edge-path) {
  stroke: #333;
  stroke-width: 2;
}

:deep(.vue-flow__edge) {
  z-index: 1;
}

// 箭头样式
:deep(.vue-flow__edge-marker) {
  fill: #333;
}
.step-function-container {
  //border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding-top: 6px;
  //background-color: #fafafa;
  min-height: 60px;

  .function-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    .function-label {
      font-weight: 500;
      color: #606266;
      margin-right: 12px;
      min-width: 120px;
    }
  }

  .no-function-tip {
    text-align: center;
    padding: 20px 0;
    color: #909399;
  }
}
/* 在组件的style部分添加 */
.vue-flow__node.selected {
  background-color: yellow !important;
  border-color: #ff9800 !important;
  box-shadow: 0 0 10px rgba(255, 152, 0, 0.5) !important;
}
</style>
