<template>
  <view>
    <uv-popup ref="popupRef" mode="bottom" round="24rpx" @change="onPopupChange">
      <view class="dept-select-container">
        <!-- Header -->
        <view class="header">
          <view class="title">选择组织部门</view>
          <uv-icon name="close" color="#94a3b8" size="20" @click="close"></uv-icon>
        </view>

        <!-- Breadcrumbs (Hierarchy Path) -->
        <view class="breadcrumbs" v-if="path.length > 0">
          <scroll-view scroll-x class="breadcrumb-scroll" :show-scrollbar="false">
            <view class="breadcrumb-inner">
              <view class="breadcrumb-item" @click="goHome">
                <text class="breadcrumb-text">全部</text>
                <uv-icon name="arrow-right" size="12" color="#cbd5e1" customStyle="margin: 0 8rpx;"></uv-icon>
              </view>
              <view v-for="(node, index) in path" :key="node.id" class="breadcrumb-item" @click="goToPath(index)">
                <text class="breadcrumb-text" :class="{'active': index === path.length - 1}">{{ node.deptName }}</text>
                <uv-icon v-if="index < path.length - 1" name="arrow-right" size="12" color="#cbd5e1" customStyle="margin: 0 8rpx;"></uv-icon>
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- Search Bar -->
        <view class="search-box">
          <uv-search v-model="keyword" placeholder="搜索部门名称" :showAction="false" @change="onSearch" @clear="onSearch"></uv-search>
        </view>

        <!-- Content Area -->
        <scroll-view scroll-y class="list-container">
          <view v-if="isSearching" class="search-results">
            <view v-for="item in searchResults" :key="item.id" class="node-item" @click="handleSelect(item)">
              <view class="node-content">
                <view class="node-name-group">
                  <text class="node-name">{{ item.deptName }}</text>
                  <text class="node-path" v-if="item.fullPath">{{ item.fullPath }}</text>
                </view>
                <view class="node-action">
                  <uv-icon v-if="!item.hasChildren" name="checkbox-mark" :color="modelValue === item.id ? '#3b82f6' : '#e2e8f0'" size="20"></uv-icon>
                  <text v-else class="dir-tip">进入</text>
                </view>
              </view>
            </view>
            <view v-if="searchResults.length === 0" class="empty-tip">未找到匹配的部门</view>
          </view>

          <view v-else class="level-list">
            <view v-for="node in currentList" :key="node.id" class="node-item" @click="handleClick(node)">
              <view class="node-content">
                <view class="node-info">
                  <uv-icon :name="node.children && node.children.length > 0 ? 'folder' : 'order'" 
                    :color="node.children && node.children.length > 0 ? '#60a5fa' : '#94a3b8'" size="20" style="margin-right: 20rpx;"></uv-icon>
                  <text class="node-name" :class="{'selected': modelValue === node.id}">{{ node.deptName }}</text>
                </view>
                <view class="node-action">
                  <template v-if="node.children && node.children.length > 0">
                    <text class="child-count">{{ node.children.length }}</text>
                    <uv-icon name="arrow-right" color="#cbd5e1" size="16"></uv-icon>
                  </template>
                  <template v-else>
                    <uv-icon name="checkbox-mark" :color="modelValue === node.id ? '#3b82f6' : '#e2e8f0'" size="20"></uv-icon>
                  </template>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>

        <!-- Footer / Tip -->
        <view class="footer-tip" v-if="!isSearching">
          <uv-icon name="info-circle" color="#3b82f6" size="14" customStyle="margin-right: 8rpx;"></uv-icon>
          <text>请选择最末级科室</text>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';

const props = defineProps({
  modelValue: [Number, String],
  treeData: {
    type: Array as any,
    default: () => []
  }
});

const emit = defineEmits(['update:modelValue', 'select']);

const popupRef = ref();
const keyword = ref('');
const isSearching = computed(() => keyword.value.trim().length > 0);
const path = ref<any[]>([]);
const currentList = ref<any[]>([]);

// Initialize currentList when treeData arrives
watch(() => props.treeData, (newVal) => {
  if (newVal && newVal.length > 0 && path.value.length === 0) {
    currentList.value = newVal;
  }
}, { immediate: true });

const searchResults = ref<any[]>([]);

const onSearch = () => {
  if (!keyword.value.trim()) {
    searchResults.value = [];
    return;
  }
  const results: any[] = [];
  const walk = (nodes: any[], parentPath: string = '') => {
    for (const node of nodes) {
      const currentPath = parentPath ? `${parentPath} / ${node.deptName}` : node.deptName;
      if (node.deptName.includes(keyword.value)) {
        results.push({
          ...node,
          fullPath: parentPath,
          hasChildren: node.children && node.children.length > 0
        });
      }
      if (node.children) walk(node.children, currentPath);
    }
  };
  walk(props.treeData);
  searchResults.value = results;
};

const open = () => {
  popupRef.value.open();
};

const close = () => {
  popupRef.value.close();
};

const onPopupChange = (e: any) => {
  if (!e.show) {
    // Reset path when closing if desired, or keep state
  }
};

const handleClick = (node: any) => {
  if (node.children && node.children.length > 0) {
    path.value.push(node);
    currentList.value = node.children;
  } else {
    handleSelect(node);
  }
};

const handleSelect = (node: any) => {
  if (node.children && node.children.length > 0) {
    // Drill down instead of select
    path.value = findPathToNode(props.treeData, node.id) || [];
    currentList.value = node.children;
    keyword.value = '';
    return;
  }
  emit('update:modelValue', node.id);
  emit('select', node);
  close();
};

const findPathToNode = (nodes: any[], id: number, currentPath: any[] = []): any[] | null => {
  for (const node of nodes) {
    if (node.id === id) return [...currentPath, node];
    if (node.children) {
      const res = findPathToNode(node.children, id, [...currentPath, node]);
      if (res) return res;
    }
  }
  return null;
};

const goToPath = (index: number) => {
  const targetNode = path.value[index];
  path.value = path.value.slice(0, index + 1);
  currentList.value = targetNode.children;
};

const goHome = () => {
  path.value = [];
  currentList.value = props.treeData;
};

defineExpose({ open, close });
</script>

<style lang="scss" scoped>
.dept-select-container {
  background-color: #ffffff;
  height: 80vh;
  display: flex;
  flex-direction: column;
  border-radius: 24rpx 24rpx 0 0;
}

.header {
  padding: 30rpx 40rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 2rpx solid #f1f5f9;
}

.title {
  font-size: 34rpx;
  font-weight: 600;
  color: #1e293b;
}

.breadcrumbs {
  padding: 20rpx 40rpx;
  background-color: #f8fafc;
  border-bottom: 2rpx solid #f1f5f9;
}

.breadcrumb-scroll {
  width: 100%;
}

.breadcrumb-inner {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.breadcrumb-item {
  display: flex;
  align-items: center;
}

.breadcrumb-text {
  font-size: 26rpx;
  color: #64748b;
  
  &.active {
    color: #3b82f6;
    font-weight: 500;
  }
}

.search-box {
  padding: 20rpx 40rpx;
}

.list-container {
  flex: 1;
  height: 0;
}

.node-item {
  padding: 0 40rpx;
  
  &:active {
    background-color: #f8fafc;
  }
}

.node-content {
  padding: 30rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 2rpx solid #f1f5f9;
}

.node-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.node-name {
  font-size: 30rpx;
  color: #334155;
  
  &.selected {
    color: #3b82f6;
    font-weight: 600;
  }
}

.node-action {
  display: flex;
  align-items: center;
}

.child-count {
  font-size: 24rpx;
  color: #94a3b8;
  margin-right: 12rpx;
}

.dir-tip {
  font-size: 24rpx;
  color: #3b82f6;
  background: #eff6ff;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
}

.search-results {
  .node-name-group {
    display: flex;
    flex-direction: column;
  }
  
  .node-path {
    font-size: 22rpx;
    color: #94a3b8;
    margin-top: 4rpx;
  }
}

.empty-tip {
  padding: 100rpx 0;
  text-align: center;
  color: #94a3b8;
  font-size: 28rpx;
}

.footer-tip {
  padding: 20rpx 40rpx calc(20rpx + env(safe-area-inset-bottom));
  background-color: #f8fafc;
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #64748b;
  border-top: 2rpx solid #f1f5f9;
}
</style>
