<template>
  <transition name="brush-control-canel-fade">
    <div v-if="isVisible" class="brush-control-panel">
      <!-- 笔刷大小控制 -->
      <VerticalSlider
        v-model="brushSize"
        :min="1"
        :max="100"
        :presets="sizePresets"
        :memorized-values="memorizedSizes"
        :active-threshold="1"
        custom-class="size-slider"
        :step="1"
        v-model:showTooltip="showSizeTooltip"
        @slide-start="handleSizeSlideStart"
        @slide-end="handleSizeSlideEnd"
        @click="showSizeTooltip = true"
      >
        <template #tooltip-content>
          <div class="tooltip-header">
            <div class="tooltip-title">Size</div>
            <div class="tooltip-close-btn" @click.stop="closeSizeTooltip">
              <SvgIcon name="CClose" size="20" />
            </div>
          </div>
          <div class="brush-preview-container">
            <div
              class="brush-size-preview"
              :style="{
                width: `${Math.min(100, brushSize)}px`,
                height: `${Math.min(100, brushSize)}px`,
                backgroundColor: showColorPicker ? brushColor : '#888888',
              }"
            ></div>
          </div>
          <div class="tooltip-content">
            <div class="tooltip-text">{{ Math.round(brushSize) }}px</div>
            <div class="tooltip-controls">
              <button
                v-if="!memorizedSizes.includes(brushSize)"
                class="control-btn add"
                @click="memorizeSize"
              >
                +
              </button>
              <button class="control-btn remove" @click="removeMemorizedSize" v-if="canRemoveSize">
                -
              </button>
            </div>
          </div>
        </template>
      </VerticalSlider>

      <!-- 1.这里加上过渡动画 颜色选择器 - 仅在特定工具下显示 -->
      <transition name="color-picker-fade" mode="out-in">
        <div v-if="showColorPicker" class="color-picker-container" key="color-picker">
          <label for="color-picker" class="current-color-label">
            <div class="current-color" :style="{ backgroundColor: brushColor }"></div>
          </label>
          <input
            type="color"
            id="color-picker"
            class="system-color-picker"
            v-model="customColor"
            @input="setBrushColor(customColor)"
          />
        </div>
      </transition>

      <!-- 2.这里加上过渡动画 透明度控制 - 仅在特定工具下显示 -->
      <transition name="opacity-slider-fade" mode="out-in">
        <VerticalSlider
          v-if="showOpacitySlider"
          key="opacity-slider"
          v-model="brushOpacity"
          :min="0"
          :max="1"
          :presets="opacityPresets"
          :memorized-values="memorizedOpacities"
          :is-percentage="true"
          custom-class="opacity-slider"
          :active-threshold="0.01"
          :step="0.01"
          v-model:showTooltip="showOpacityTooltip"
          @slide-start="handleOpacitySlideStart"
          @slide-end="handleOpacitySlideEnd"
          @click="showOpacityTooltip = true"
        >
          <template #tooltip-content>
            <div class="tooltip-header">
              <div class="tooltip-title">Opacity</div>
              <div class="tooltip-close-btn" @click.stop="closeOpacityTooltip">
                <SvgIcon name="CClose" size="20" />
              </div>
            </div>
            <div class="opacity-preview">
              <div class="opacity-checker"></div>
              <div
                class="opacity-color"
                :style="{
                  backgroundColor: brushColor,
                  opacity: brushOpacity,
                }"
              ></div>
            </div>
            <div class="tooltip-content">
              <div class="tooltip-text">{{ Math.round(brushOpacity * 100) }}%</div>
              <div class="tooltip-controls">
                <button
                  class="control-btn add"
                  v-if="!memorizedOpacities.includes(brushOpacity)"
                  @click="memorizeOpacity"
                >
                  +
                </button>
                <button
                  class="control-btn remove"
                  @click="removeMemorizedOpacity"
                  v-if="canRemoveOpacity"
                >
                  -
                </button>
              </div>
            </div>
          </template>
        </VerticalSlider>
      </transition>
    </div>
  </transition>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from "vue";
import { BrushStore } from "../store/BrushStore";
import { OperationType } from "../utils/layerHelper";
import { inject } from "vue";
import VerticalSlider from "./VerticalSlider.vue";

const props = defineProps({
  activeTool: {
    type: String,
    required: true,
  },
});

// 工具管理器和画布管理器
const toolManager = inject("toolManager");
const canvasManager = inject("canvasManager");

// 可见性控制
const isVisible = computed(() => {
  return [
    OperationType.DRAW,
    OperationType.ERASER,
    OperationType.RED_BRUSH,
    OperationType.GREEN_BRUSH,
  ].includes(props.activeTool);
});

// 控制颜色选择器的显示
const showColorPicker = computed(() => {
  return props.activeTool === OperationType.DRAW;
});

// 控制透明度滑块的显示
const showOpacitySlider = computed(() => {
  return props.activeTool === OperationType.DRAW;
});

// 笔刷大小相关
const brushSize = ref(BrushStore.state.size);
const showSizeTooltip = ref(false);
const sizePresets = ref([5, 10, 20, 50]); // 预设大小，便于吸附
const memorizedSizes = ref([]);
const canRemoveSize = computed(() => {
  return memorizedSizes.value.includes(brushSize.value);
});
const isSizeSliding = ref(false); // 是否正在滑动大小滑块

// 笔刷颜色相关
const brushColor = ref(BrushStore.state.color);
const customColor = ref(BrushStore.state.color);

// 笔刷透明度相关
const brushOpacity = ref(BrushStore.state.opacity);
const showOpacityTooltip = ref(false);
const opacityPresets = ref([0.1, 0.2, 0.5, 0.8]); // 预设透明度，便于吸附
const memorizedOpacities = ref([]);
const canRemoveOpacity = computed(() => {
  return memorizedOpacities.value.includes(brushOpacity.value);
});
const isOpacitySliding = ref(false); // 是否正在滑动透明度滑块

// 添加计时器变量用于控制外部变化引起的提示框自动隐藏
const sizeTooltipTimer = ref(null);
const opacityTooltipTimer = ref(null);
const TOOLTIP_HIDE_DELAY = 1500; // 与VerticalSlider组件保持一致的延迟时间

// 处理滑块开始和结束事件
function handleSizeSlideStart() {
  isSizeSliding.value = true;
}

function handleSizeSlideEnd(event) {
  isSizeSliding.value = false;
}

function handleOpacitySlideStart() {
  isOpacitySliding.value = true;
}

function handleOpacitySlideEnd(event) {
  isOpacitySliding.value = false;
}

// 设置笔刷大小
function setBrushSize(size) {
  brushSize.value = size;
  BrushStore.setBrushSize(size);

  // 如果工具管理器存在，立即应用此更改
  if (toolManager) {
    toolManager.updateBrushSize(size);
  }
}

// 设置笔刷颜色
function setBrushColor(color) {
  brushColor.value = color;
  customColor.value = color;
  BrushStore.setBrushColor(color);

  // 如果工具管理器存在，立即应用此更改
  if (toolManager && props.activeTool === OperationType.DRAW) {
    toolManager.updateBrushColor(color);
  }
}

// 设置笔刷透明度
function setBrushOpacity(opacity) {
  brushOpacity.value = opacity;
  BrushStore.setBrushOpacity(opacity);

  // 如果工具管理器存在，立即应用此更改
  if (toolManager) {
    toolManager.updateBrushOpacity(opacity);

    // 同时更新颜色以确保透明度生效
    const currentColor = BrushStore.state.color;
    if (currentColor) {
      toolManager.updateBrushColor(currentColor);
    }
  }
}

// 添加用于自动隐藏大小提示框的方法
function startSizeTooltipHideTimer() {
  // 清除已有的计时器
  clearSizeTooltipTimer();

  // 创建新计时器
  sizeTooltipTimer.value = setTimeout(() => {
    showSizeTooltip.value = false;
    sizeTooltipTimer.value = null;
  }, TOOLTIP_HIDE_DELAY);
}

// 清除大小提示框隐藏计时器
function clearSizeTooltipTimer() {
  if (sizeTooltipTimer.value) {
    clearTimeout(sizeTooltipTimer.value);
    sizeTooltipTimer.value = null;
  }
}

// 添加用于自动隐藏透明度提示框的方法
function startOpacityTooltipHideTimer() {
  // 清除已有的计时器
  clearOpacityTooltipTimer();

  // 创建新计时器
  opacityTooltipTimer.value = setTimeout(() => {
    showOpacityTooltip.value = false;
    opacityTooltipTimer.value = null;
  }, TOOLTIP_HIDE_DELAY);
}

// 清除透明度提示框隐藏计时器
function clearOpacityTooltipTimer() {
  if (opacityTooltipTimer.value) {
    clearTimeout(opacityTooltipTimer.value);
    opacityTooltipTimer.value = null;
  }
}

// 主动关闭提示框
function closeSizeTooltip() {
  showSizeTooltip.value = false;
  clearSizeTooltipTimer(); // 清除任何存在的计时器
}

function closeOpacityTooltip() {
  showOpacityTooltip.value = false;
  clearOpacityTooltipTimer(); // 清除任何存在的计时器
}

// 记忆当前笔刷大小
function memorizeSize() {
  if (!memorizedSizes.value.includes(brushSize.value)) {
    memorizedSizes.value.push(brushSize.value);
    // 记忆值限制为最多5个
    if (memorizedSizes.value.length > 5) {
      memorizedSizes.value.shift();
    }
  }
}

// 删除当前记忆的笔刷大小
function removeMemorizedSize() {
  if (memorizedSizes.value.includes(brushSize.value)) {
    const index = memorizedSizes.value.indexOf(brushSize.value);
    memorizedSizes.value.splice(index, 1);
  }
}

// 记忆当前笔刷透明度
function memorizeOpacity() {
  if (!memorizedOpacities.value.includes(brushOpacity.value)) {
    memorizedOpacities.value.push(brushOpacity.value);
    // 记忆值限制为最多5个
    if (memorizedOpacities.value.length > 5) {
      memorizedOpacities.value.shift();
    }
  }
}

// 删除当前记忆的笔刷透明度
function removeMemorizedOpacity() {
  if (memorizedOpacities.value.includes(brushOpacity.value)) {
    const index = memorizedOpacities.value.indexOf(brushOpacity.value);
    memorizedOpacities.value.splice(index, 1);
  }
}

// 监听工具的变化
watch(
  () => props.activeTool,
  (newTool) => {
    // 当切换到橡皮擦工具时，可以设置特殊的默认值
    if (newTool === OperationType.ERASER) {
      // 橡皮擦模式下不需要调整颜色，但可能会调整大小和不透明度
    } else if (newTool === OperationType.DRAW) {
      // 恢复到绘制模式时可能有特殊设置
    }
  }
);

// 监听brushSize的变化，更新到BrushStore
watch(
  () => brushSize.value,
  (newSize) => {
    setBrushSize(newSize);
  }
);
watch(()=>isVisible.value, (newVisible) => {
  if (newVisible) {
    setBrushSize(brushSize.value);
  }
})

// 监听brushOpacity的变化，更新到BrushStore
watch(
  () => brushOpacity.value,
  (newOpacity) => {
    setBrushOpacity(newOpacity);
  }
);

// 监听BrushStore中的变化
watch(
  () => BrushStore.state.size,
  (newSize) => {
    if (Math.abs(brushSize.value - newSize) > 0.1) {
      brushSize.value = newSize;
      // 当外部修改了笔刷大小时，显示提示框
      showSizeTooltip.value = true;
      // 启动自动隐藏计时器
      startSizeTooltipHideTimer();
    }
  }
);

watch(
  () => BrushStore.state.opacity,
  (newOpacity) => {
    if (Math.abs(brushOpacity.value - newOpacity) > 0.01) {
      brushOpacity.value = newOpacity;
      // 当外部修改了笔刷透明度时，显示提示框
      showOpacityTooltip.value = true;
      // 启动自动隐藏计时器
      startOpacityTooltipHideTimer();
    }
  }
);

watch(
  () => BrushStore.state.color,
  (newColor) => {
    if (brushColor.value !== newColor) {
      brushColor.value = newColor;
      customColor.value = newColor;
    }
  }
);

onMounted(() => {
  // 初始化时从BrushStore获取当前值
  brushSize.value = BrushStore.state.size;
  brushOpacity.value = BrushStore.state.opacity;
  brushColor.value = BrushStore.state.color;
  customColor.value = BrushStore.state.color;
});

onBeforeUnmount(() => {
  // 组件卸载前清除所有计时器
  clearSizeTooltipTimer();
  clearOpacityTooltipTimer();
});

// 监听showSizeTooltip和showOpacityTooltip的变化，防止两个滑块的提示框同时显示
watch(
  () => showSizeTooltip.value,
  (newValue) => {
    if (newValue && showOpacityTooltip.value) {
      // 如果大小提示框显示，则隐藏透明度提示框
      showOpacityTooltip.value = false;
    }
  }
);

watch(
  () => showOpacityTooltip.value,
  (newValue) => {
    if (newValue && showSizeTooltip.value) {
      // 如果透明度提示框显示，则隐藏大小提示框
      showSizeTooltip.value = false;
    }
  }
);
</script>

<style scoped lang="less">
.brush-control-panel {
  position: absolute;
  top: 50%;
  left: 15px;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1.5rem;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 5px;
  padding: 1.5rem 3px;
  box-shadow:
    0 4px 20px rgba(0, 0, 0, 0.1),
    0 0 0 1px rgba(0, 0, 0, 0.05);
  z-index: 8;
  backdrop-filter: blur(2px);
  color: #333;
  user-select: none;
  -webkit-user-select: none;

  // 添加高度过渡动画
  transition:
    height 0.3s ease-out,
    min-height 0.3s ease-out;
  // overflow: hidden;

  transform: translate3d(0, -50%, 0); // 确保使用3D变换以提高性能
  opacity: 1;
}

// 笔刷大小预览相关样式
.brush-preview-container {
  width: 11rem;
  height: 11rem;
  display: flex;
  justify-content: center;
  align-items: center;
  background: repeating-conic-gradient(#F9FAFA 0% 25%, #ffffff 0% 50%) 50% / 10px 10px;
  border-radius: 6px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 5px;
}

.brush-size-preview {
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  max-width: 100%;
  max-height: 100%;
}

// 透明度预览相关样式
.opacity-preview {
  width: 11rem;
  height: 11rem;
  border-radius: 6px;
  overflow: hidden;
  position: relative;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 5px;
}

.opacity-checker {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: repeating-conic-gradient(#F9FAFA 0% 25%, #ffffff 0% 50%) 50% / 10px 10px;
}

.opacity-color {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

// 工具提示内容样式
.tooltip-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.tooltip-text {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  background: #F9FAFA;
  padding: 2px 8px;
  border-radius: 4px;
  min-width: 50px;
  text-align: center;
}

.tooltip-controls {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 3px;
}

.control-btn {
  width: 2.4rem;
  height: 2.4rem;
  border: none;
  border-radius: 4px;
  background: #f0f0f0;
  color: #333;
  cursor: pointer;
  font-size: 1.6rem;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);

  &:hover {
    background: #e0e0e0;
  }

  &:active {
    transform: scale(0.95);
  }

  &.add {
    color: #4caf50;

    &:hover {
      background: rgba(76, 175, 80, 0.1);
    }
  }

  &.remove {
    color: #f44336;

    &:hover {
      background: rgba(244, 67, 54, 0.1);
    }
  }
}

// 颜色选择器样式
.color-picker-container {
  position: relative;
  width: 100%;
  display: flex;
  justify-content: center;
}

.current-color-label {
  cursor: pointer;
}

.current-color {
  width: 3.2rem;
  height: 3.2rem;
  border-radius: 8px;
  border: 2px solid #fff;
  box-shadow:
    0 2px 6px rgba(0, 0, 0, 0.15),
    0 0 0 1px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
  cursor: pointer;

  &:hover {
    transform: scale(1.05);
    box-shadow:
      0 4px 8px rgba(0, 0, 0, 0.2),
      0 0 0 1px rgba(0, 0, 0, 0.1);
  }
}

.system-color-picker {
  width: 0;
  height: 0;
  opacity: 0;
  position: absolute;
  pointer-events: none;
}

// 工具提示标题和关闭按钮
.tooltip-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.tooltip-title {
  font-size: 1.6rem;
  color: #333;
  font-weight: 600;
}

.tooltip-close-btn {
  position: absolute;
  right: 3px;
  top: 3px;
  width: 2rem;
  height: 2rem;
  border: none;
  background: transparent;
  color: #999;
  font-size: 1.6rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  padding: 0;
  margin: 0;
  transition: all 0.2s ease;
  z-index: 99;

  &:hover {
    background: rgba(0, 0, 0, 0.05);
    color: #333;
  }

  &:active {
    transform: scale(0.9);
  }
}

// 淡入淡出动画
.brush-control-canel-fade-enter-active,
.brush-control-canel-fade-leave-active {
  transition:
    opacity 0.3s,
    transform 0.3s;
}
.brush-control-canel-fade-enter-from,
.brush-control-canel-fade-leave-to {
  opacity: 0;
  transform: translateX(-10px) translateY(-50%);
}

// 颜色选择器过渡动画
.color-picker-fade-enter-active,
.color-picker-fade-leave-active {
  transition:
    opacity 0.25s ease-out,
    transform 0.25s ease-out;
}
.color-picker-fade-enter-from,
.color-picker-fade-leave-to {
  opacity: 0;
  transform: translateY(-8px) scale(0.95);
}

// 透明度滑块过渡动画
.opacity-slider-fade-enter-active,
.opacity-slider-fade-leave-active {
  transition:
    opacity 0.25s ease-out,
    transform 0.25s ease-out;
}
.opacity-slider-fade-enter-from,
.opacity-slider-fade-leave-to {
  opacity: 0;
  transform: translateY(8px) scale(0.95);
}

// 响应式调整
@media (max-height: 600px) {
  .brush-control-panel {
    gap: 10px;
  }
}

@media (max-width: 768px) {
  .brush-control-panel {
    left: 10px;
    padding: 12px 3px;
  }
}
</style>
