<template>
  <div>
    <van-cell-group class="">
      <van-cell icon="bulb-o" title="暗黑模式">
        <van-switch v-model="isDarkMode" />
      </van-cell>
      <van-cell icon="gem-o" title="主题颜色">
        <el-color-picker v-model="themeColor" :predefine="predefineColors" @change="themeChange" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script setup>
import { toggleTheme, setThemeColor } from "@/utils/index";
const { proxy } = getCurrentInstance();
const store = useStore();

const themeColor = ref(store.state.settings.theme);
const predefineColors = ref([
  // "#409EFF",
  "#20A884",
  "#ff4500",
  "#ff8c00",
  "#ffd700",
  "#90ee90",
  "#00ced1",
  "#1e90ff",
  "#c71585",
]);

const storeSettings = computed(() => store.state.settings);
const isDarkMode = computed({
  get: () => store.state.settings.sideTheme === "theme-dark",
  set: (val) => {
    handleTheme(val ? "theme-dark" : "theme-light");
  },
});

function handleTheme(val) {
  store.dispatch("settings/changeSetting", {
    key: "sideTheme",
    value: val,
  });
  let addClassString = val.split("-")[1];
  toggleTheme(addClassString);
  saveSetting();
}

function themeChange(val) {
  store.dispatch("settings/changeSetting", {
    key: "theme",
    value: val,
  });
  themeColor.value = val;
  setThemeColor(val);
  saveSetting();
  // localStorage.setItem("color-setting", JSON.stringify(form.value));
}

function saveSetting() {
  let colorSettingObj = JSON.parse(localStorage.getItem("color-setting")) || {};
  colorSettingObj.elColorPrimary = themeColor.value;
  //   el.style.setProperty("--el-color-primary", "#F98F8FFF");

  proxy.$modal.loading("正在保存到本地，请稍候...");
  let layoutSetting = {
    topNav: storeSettings.value.topNav,
    tagsView: storeSettings.value.tagsView,
    fixedHeader: storeSettings.value.fixedHeader,
    sidebarLogo: storeSettings.value.sidebarLogo,
    dynamicTitle: storeSettings.value.dynamicTitle,
    sideTheme: storeSettings.value.sideTheme,
    theme: themeColor.value,
  };
  localStorage.setItem("layout-setting", JSON.stringify(layoutSetting));
  localStorage.setItem("color-setting", JSON.stringify(colorSettingObj));

  setTimeout(proxy.$modal.closeLoading(), 1000);
}
</script>