<template>
  <el-dialog title="皮肤设置" v-model="visible" width="900px" class="skin-dialog" :close-on-click-modal="false"
    :before-close="handleDialogCancel">
    <div class="skin-content">
      <h4 class="section-title">选择皮肤颜色</h4>

      <div class="theme-list">
        <div v-for="item in themes" :key="item.value" class="theme-item"
          :class="{ active: currentThemeValue === item.value }">
          <div class="theme-preview" :style="getThemePreviewStyle(item)" @click="selectTheme(item.value)">
            <div class="header" :style="{ background: getThemeColor(item) }"></div>
            <div class="body" :class="{ dark: item.value === 'black' }">
              <div class="logo" :style="{ color: getThemeColor(item), borderColor: getThemeColor(item,0.33) }">
                <SvgIcon name="logo" :size="12" class="mr-2" />
                <span>康策CRM8.0</span>
              </div>
              <div class="line-wrap" :style="{ color: getThemeColor(item,0.33) }">
                <div class="avatar-fake"></div>
                <div class="lines">
                  <div class="line short"></div>
                  <div class="line"></div>
                </div>
              </div>
            </div>
          </div>

          <div class="theme-radio custom-theme-radio">
            <el-radio style="margin-right: 0;" :model-value="currentThemeValue" :label="item.value"
              @change="selectTheme(item.value)">
              {{ item.label }}
            </el-radio>
            <template v-if="item.value === 'custom'">
              <el-button link class="edit-custom-btn" @click.stop="toggleCustomColorPanel">
                <!-- 编辑 -->
                <el-icon :size="14">
                  <EditPen />
                </el-icon>
              </el-button>
              <div class="custom-color-panel" :class="{ appear: showCustomPanel }" @click.stop>
                <CustomColorPicker :model-value="draftCustomColor" :visible="showCustomPanel"
                  @update:modelValue="handleCustomColorChange" />
                <div class="custom-color-panel__actions">
                  <el-button size="small" @click="cancelCustomColor">取消</el-button>
                  <el-button size="small" type="primary" @click="confirmCustomColor">确认</el-button>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleDialogCancel">取消</el-button>
      <el-button type="primary" @click="setAsDefault">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, onBeforeUnmount, ref } from "vue";
import { useThemeStore } from "@/stores/theme";
import { ElMessage } from "element-plus";
import CustomColorPicker from "@/components/themeSwitch/CustomColorPicker.vue";
import { EditPen } from '@element-plus/icons-vue';
import { applyAlphaToColor } from "@/utils/index.js";

const visible = ref(false);
const themeStore = useThemeStore();
const draftCustomColor = ref(themeStore.customThemeColor);
const showCustomPanel = ref(false);
const panelInitialColor = ref(themeStore.customThemeColor);
const panelInitialTheme = ref(themeStore.themeValue);
const dialogInitialColor = ref(themeStore.customThemeColor);
const dialogInitialTheme = ref(themeStore.themeValue);
let previewFrameId = 0;
let pendingPreviewColor = themeStore.customThemeColor;

const themes = [
  {
    label: "穹宇蓝",
    value: "blue",
    color: "#1764FF",
    previewBg: "linear-gradient(180deg, #E6EEFF 0%, #F5F8FF 100%)",
    className: "blue",
  },
  {
    label: "星轨紫",
    value: "purple",
    color: "#8649FB",
    previewBg: "linear-gradient(180deg, #F3E9FF 0%, #FBF7FF 100%)",
    className: "purple",
  },
  {
    label: "青岚绿",
    value: "green",
    color: "#29A181",
    previewBg: "linear-gradient(180deg, #E7F6F0 0%, #F4FBF8 100%)",
    className: "green",
  },
  {
    label: "曜石黑",
    value: "black",
    color: "#000000",
    previewBg: "#2B2B2B",
    className: "dark",
  },
  {
    label: "自定义颜色",
    value: "custom",
    color: themeStore.customThemeColor,
    previewBg: "linear-gradient(180deg, #E9EEF8 0%, #FFFFFF 100%)",
    className: "custom",
  },
];

const currentThemeValue = computed(() => themeStore.themeValue);

const getThemeColor = (item, alpha = 1) => {
  const color = item.value === "custom" ? themeStore.customThemeColor : item.color;
  return applyAlphaToColor(color, alpha);
};

const getThemePreviewStyle = (item) => ({
  background: item.value === "custom"
    ? `linear-gradient(180deg, ${themeStore.buildCustomThemeVars(themeStore.customThemeColor)['--el-color-primary-light-8']} 0%, #FFFFFF 100%)`
    : item.previewBg,
  borderColor: currentThemeValue.value === item.value ? getThemeColor(item) : '#e5e5e5',
});

const open = () => {
  clearScheduledPreview();
  dialogInitialColor.value = themeStore.customThemeColor;
  dialogInitialTheme.value = themeStore.themeValue;
  draftCustomColor.value = themeStore.customThemeColor;
  showCustomPanel.value = false;
  visible.value = true;
};
defineExpose({ open });

const restoreThemeState = (theme, color) => {
  draftCustomColor.value = color;
  themeStore.setCustomThemeColor(color);
  themeStore.setTheme(theme);
};

const clearScheduledPreview = () => {
  if (!previewFrameId) return;
  cancelAnimationFrame(previewFrameId);
  previewFrameId = 0;
};

const scheduleCustomColorPreview = (color) => {
  pendingPreviewColor = color;

  if (previewFrameId) return;

  previewFrameId = requestAnimationFrame(() => {
    previewFrameId = 0;
    themeStore.previewCustomThemeColor(pendingPreviewColor);
    if (themeStore.themeValue !== 'custom') {
      themeStore.setTheme('custom');
    }
  });
};

onBeforeUnmount(() => {
  clearScheduledPreview();
});

const toggleCustomColorPanel = () => {
  if (!showCustomPanel.value) {
    panelInitialColor.value = themeStore.customThemeColor;
    panelInitialTheme.value = themeStore.themeValue;
    draftCustomColor.value = themeStore.customThemeColor;
    if (themeStore.themeValue !== 'custom') {
      themeStore.setTheme('custom');
    }
  }

  showCustomPanel.value = true;
};

const selectTheme = (value) => {
  if (value === 'custom') {
    themeStore.previewCustomThemeColor(draftCustomColor.value);
  }
  themeStore.setTheme(value);
};

const handleCustomColorChange = (color) => {
  if (!color) return;
  draftCustomColor.value = color;
  scheduleCustomColorPreview(color);
};

const cancelCustomColor = () => {
  clearScheduledPreview();
  restoreThemeState(panelInitialTheme.value, panelInitialColor.value);
  showCustomPanel.value = false;
};

const confirmCustomColor = () => {
  clearScheduledPreview();
  themeStore.setCustomThemeColor(draftCustomColor.value);
  themeStore.setTheme('custom');
  showCustomPanel.value = false;
};

const setAsDefault = () => {
  clearScheduledPreview();
  if (themeStore.themeValue === 'custom') {
    themeStore.setCustomThemeColor(draftCustomColor.value);
  }
  themeStore.setTheme(themeStore.themeValue);
  showCustomPanel.value = false;
  visible.value = false;
  ElMessage.success('设置主题成功！');
};

const handleDialogCancel = (done) => {
  clearScheduledPreview();
  restoreThemeState(dialogInitialTheme.value, dialogInitialColor.value);
  showCustomPanel.value = false;
  visible.value = false;
  if (typeof done === 'function') done();
};
</script>


<style scoped lang="scss">
.skin-dialog .el-dialog__body {
  padding: 20px 30px;
}

.skin-content {
  text-align: left;
}

.section-title {
  color: #999;
  margin-bottom: 20px;
  font-weight: normal;
}

.theme-list {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 20px;
}

.theme-item {
  text-align: center;
  cursor: pointer;
  min-width: 0;
  max-width: none;
  position: relative;
}

.theme-preview {
  border: 2px solid #e5e5e5;
  border-radius: 6px;
  height: 121px;
  margin-bottom: 10px;
  overflow: hidden;
  transition: all 0.3s;
  padding: 16px 0 0 16px;
}

.theme-item.active .theme-preview {
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}

.theme-preview .header {
  height: 22px;
  width: 60px;
  border-radius: 6px;
  margin-bottom: 10px;
}

.theme-preview .body {
  background-color: #fff;
  border-radius: 6px;
  height: 999px;
}

.theme-preview .body.dark {
  background: rgba(255, 255, 255, 0.04);
}

.theme-preview .logo {
  font-size: 12px;
  height: 22px;
  border-bottom-width: 2px;
  border-bottom-style: solid;
  display: flex;
  align-items: center;
  line-height: 1;
  padding-left: 10px;
}

.theme-preview .line-wrap {
  height: 50px;
  display: flex;
  padding-left: 10px;
  align-items: center;
  gap: 5px;

  .avatar-fake {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: currentColor;
  }

  .lines {
    display: flex;
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;

    .line {
      width: 100px;
      height: 6px;
      border-radius: 3px;
      background-color: currentColor;
    }

    .line.short {
      width: 60px;
    }
  }
}

.theme-radio {
  font-size: 14px;
}

.custom-theme-radio {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.edit-custom-btn {
  padding: 0;
  font-size: 12px;
}

.custom-color-panel {
  position: absolute;
  top: 50%;
  left: calc(100% + 10px);
  transform: translateY(-50%) translateX(-100%);
  z-index: 30;
  padding: 12px;
  background: #fff;
  border: 1px solid var(--el-border-color-light);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  overflow: visible;
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s ease;

  &.appear {
    opacity: 1;
    pointer-events: auto;
    transform: translateY(-50%) translateX(0);
  }
}

.custom-color-panel {
  min-width: 332px;
}

.custom-color-panel__actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 12px;
}

.dialog-footer {
  text-align: right;
}
</style>
