<template>
  <div class="create-flow-container">
    <div class="page-header">
      <el-button type="primary" link @click="handleBack"
        ><el-icon><ArrowLeft /></el-icon>返回</el-button
      >
      <span class="page-title">{{ isEdit ? '编辑审批' : '新建审批' }}</span>
    </div>

    <div class="flow-tip">
      <i class="title-bar"></i>
      <span>最多可设置5级审批</span>
      <div class="status-info" v-if="isEdit">
        <el-tag :type="hasUnsavedChanges ? 'warning' : 'success'" size="small">
          {{ hasUnsavedChanges ? '有未保存的更改' : '已保存' }}
        </el-tag>
      </div>
    </div>

    <div class="flow-form">
      <div class="form-item">
        <label>流程名称</label>
        <el-input v-model="flowName" placeholder="请输入" style="width: 100%" />
      </div>
    </div>

    <!-- 流程设计器 -->
    <div v-loading="detailLoading" class="flow-designer">
      <!-- 流程发起节点 -->
      <div class="flow-node start-node">
        <div class="node-header">流程发起</div>
        <div class="node-content">
          <span>发起人：所有人</span>
          <el-icon><ArrowRight /></el-icon>
        </div>
      </div>

      <!-- 连接线 + 添加按钮 -->
      <div class="flow-line">
        <div class="line"></div>
        <div class="add-btn" @click="handleAddNode">
          <el-icon><Plus /></el-icon>
        </div>
        <div class="line"></div>
      </div>

      <!-- 审批人节点 -->
      <div v-for="(node, index) in approvalNodes" :key="index" class="flow-node approval-node">
        <div class="node-header">
          <span>审批人</span>
          <div class="node-actions">
            <el-icon @click="handleEditNode(index)"><Edit /></el-icon>
            <el-icon @click="handleDeleteNode(index)"><Delete /></el-icon>
          </div>
        </div>
        <div class="node-content" @click="handleEditNode(index)" :class="{ 'missing-approver': !node.handlerId }">
          <div class="node-info">
            <span class="node-name">{{ node.nodeName }}</span>
            <span class="approver-info">审批人：{{ node.handlerName || '未设置' }}</span>
          </div>
          <el-icon><ArrowRight /></el-icon>
        </div>

        <!-- 连接线 -->
        <div class="flow-line">
          <div class="line"></div>
          <div class="add-btn" @click="handleAddNodeAfter(index)">
            <el-icon><Plus /></el-icon>
          </div>
          <div class="line"></div>
        </div>
      </div>

      <!-- 审批结束节点 -->
      <div class="flow-node end-node">
        <div class="node-btn">审批结束</div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="footer-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSave" :disabled="!flowName.trim() || approvalNodes.length === 0">
        {{ isEdit ? '更新流程' : '创建流程' }}
      </el-button>
    </div>
  </div>

  <!-- 选择审批人弹窗 -->
  <el-dialog v-model="selectDialogVisible" title="选择审批人" width="500px" :close-on-click-modal="false">
    <div class="contact-search">
      <el-input v-model="contactSearchKey" placeholder="搜索姓名/手机号" clearable @input="handleContactSearch">
        <template #prefix>
          <el-icon><Search /> </el-icon>
        </template>
      </el-input>
    </div>

    <div v-loading="contactLoading" class="contact-list">
      <el-empty v-if="!contactLoading && filteredContactList.length === 0" description="暂无联系人" />
      <div
        v-for="contact in filteredContactList"
        :key="contact.id"
        class="contact-item"
        :class="{ selected: isContactSelected(contact) }"
        @click="toggleContact(contact)"
      >
        <div class="contact-info">
          <span class="contact-name">{{ contact.contactName || contact.name }}</span>
          <span class="contact-phone">{{ contact.phone || contact.mobile }}</span>
        </div>
        <el-icon v-if="isContactSelected(contact)" class="check-icon"><Check /></el-icon>
      </div>
    </div>

    <div v-if="selectedContacts.length > 0" class="selected-tags">
      <span class="selected-label">已选：</span>
      <el-tag v-for="contact in selectedContacts" :key="contact.id" closable size="small" @close="removeContact(contact)">
        {{ contact.contactName || contact.name }}
      </el-tag>
    </div>

    <template #footer>
      <el-button @click="selectDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirmSelect">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ArrowLeft, ArrowRight, Plus, Edit, Delete, Search, Check } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addOrderFlow, updateOrderFlow, getOrderFlowDetail } from '@/api/pc/enterprise/order';
import { getContactList } from '@/api/pc/organization/index';
import type { OrderCustomerFlowNode, OrderCustomerFlowSaveBo } from '@/api/pc/enterprise/orderTypes';

const router = useRouter();
const route = useRoute();

const flowId = computed(() => (route.query.id ? route.query.id : undefined));
const isEdit = computed(() => !!flowId.value);

const flowName = ref('');
const approvalNodes = ref<OrderCustomerFlowNode[]>([]);
const detailLoading = ref(false);
const submitLoading = ref(false);

// 新增的响应式变量
const originalNodes = ref<OrderCustomerFlowNode[]>([]); // 保存原始节点数据用于对比

// ==================== 联系人选择弹窗 ====================
const selectDialogVisible = ref(false);
const contactLoading = ref(false);
const contactList = ref<any[]>([]);
const contactSearchKey = ref('');
const selectedContacts = ref<any[]>([]);
const currentEditIndex = ref<number>(-1);

const filteredContactList = computed(() => {
  const key = contactSearchKey.value.trim().toLowerCase();
  if (!key) return contactList.value;
  return contactList.value.filter((c) => {
    const name = (c.contactName || c.name || '').toLowerCase();
    const phone = (c.phone || c.mobile || '').toLowerCase();
    return name.includes(key) || phone.includes(key);
  });
});

const loadContactList = async () => {
  contactLoading.value = true;
  try {
    const res = await getContactList();
    contactList.value = res.rows || [];
  } catch (e) {
    ElMessage.error('加载联系人列表失败');
  } finally {
    contactLoading.value = false;
  }
};

/** 根据 contactList 为已有节点填充 handlerName（编辑模式下后端不返回 handlerName，需前端自行匹配） */
const populateHandlerNames = () => {
  if (contactList.value.length === 0 || approvalNodes.value.length === 0) return;
  approvalNodes.value.forEach((node) => {
    if (node.handlerId && !node.handlerName) {
      const ids = node.handlerId.split(',').filter(Boolean);
      node.handlerName = contactList.value
        .filter((c) => ids.includes(String(c.id)))
        .map((c) => c.contactName || c.name)
        .join(',');
    }
  });
  // 同步更新 originalNodes，避免 handlerName 填充导致误判为"有未保存的更改"
  originalNodes.value = JSON.parse(JSON.stringify(approvalNodes.value));
};

const handleContactSearch = () => {
  // filteredContactList 由 computed 自动过滤，无需额外操作
};

const isContactSelected = (contact: any) => {
  return selectedContacts.value.some((c) => c.id === contact.id);
};

const toggleContact = (contact: any) => {
  const idx = selectedContacts.value.findIndex((c) => c.id === contact.id);
  if (idx === -1) {
    selectedContacts.value.push(contact);
  } else {
    selectedContacts.value.splice(idx, 1);
  }
};

const removeContact = (contact: any) => {
  const idx = selectedContacts.value.findIndex((c) => c.id === contact.id);
  if (idx !== -1) selectedContacts.value.splice(idx, 1);
};

const handleConfirmSelect = () => {
  if (currentEditIndex.value < 0) return;
  const currentNode = approvalNodes.value[currentEditIndex.value];
  // 存储处理人ID
  currentNode.handlerId = selectedContacts.value.map((c) => String(c.id)).join(',');
  // 存储处理人姓名（用于显示）
  currentNode.handlerName = selectedContacts.value.map((c) => c.contactName || c.name).join(',');
  selectDialogVisible.value = false;
};

// ==================== 流程详情加载 ====================

/** 编辑模式：加载流程详情 */
const loadFlowDetail = async (id: number) => {
  detailLoading.value = true;
  try {
    const res = await getOrderFlowDetail(id);
    const detail = res.data;
    flowName.value = detail?.flowName ?? '';
    // 深拷贝节点数据，保存原始数据用于对比
    const nodes = (detail?.flowNodes ?? []).map((node: OrderCustomerFlowNode) => ({ ...node }));
    approvalNodes.value = nodes;
    originalNodes.value = JSON.parse(JSON.stringify(nodes)); // 深拷贝保存原始数据
  } catch (e) {
    ElMessage.error('加载流程详情失败');
  } finally {
    detailLoading.value = false;
  }
};

onMounted(async () => {
  if (isEdit.value && flowId.value) {
    // 并行加载流程详情和联系人列表，两者都完成后再填充 handlerName
    await Promise.all([loadFlowDetail(flowId.value as any), loadContactList()]);
    populateHandlerNames();
  } else {
    // 新建模式只需加载联系人列表
    loadContactList();
  }
});

const handleBack = () => {
  router.back();
};

const handleCancel = async () => {
  // 如果有未保存的更改，提示用户确认
  if (hasUnsavedChanges.value) {
    try {
      await ElMessageBox.confirm('您有未保存的更改，确定要离开页面吗？', '离开确认', {
        confirmButtonText: '确定离开',
        cancelButtonText: '继续编辑',
        type: 'warning'
      });
    } catch {
      return; // 用户选择继续编辑
    }
  }
  router.back();
};

const handleAddNode = () => {
  if (approvalNodes.value.length >= 5) {
    ElMessage.warning('最多可设置5级审批');
    return;
  }
  const newNode: OrderCustomerFlowNode = {
    nodeName: `审批节点${approvalNodes.value.length + 1}`,
    nodeType: '1', // 中间节点
    sort: 1,
    handlerId: '',
    handlerName: ''
  };
  approvalNodes.value.unshift(newNode);
  // 更新所有节点的顺序
  updateNodeOrders();
};

const handleAddNodeAfter = (index: number) => {
  if (approvalNodes.value.length >= 5) {
    ElMessage.warning('最多可设置5级审批');
    return;
  }
  const newNode: OrderCustomerFlowNode = {
    nodeName: `审批节点${approvalNodes.value.length + 1}`,
    nodeType: '1', // 中间节点
    sort: index + 2,
    handlerId: '',
    handlerName: ''
  };
  approvalNodes.value.splice(index + 1, 0, newNode);
  // 更新所有节点的顺序
  updateNodeOrders();
};

// 新增：更新所有节点的顺序
const updateNodeOrders = () => {
  approvalNodes.value.forEach((node, index) => {
    node.sort = index + 1;
  });
};

const handleEditNode = (index: number) => {
  currentEditIndex.value = index;
  contactSearchKey.value = '';
  // 回显已选中的联系人（根据 handlerId 匹配）
  const currentNode = approvalNodes.value[index];
  if (currentNode.handlerId) {
    const handlerIds = currentNode.handlerId.split(',').filter(Boolean);
    selectedContacts.value = contactList.value.filter((c) => handlerIds.includes(String(c.id)));
  } else {
    selectedContacts.value = [];
  }
  selectDialogVisible.value = true;
  // 若联系人列表未加载，则加载
  if (contactList.value.length === 0) {
    loadContactList();
  }
};

const handleDeleteNode = async (index: number) => {
  const node = approvalNodes.value[index];

  // 如果是编辑模式且节点有ID，提示用户确认删除
  if (isEdit.value && node.id) {
    try {
      await ElMessageBox.confirm(`确定要删除审批节点"${node.nodeName}"吗？此操作将永久删除该节点。`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
    } catch {
      return; // 用户取消删除
    }
  }

  approvalNodes.value.splice(index, 1);
  // 更新所有节点的顺序
  updateNodeOrders();
};

/** 保存流程 */
const handleSave = async () => {
  if (!flowName.value.trim()) {
    ElMessage.warning('请输入流程名称');
    return;
  }

  // 验证审批节点
  if (approvalNodes.value.length === 0) {
    ElMessage.warning('请至少添加一个审批节点');
    return;
  }

  // 检查是否有未设置审批人的节点
  const emptyApproverNodes = approvalNodes.value.filter((node) => !node.handlerId);
  if (emptyApproverNodes.length > 0) {
    ElMessage.warning(`存在未设置审批人的节点：${emptyApproverNodes.map((n) => n.nodeName).join('、')}`);
    return;
  }

  // 构造保存数据
  const saveData: OrderCustomerFlowSaveBo = {
    flowName: flowName.value.trim(),
    flowNodes: approvalNodes.value.map((node, index) => ({
      ...node,
      sort: index + 1 // 确保顺序正确
    }))
  };

  // 编辑模式下添加ID
  if (isEdit.value && flowId.value) {
    saveData.id = flowId.value;
  }

  submitLoading.value = true;
  try {
    if (isEdit.value) {
      await updateOrderFlow(saveData);
      ElMessage.success('编辑成功');
    } else {
      await addOrderFlow(saveData);
      ElMessage.success('新增成功');
    }
    router.back();
  } catch (e: any) {
    console.error('保存失败:', e);
    ElMessage.error(isEdit.value ? '编辑失败' : '新增失败');
  } finally {
    submitLoading.value = false;
  }
};

// 新增：检查是否有未保存的更改
const hasUnsavedChanges = computed(() => {
  if (!isEdit.value) return approvalNodes.value.length > 0;

  // 比较节点数量
  if (approvalNodes.value.length !== originalNodes.value.length) return true;

  // 比较节点内容
  return approvalNodes.value.some((node, index) => {
    const originalNode = originalNodes.value[index];
    return (
      node.nodeName !== originalNode.nodeName ||
      node.handlerId !== originalNode.handlerId ||
      node.handlerName !== originalNode.handlerName ||
      node.sort !== originalNode.sort
    );
  });
});

// 新增：页面离开前确认
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
  if (hasUnsavedChanges.value) {
    e.preventDefault();
    e.returnValue = '';
    return '';
  }
};

// 监听页面卸载事件
window.addEventListener('beforeunload', handleBeforeUnload);

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload);
});
</script>

<style scoped lang="scss">
.create-flow-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
  flex: 1;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  .page-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
}

.flow-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #333;
  .title-bar {
    display: inline-block;
    width: 3px;
    height: 14px;
    background: #e60012;
    border-radius: 2px;
  }
  .status-info {
    margin-left: auto;
  }
}

.flow-form {
  margin-bottom: 30px;
  .form-item {
    label {
      display: block;
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
    }
    :deep(.el-input__wrapper) {
      background: #f5f5f5;
      box-shadow: none;
    }
  }
}

.flow-designer {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.flow-node {
  width: 280px;
  border-radius: 4px;
  overflow: hidden;

  &.start-node {
    .node-header {
      background: #ff6b6b;
      color: #fff;
      padding: 8px 15px;
      font-size: 13px;
    }
    .node-content {
      background: #fff;
      border: 1px solid #eee;
      border-top: none;
      padding: 12px 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 13px;
      color: #666;
      cursor: pointer;
    }
  }

  &.approval-node {
    .node-header {
      background: #409eff;
      color: #fff;
      padding: 8px 15px;
      font-size: 13px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .node-actions {
        display: flex;
        gap: 10px;
        .el-icon {
          cursor: pointer;
          &:hover {
            opacity: 0.8;
          }
        }
      }
    }
    .node-content {
      background: #fff;
      border: 1px solid #eee;
      border-top: none;
      padding: 12px 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 13px;
      color: #666;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        background: #f9f9f9;
      }

      &.missing-approver {
        border-color: #f56c6c;
        background: #fef0f0;

        .approver-info {
          color: #f56c6c;
        }
      }

      .node-info {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .node-name {
          font-weight: 500;
          color: #333;
        }

        .approver-info {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }

  &.end-node {
    .node-btn {
      background: #909399;
      color: #fff;
      padding: 10px 40px;
      border-radius: 4px;
      font-size: 13px;
      text-align: center;
    }
  }
}

.footer-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 30px;
  padding-bottom: 20px;
}

// 联系人弹窗样式
.contact-search {
  margin-bottom: 12px;
}

.contact-list {
  max-height: 320px;
  overflow-y: auto;
  border: 1px solid #eee;
  border-radius: 4px;

  .contact-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 14px;
    cursor: pointer;
    transition: background 0.2s;

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

    &:hover {
      background: #f5f7fa;
    }

    &.selected {
      background: #ecf5ff;
    }

    .contact-info {
      display: flex;
      flex-direction: column;
      gap: 2px;

      .contact-name {
        font-size: 14px;
        color: #333;
      }

      .contact-phone {
        font-size: 12px;
        color: #999;
      }
    }

    .check-icon {
      color: #409eff;
      font-size: 16px;
    }
  }
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 6px;
  margin-top: 12px;
  padding: 8px 10px;
  background: #f5f7fa;
  border-radius: 4px;

  .selected-label {
    font-size: 13px;
    color: #666;
  }
}

.flow-line {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;

  .line {
    width: 1px;
    height: 20px;
    background: #ddd;
  }
  .add-btn {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #409eff;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 12px;
    margin: 5px 0;
    &:hover {
      background: #66b1ff;
    }
  }
}
</style>
