<script setup>
import { computed, ref, watch, provide } from "vue";
import { useNamespace, useLocale } from "@yh-ui/hooks";
import { transferPanelContextKey } from "./transfer";
defineOptions({
  name: "YhTransferPanel"
});
const props = defineProps({
  data: { type: Array, required: true, default: () => [] },
  checked: { type: Array, required: true, default: () => [] },
  title: { type: String, required: false, default: "" },
  filterable: { type: Boolean, required: false, default: false },
  filterPlaceholder: { type: String, required: false },
  filterMethod: { type: Function, required: false },
  disabled: { type: Boolean, required: false, default: false },
  size: { type: null, required: false, default: "default" },
  props: { type: Object, required: false },
  renderContent: { type: Function, required: false },
  virtual: { type: Boolean, required: false, default: false },
  itemHeight: { type: Number, required: false, default: 40 },
  height: { type: Number, required: false, default: 280 },
  showAllCheckbox: { type: Boolean, required: false, default: true },
  emptyText: { type: String, required: false }
});
const emit = defineEmits(["update:checked", "checked-change"]);
const ns = useNamespace("transfer-panel");
const { t } = useLocale();
const query = ref("");
const scrollTop = ref(0);
const virtualWrapperRef = ref();
const keyProp = computed(() => props.props?.key || "key");
const labelProp = computed(() => props.props?.label || "label");
const disabledProp = computed(() => props.props?.disabled || "disabled");
const getKey = (item) => {
  return item[keyProp.value] ?? "";
};
const getLabel = (item) => {
  return String(item[labelProp.value] || "");
};
const isItemDisabled = (item) => {
  return Boolean(item[disabledProp.value]) || (props.disabled ?? false);
};
const filteredData = computed(() => {
  if (!query.value) return props.data;
  const q = query.value.toLowerCase();
  if (props.filterMethod) {
    return props.data.filter((item) => props.filterMethod(query.value, item));
  }
  return props.data.filter((item) => {
    const label = getLabel(item);
    return label.toLowerCase().includes(q);
  });
});
const checkableData = computed(() => {
  return filteredData.value.filter((item) => !isItemDisabled(item));
});
const checkedKeys = computed(() => props.checked);
const isChecked = (key) => {
  return checkedKeys.value.includes(key);
};
const isAllChecked = computed(() => {
  if (checkableData.value.length === 0) return false;
  return checkableData.value.every((item) => isChecked(getKey(item)));
});
const isIndeterminate = computed(() => {
  const checkedCount = checkableData.value.filter((item) => isChecked(getKey(item))).length;
  return checkedCount > 0 && checkedCount < checkableData.value.length;
});
const totalCheckedCount = computed(() => {
  return props.data.filter((item) => isChecked(getKey(item))).length;
});
const virtualConfig = computed(() => {
  const itemHeight = props.itemHeight || 40;
  const containerHeight = props.height || 280;
  const overscan = 3;
  const items = filteredData.value;
  if (!props.virtual || items.length === 0) {
    return {
      visibleItems: items,
      totalHeight: items.length * itemHeight,
      offsetY: 0,
      startIndex: 0,
      endIndex: items.length
    };
  }
  const totalHeight = items.length * itemHeight;
  const startIndex = Math.max(0, Math.floor(scrollTop.value / itemHeight) - overscan);
  const visibleCount = Math.ceil(containerHeight / itemHeight);
  const endIndex = Math.min(items.length, startIndex + visibleCount + overscan * 2);
  return {
    visibleItems: items.slice(startIndex, endIndex),
    totalHeight,
    offsetY: startIndex * itemHeight,
    startIndex,
    endIndex
  };
});
const displayItems = computed(() => {
  return props.virtual ? virtualConfig.value.visibleItems : filteredData.value;
});
const handleVirtualScroll = (event) => {
  const target = event.target;
  scrollTop.value = target.scrollTop;
};
const handleCheck = (key, checked) => {
  if (props.disabled) return;
  const newChecked = [...checkedKeys.value];
  const index = newChecked.indexOf(key);
  if (checked) {
    if (index === -1) {
      newChecked.push(key);
    }
  } else {
    if (index > -1) {
      newChecked.splice(index, 1);
    }
  }
  emit("update:checked", newChecked);
  emit("checked-change", newChecked, [key]);
};
const handleItemClick = (item) => {
  if (isItemDisabled(item)) return;
  const key = getKey(item);
  handleCheck(key, !isChecked(key));
};
const handleCheckAll = () => {
  if (props.disabled || checkableData.value.length === 0) return;
  let newChecked;
  if (isAllChecked.value) {
    const checkableKeys = new Set(checkableData.value.map((item) => getKey(item)));
    newChecked = checkedKeys.value.filter((key) => !checkableKeys.has(key));
  } else {
    const checkableKeys = checkableData.value.map((item) => getKey(item));
    newChecked = [.../* @__PURE__ */ new Set([...checkedKeys.value, ...checkableKeys])];
  }
  emit("update:checked", newChecked);
  emit("checked-change", newChecked);
};
const clearChecked = () => {
  emit("update:checked", []);
  emit("checked-change", []);
};
provide(transferPanelContextKey, {
  props,
  checked: checkedKeys.value,
  handleCheck
});
defineExpose({
  clearChecked,
  query
});
watch(query, () => {
  scrollTop.value = 0;
  if (virtualWrapperRef.value) {
    virtualWrapperRef.value.scrollTop = 0;
  }
});
</script>

<template>
  <div :class="ns.b()">
    <!-- 头部 -->
    <div :class="ns.e('header')">
      <slot name="header">
        <div
          v-if="showAllCheckbox"
          :class="[ns.e('check-all'), {
  'is-disabled': disabled || checkableData.length === 0
}]"
          @click="handleCheckAll"
        >
          <span
            :class="[ns.e('item-checkbox'), {
  'is-checked': isAllChecked,
  'is-indeterminate': isIndeterminate
}]"
          >
            <!-- 选中图标 -->
            <svg v-if="isAllChecked" :class="ns.e('item-checkbox__icon')" viewBox="0 0 1024 1024">
              <path
                fill="currentColor"
                d="M406.4 726.4l-236.8-236.8 57.6-57.6 179.2 179.2 390.4-390.4 57.6 57.6z"
              />
            </svg>
            <!-- 半选图标 -->
            <svg
              v-if="isIndeterminate && !isAllChecked"
              :class="ns.e('item-checkbox__icon')"
              viewBox="0 0 1024 1024"
            >
              <path fill="currentColor" d="M192 480h640v64H192z" />
            </svg>
          </span>
        </div>
        <div :class="ns.e('title')">
          <span>{{ title }}</span>
          <span :class="ns.e('count')">
            {{
              totalCheckedCount > 0 ? t("transfer.hasCheckedFormat", {
  checked: totalCheckedCount,
  total: data.length
}) : t("transfer.noCheckedFormat", {
  total: data.length
})
            }}
          </span>
        </div>
      </slot>
    </div>

    <!-- 搜索框 -->
    <div v-if="filterable" :class="ns.e('filter')">
      <input
        v-model="query"
        type="text"
        :class="ns.e('filter-input')"
        :placeholder="filterPlaceholder ?? t('transfer.filterPlaceholder')"
        :disabled="disabled"
      />
    </div>

    <!-- 列表区域 -->
    <div :class="ns.e('body')">
      <!-- 空状态 -->
      <div v-if="filteredData.length === 0" :class="ns.e('empty')">
        <slot name="empty">
          <svg :class="ns.e('empty-icon')" viewBox="0 0 1024 1024">
            <path
              fill="currentColor"
              d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"
            />
            <path
              fill="currentColor"
              d="M464 336a48 48 0 1096 0 48 48 0 10-96 0zM464 512v176c0 8.8 7.2 16 16 16h64c8.8 0 16-7.2 16-16V512c0-8.8-7.2-16-16-16h-64c-8.8 0-16 7.2-16 16z"
            />
          </svg>
          <span :class="ns.e('empty-text')">{{ emptyText || t("transfer.noData") }}</span>
        </slot>
      </div>

      <!-- 虚拟滚动列表 -->
      <template v-else-if="virtual">
        <div
          ref="virtualWrapperRef"
          :class="ns.e('virtual-wrapper')"
          :style="{
  height: height + 'px'
}"
          @scroll="handleVirtualScroll"
        >
          <div :style="{
  height: virtualConfig.totalHeight + 'px',
  position: 'relative'
}">
            <ul
              :class="ns.e('list')"
              :style="{
  transform: `translateY(${virtualConfig.offsetY}px)`
}"
            >
              <li
                v-for="item in displayItems"
                :key="getKey(item)"
                :class="[ns.e('item'), {
  'is-checked': isChecked(getKey(item)),
  'is-disabled': isItemDisabled(item)
}]"
                :style="{
  height: itemHeight + 'px'
}"
                @click="handleItemClick(item)"
              >
                <span :class="[ns.e('item-checkbox'), {
  'is-checked': isChecked(getKey(item))
}]">
                  <svg
                    v-if="isChecked(getKey(item))"
                    :class="ns.e('item-checkbox__icon')"
                    viewBox="0 0 1024 1024"
                  >
                    <path
                      fill="currentColor"
                      d="M406.4 726.4l-236.8-236.8 57.6-57.6 179.2 179.2 390.4-390.4 57.6 57.6z"
                    />
                  </svg>
                </span>
                <span :class="ns.e('item-label')">
                  <slot :option="item">{{ getLabel(item) }}</slot>
                </span>
              </li>
            </ul>
          </div>
        </div>
      </template>

      <!-- 普通列表 -->
      <ul v-else :class="ns.e('list')">
        <li
          v-for="item in displayItems"
          :key="getKey(item)"
          :class="[ns.e('item'), {
  'is-checked': isChecked(getKey(item)),
  'is-disabled': isItemDisabled(item)
}]"
          @click="handleItemClick(item)"
        >
          <span :class="[ns.e('item-checkbox'), {
  'is-checked': isChecked(getKey(item))
}]">
            <svg
              v-if="isChecked(getKey(item))"
              :class="ns.e('item-checkbox__icon')"
              viewBox="0 0 1024 1024"
            >
              <path
                fill="currentColor"
                d="M406.4 726.4l-236.8-236.8 57.6-57.6 179.2 179.2 390.4-390.4 57.6 57.6z"
              />
            </svg>
          </span>
          <span :class="ns.e('item-label')">
            <slot :option="item">{{ getLabel(item) }}</slot>
          </span>
        </li>
      </ul>
    </div>

    <!-- 底部插槽 -->
    <div v-if="$slots.footer" :class="ns.e('footer')">
      <slot name="footer" />
    </div>
  </div>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
/* 穿梭框面板独立样式 */
.yh-transfer-panel {
  display: inline-flex;
  flex-direction: column;
  background: var(--yh-fill-color-blank, #fff);
  border: 1px solid var(--yh-border-color-lighter, #ebeef5);
  border-radius: var(--yh-radius-base, 4px);
  overflow: hidden;
  box-sizing: border-box;
  width: 200px;
  height: 300px;
}
.yh-transfer-panel__header {
  height: 40px;
  background: var(--yh-fill-color-light, #f5f7fa);
  padding: 0 12px;
  border-bottom: 1px solid var(--yh-border-color-lighter, #ebeef5);
  display: flex;
  align-items: center;
  color: var(--yh-text-color-primary, #303133);
  box-sizing: border-box;
}

.yh-transfer-panel__check-all {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-right: 10px;
}
.yh-transfer-panel__check-all.is-disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.yh-transfer-panel__title {
  flex: 1;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.yh-transfer-panel__count {
  font-size: 12px;
  color: var(--yh-text-color-secondary, #909399);
  margin-left: 4px;
}

.yh-transfer-panel__filter {
  padding: 10px;
  box-sizing: border-box;
}
.yh-transfer-panel__filter-input {
  width: 100%;
  height: 32px;
  padding: 0 10px;
  border: 1px solid var(--yh-border-color, #dcdfe6);
  border-radius: var(--yh-radius-base, 4px);
  font-size: 12px;
  outline: none;
  box-sizing: border-box;
  transition: border-color var(--yh-transition-base, 0.2s);
}
.yh-transfer-panel__filter-input:focus {
  border-color: var(--yh-color-primary, #409eff);
}

.yh-transfer-panel__body {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
}

.yh-transfer-panel__list {
  margin: 0;
  padding: 6px 0;
  list-style: none;
  flex: 1;
  overflow-y: auto;
  box-sizing: border-box;
}

.yh-transfer-panel__virtual-wrapper {
  overflow-y: auto;
  width: 100%;
  flex: 1;
}

.yh-transfer-panel__item {
  padding: 0 12px;
  height: 30px;
  line-height: 30px;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: var(--yh-text-color-regular, #606266);
}
.yh-transfer-panel__item:hover:not(.is-disabled) {
  background: var(--yh-fill-color-light, #f5f7fa);
  color: var(--yh-color-primary, #409eff);
}
.yh-transfer-panel__item.is-disabled {
  color: var(--yh-text-color-disabled, #c0c4cc);
  cursor: not-allowed;
}

.yh-transfer-panel__item-checkbox {
  width: 14px;
  height: 14px;
  border: 1px solid var(--yh-border-color, #dcdfe6);
  border-radius: 2px;
  margin-right: 8px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: var(--yh-fill-color-blank, #fff);
  position: relative;
  flex-shrink: 0;
  transition: all 0.2s;
}
.yh-transfer-panel__item-checkbox.is-checked {
  background-color: var(--yh-color-primary, #409eff);
  border-color: var(--yh-color-primary, #409eff);
  color: #fff;
}

.yh-transfer-panel__item-checkbox.is-indeterminate {
  background-color: var(--yh-color-primary, #409eff);
  border-color: var(--yh-color-primary, #409eff);
  color: #fff;
}

.yh-transfer-panel__item-checkbox__icon {
  width: 100%;
  height: 100%;
  transform: scale(0.8);
}

.yh-transfer-panel__item-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.yh-transfer-panel__empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--yh-text-color-secondary, #909399);
  padding: 20px 0;
}
.yh-transfer-panel__empty-text {
  font-size: 14px;
}

.yh-transfer-panel__empty-icon {
  width: 48px;
  height: 48px;
  margin-bottom: 8px;
  color: var(--yh-border-color-light, #dcdfe6);
}

.yh-transfer-panel__footer {
  border-top: 1px solid var(--yh-border-color-lighter, #ebeef5);
  background: var(--yh-fill-color-blank, #fff);
}

/* 穿梭框整体样式 */
.yh-transfer {
  display: inline-flex;
  align-items: center;
  font-size: 14px;
  vertical-align: middle;
}
.yh-transfer__buttons {
  display: inline-flex;
  flex-direction: column;
  padding: 0 12px;
  gap: 10px;
}

.yh-transfer__button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 32px;
  height: 32px;
  border-radius: 4px;
  border: 1px solid var(--yh-border-color, #dcdfe6);
  background: var(--yh-fill-color-light, #f5f7fa);
  color: var(--yh-text-color-regular, #909399);
  cursor: pointer;
  padding: 0 10px;
  transition: var(--yh-transition-base, 0.3s);
  white-space: nowrap;
}
.yh-transfer__button:hover:not(:disabled) {
  color: var(--yh-color-primary, #409eff);
  border-color: var(--yh-color-primary, #409eff);
}
.yh-transfer__button.is-active:not(:disabled) {
  background: var(--yh-color-primary, #409eff);
  color: #fff;
  border-color: var(--yh-color-primary, #409eff);
}

.yh-transfer__button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}
.yh-transfer__button svg {
  width: 14px;
  height: 14px;
}
.yh-transfer__text {
  margin: 0 4px;
}

.yh-transfer {
  /* 尺寸支持 */
}
.yh-transfer--large .yh-transfer-panel {
  width: 240px;
  height: 360px;
}

.yh-transfer--small .yh-transfer-panel {
  width: 180px;
  height: 260px;
}
</style>
