<template>
  <view class="multi-select-container">
    <!-- 选中标签展示区 -->
    <view
      class="selected-tags"
      :class="{ 'has-value': selectedItems.length > 0 }"
      @click="toggleDropdown"
    >
      <view class="tag-box" v-if="selectedItems.length > 0">
        <view
          class="tag-item"
          v-for="(item, index) in selectedItems"
          :key="index"
          @click.stop.prevent="removeItem(item)"
        >
          {{ item.name }}
          <u-icon name="close" size="20rpx" class="tag-close"></u-icon>
        </view>
      </view>
      <template v-else>
        <text class="placeholder">{{ placeholder }}</text>
      </template>
      <u-icon
        name="arrow-down"
        size="24rpx"
        class="dropdown-icon"
        :class="{ rotate: isOpen }"
      ></u-icon>
    </view>

    <!-- 下拉选项面板 -->
    <view
      class="dropdown-panel"
      v-if="isOpen"
      :style="{
        width: panelWidth,
        maxHeight: panelMaxHeight,
      }"
      @tap.stop
    >
      <!-- 一级选项 -->
      <view class="level1-wrapper">
        <view
          class="level1-item"
          v-for="level1 in options"
          :key="level1.id"
          :class="{ active: activeLevel1Id === level1.id }"
          @click="handleLevel1Click(level1.id)"
        >
          {{ level1.name }}
        </view>
      </view>

      <view class="level2-wrapper">
        <view
          class="level2-item"
          v-for="level2 in filteredLevel2"
          :key="level2.id"
          :class="{ checked: isSelected(level2) }"
          @click="toggleLevel2(level2)"
        >
          <text class="item-text">{{ level2.name }}</text>
        </view>
        <view class="empty-text" v-if="filteredLevel2.length === 0">
          <trans _t="暂无选项" />
        </view>
      </view>
    </view>
    <view v-if="isOpen" class="backdrop" @tap="close"></view>
  </view>
</template>

<script setup>
import { ref, watch, computed, defineProps, defineEmits } from "vue";

// 定义组件属性
const props = defineProps({
  // 选项数据
  options: {
    type: Array,
    default: () => [],
    // 数据格式: [{
    //   id: 1,
    //   name: '一级选项1',
    //   children: [{ id: 11, name: '二级选项1-1' }, ...]
    // }, ...]
  },
  // 占位文本
  placeholder: {
    type: String,
    default: "",
  },
  // 面板宽度
  panelWidth: {
    type: String,
    default: "500rpx",
  },
  // 面板最大高度
  panelMaxHeight: {
    type: String,
    default: "600rpx",
  },
  // 默认选中值
  modelValue: {
    type: Array,
    default: () => [],
  },
});

// 定义事件
const emits = defineEmits(["update:modelValue", "change"]);

// 状态管理
const isOpen = ref(false); // 下拉面板是否展开
const activeLevel1Id = ref(""); // 当前激活的一级选项ID
const selectedItems = ref([]); // 选中的二级选项

// 初始化
watch(
  () => props.modelValue,
  (newVal) => {
    // 从外部值初始化选中项
    if (newVal && newVal.length > 0) {
      const items = [];
      props.options.forEach((level1) => {
        level1.children?.forEach((level2) => {
          if (newVal.includes(level2.id)) {
            items.push(level2);
          }
        });
      });
      selectedItems.value = items;
    }
  },
  { immediate: true }
);

// 初始化默认选中的一级选项
watch(
  () => props.options,
  (newVal) => {
    if (newVal && newVal.length > 0 && !activeLevel1Id.value) {
      activeLevel1Id.value = newVal[0].id;
    }
  },
  { immediate: true }
);

// 过滤当前一级选项对应的二级选项
const filteredLevel2 = computed(() => {
  const level1 = props.options.find((item) => item.id === activeLevel1Id.value);
  return level1?.children || [];
});

// 切换下拉面板
const toggleDropdown = () => {
  isOpen.value = !isOpen.value;
};

// 点击一级选项
const handleLevel1Click = (id) => {
  activeLevel1Id.value = id;
};

// 切换二级选项选中状态
const toggleLevel2 = (item) => {
  const index = selectedItems.value.findIndex((i) => i.id === item.id);

  if (index > -1) {
    // 取消选中
    selectedItems.value.splice(index, 1);
  } else {
    // 选中
    selectedItems.value.push(item);
  }

  // 通知父组件
  emitChange();
};

// 判断二级选项是否选中
const isSelected = (item) => {
  return selectedItems.value.some((i) => i.id === item.id);
};

// 移除选中项
const removeItem = (item) => {
  const index = selectedItems.value.findIndex((i) => i.id === item.id);
  if (index > -1) {
    selectedItems.value.splice(index, 1);
    // 通知父组件
    emitChange();
  }
};

// 通知父组件变化
const emitChange = () => {
  const ids = selectedItems.value.map((item) => item.id);
  emits("update:modelValue", ids);
  emits("change", {
    ids,
    items: [...selectedItems.value],
  });
};

const close = () => (isOpen.value = false);

// 点击外部关闭下拉框
watch(
  () => isOpen.value,
  (newVal) => {
    const handleClickOutside = (e) => {
      const dropdown = document.querySelector(".multi-select-container");
      if (dropdown && !dropdown.contains(e.target)) {
        isOpen.value = false;
        document.removeEventListener("click", handleClickOutside);
      }
    };

    if (newVal) {
      setTimeout(() => {
        document.addEventListener("click", handleClickOutside);
      }, 0);
    }
  }
);
</script>

<style lang="less" scoped>
.multi-select-container {
  position: relative;
  display: inline-block;

  // 选中标签区域
  .selected-tags {
    display: flex;
    // flex-wrap: wrap;
    align-items: center;
    max-width: 540rpx;
    min-height: 70rpx;
    // border: 2rpx solid #ddd;
    border-radius: 8rpx;
    // background-color: #fff;
    cursor: pointer;
    transition: all 0.2s;

    &.has-value {
      border-color: #3c9cff;
    }

    &:focus-within {
      border-color: #3c9cff;
      box-shadow: 0 0 0 2rpx rgba(60, 156, 255, 0.2);
    }

    .placeholder {
      color: #999;
      font-weight: 500;
    }
    .tag-box {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }
    .tag-item {
      display: inline-flex;
      align-items: center;
      margin: 5rpx 8rpx 5rpx 0;
      padding: 5rpx 15rpx;
      background-color: #f0f7ff;
      color: #3c9cff;
      border-radius: 20rpx;
      font-size: 26rpx;

      .tag-close {
        margin-left: 8rpx;
        color: #3c9cff;
        opacity: 0.8;

        &:hover {
          opacity: 1;
        }
      }
    }

    .dropdown-icon {
      margin-left: 10rpx;
      color: #999;
      transition: transform 0.2s;

      &.rotate {
        transform: rotate(180deg);
      }
    }
  }

  // 下拉面板
  .dropdown-panel {
    position: absolute;
    top: 80rpx;
    right: 0;
    display: flex;
    border: 2rpx solid #eee;
    border-radius: 8rpx;
    background-color: #fff;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
    z-index: 999;
    overflow: hidden;

    // 一级选项
    .level1-wrapper {
      width: 35%;
      border-right: 2rpx solid #eee;
      background-color: #fafafa;
      overflow-y: auto;

      .level1-item {
        padding: 20rpx;
        font-size: 28rpx;
        color: #333;
        transition: all 0.2s;

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

        &.active {
          background-color: #fff;
          color: #3c9cff;
          font-weight: 500;
        }
      }
    }

    // 二级选项
    .level2-wrapper {
      width: 65%;
      padding: 10rpx;
      overflow-y: auto;

      .level2-item {
        display: flex;
        align-items: center;
        padding: 15rpx 20rpx;
        font-size: 28rpx;
        color: #333;
        border-radius: 6rpx;
        transition: background-color 0.2s;

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

        &.checked {
          background-color: #f0f7ff;
          color: #3c9cff;
        }

        .check-icon {
          margin-right: 15rpx;
        }
      }

      .empty-text {
        padding: 40rpx;
        text-align: center;
        font-size: 28rpx;
        color: #999;
      }
    }
  }

  .backdrop {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    background: rgba(0, 0, 0, 0); /* 透明即可捕获点击 */
  }
}

// 解决点击事件冒泡问题
::v-deep .u-icon {
  pointer-events: none;
}
</style>
