<template>
  <a-collapse
    :key="themeKey"
    :bordered="false"
    default-active-key="a"
    expand-icon-position="right"
    class="collapse-header-divide side-setting"
  >
    <a-collapse-panel key="a" :header="$t('THEME_SETTING')">
      <setting-item :title="$t('WHOLE_STYLE_SETTING')">
        <img-checkbox-group
          :default-values="[theme.mode]"
          @change="(values) => setTheme({ ...theme, mode: values[0] })"
        >
          <img-checkbox
            :title="$t('DARK_STYLE')"
            img="https://gw.alipayobjects.com/zos/rmsportal/LCkqqYNmvBEbokSDscrm.svg"
            value="dark"
          />
          <img-checkbox
            :title="$t('LIGHT_STYLE')"
            img="https://gw.alipayobjects.com/zos/rmsportal/jpRkZQMyYRryryPNtyIC.svg"
            value="light"
          />
          <img-checkbox
            :title="$t('MIX_STYLE')"
            img="https://gw.alipayobjects.com/zos/antfincdn/x8Ob%26B8cy8/LCkqqYNmvBEbokSDscrm.svg"
            value="mix"
          />
          <img-checkbox
            :title="$t('NIGHT_STYLE')"
            img="https://gw.alipayobjects.com/zos/antfincdn/hmKaLQvmY2/LCkqqYNmvBEbokSDscrm.svg"
            value="night"
          />
        </img-checkbox-group>
      </setting-item>
      <setting-item :title="$t('THEME_COLOR')">
        <color-checkbox-group
          :default-values="[palettes.indexOf(theme.color)]"
          :multiple="false"
          @change="(values, colors) => setTheme({ ...theme, color: colors[0] })"
        >
          <color-checkbox
            v-for="(color, index) in palettes"
            :key="index"
            :color="color"
            :value="index"
          />
        </color-checkbox-group>
      </setting-item>
      <a-divider />
      <setting-item :title="$t('NAVIGATION_SETTINGS')">
        <img-checkbox-group
          :default-values="[layout]"
          @change="(values) => setLayout(values[0])"
        >
          <img-checkbox
            :title="$t('SIDE_MENU_LAYOUT')"
            img="https://gw.alipayobjects.com/zos/rmsportal/JopDzEhOqwOjeNTXkoje.svg"
            value="side"
          />
          <img-checkbox
            :title="$t('TOP_MENU_LAYOUT')"
            img="https://gw.alipayobjects.com/zos/rmsportal/KDNDBbriJhLwuqMoxcAr.svg"
            value="head"
          />
          <img-checkbox
            :title="$t('MIX_MENU_LAYOUT')"
            img="https://gw.alipayobjects.com/zos/antfincdn/x8Ob%26B8cy8/LCkqqYNmvBEbokSDscrm.svg"
            value="mix"
          />
        </img-checkbox-group>
      </setting-item>
      <setting-item>
        <a-list :split="false">
          <a-list-item>
            <a-list-item-meta>
              <span slot="title">{{ $t("CONTENT_AREA_WIDTH") }}</span>
            </a-list-item-meta>

            <a-radio-group
              :options="[
                { label: $t('FLUID'), value: 'fluid' },
                { label: $t('FIXED'), value: 'static' },
              ]"
              :default-value="pageWidth"
              @change="(e) => setPageWidth(e.target.value)"
            />
          </a-list-item>
          <a-list-item>
            <a-checkbox
              :default-checked="fixedHeader"
              @change="(e) => setFixedHeader(e.target.checked)"
            >
              {{ $t("FIXED_HEADER") }}
            </a-checkbox>
          </a-list-item>
          <a-list-item>
            <a-checkbox
              :default-checked="fixedSideBar"
              @change="(e) => setFixedSideBar(e.target.checked)"
            >
              {{ $t("FIXED_SIDEBAR") }}
            </a-checkbox>
          </a-list-item>
          <a-list-item>
            <a-list-item-meta>
              <span slot="title">{{ $t("SIDE_BAR_WIDTH") }}</span>
            </a-list-item-meta>
            <div style="display: flex; align-items: center">
              <a-input-number
                id="sideMenuDefaultWidth"
                style="width: 200px"
                :default-value="sideMenuDefaultWidth"
                @change="setSideMenuWidth"
              />
              px<a-alert
                style="margin-left: 15px"
                :message="$t('EDIT_REFRESH_EFFECT')"
                banner
              />
            </div>
          </a-list-item>
        </a-list>
      </setting-item>
      <a-divider />
      <setting-item :title="$t('OTHER_SETTING')">
        <a-list :split="false">
          <a-list-item>
            <a-checkbox
              :default-checked="weekMode"
              @change="(e) => setWeekMode(e.target.checked)"
            >
              {{ $t("WEAK_MODE") }}
            </a-checkbox>
          </a-list-item>
          <!-- <a-list-item>
            <a-checkbox
              :default-checked="multiPage"
              @change="(e) => setMultiPage(e.target.checked)"
            >
              {{ $t("MULTI_PAGE_MODE") }}
            </a-checkbox>
          </a-list-item> -->
        </a-list>
      </setting-item>
      <a-divider />
      <setting-item :title="$t('PAGE_TOGGLE_ANIMATION')">
        <a-list :split="false">
          <a-list-item>
            <a-checkbox
              :default-checked="animate.disabled"
              @change="
                (e) => setAnimate({ ...animate, disabled: e.target.checked })
              "
            >
              {{ $t("DISABLE_ANIMATION") }}
            </a-checkbox>
          </a-list-item>
          <a-list-item>
            <div class="mb-1">{{ $t("ANIMATION_EFFECT") }}</div>
            <a-select
              :value="animate.name"
              :get-popup-container="getPopupContainer"
              class="select-item"
              @change="(val) => setAnimate({ ...animate, name: val })"
            >
              <a-select-option
                v-for="(item, index) in animates"
                :key="index"
                :value="item.name"
              >
                {{ item.alias }}
              </a-select-option>
            </a-select>
          </a-list-item>
          <a-list-item>
            <div class="mb-1">{{ $t("ANIMATION_DIRECTION") }}</div>
            <a-select
              :value="animate.direction"
              :get-popup-container="getPopupContainer"
              class="select-item"
              @change="(val) => setAnimate({ ...animate, direction: val })"
            >
              <a-select-option
                v-for="(item, index) in directions"
                :key="index"
                :value="item"
              >
                {{ item }}
              </a-select-option>
            </a-select>
          </a-list-item>
        </a-list>
      </setting-item>
      <setting-item>
        <a-button type="primary" :loading="saveBtnLoading" @click="saveSetting">
          <Icon type="icon-cur-save_1" :size="18" />{{ $t("SAVE") }}
        </a-button>
        <a-button
          type="dashed"
          icon="redo"
          :loading="resetBtnLoading"
          @click="resetSetting"
        >
          {{ $t("RESET") }}
        </a-button>
      </setting-item>
    </a-collapse-panel>
  </a-collapse>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import fastEqual from "fast-deep-equal";
import deepMerge from "deepmerge";
import { ColorCheckbox, ImgCheckbox } from "@/components/checkbox";
import { setting } from "@/config/theme/default";
import sysConfig from "@/config/theme/config";
import ApiConstant from "@/api/ApiConstant";
import { Icon } from "@mega-design/ui-vue";
import SettingItem from "./SettingItem";

const ColorCheckboxGroup = ColorCheckbox.Group;
const ImgCheckboxGroup = ImgCheckbox.Group;

export default {
  components: {
    ImgCheckboxGroup,
    ImgCheckbox,
    ColorCheckboxGroup,
    ColorCheckbox,
    SettingItem,
    Icon,
  },
  inject: ["defaultLayout"],
  data() {
    return {
      saveBtnLoading: false,
      resetBtnLoading: false,
      themeKey: "ThemeSetting",
    };
  },
  computed: {
    directions() {
      return this.animates.find((item) => item.name === this.animate.name)
        .directions;
    },
    ...mapState("setting", [
      "theme",
      "layout",
      "animate",
      "animates",
      "palettes",
      "multiPage",
      "weekMode",
      "fixedHeader",
      "fixedSideBar",
      "hideSetting",
      "pageWidth",
      "sideMenuDefaultWidth",
    ]),
    ...mapState({
      systemConfig: (state) => state.app.systemConfig,
    }),
  },
  watch: {
    "animate.name": function (val) {
      this.setAnimate({ name: val, direction: this.directions[0] });
    },
  },
  methods: {
    ...mapMutations("setting", [
      "setTheme",
      "setLayout",
      "setMultiPage",
      "setWeekMode",
      "setFixedSideBar",
      "setFixedHeader",
      "setAnimate",
      "setHideSetting",
      "setPageWidth",
      "setSideMenuWidth",
    ]),
    getPopupContainer() {
      return this.$el.parentNode;
    },
    saveSetting() {
      const config = this.extractConfig(true);
      this.saveBtnLoading = true;
      const value = JSON.stringify(config);
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/sys/config/update-key-value`, {
          key: "THEME_SETTINGS",
          value,
        })
        .then(() => {
          this.saveBtnLoading = false;
          this.$store.commit("app/SET_SYSTEM_CONFIG", {
            ...this.systemConfig,
            THEME_SETTINGS: value,
          });
          this.$message.success(this.$t("UPDATE_SUCCESS"));
        })
        .catch(() => {
          this.saveBtnLoading = false;
        });
    },
    resetSetting() {
      this.$confirm({
        title: this.$t("TIPS"),
        content: this.$t("RESET_THEME_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        icon: "exclamation-circle",
        onOk: () => {
          this.resetBtnLoading = true;
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/sys/config/update-key-value`, {
              key: "THEME_SETTINGS",
              value: null,
            })
            .then(() => {
              this.resetBtnLoading = false;
              this.$store.commit("app/SET_SYSTEM_CONFIG", {
                ...this.systemConfig,
                THEME_SETTINGS: "",
              });
              this.themeKey = `ThemeSetting${Math.ceil(Math.random() * 10000)}`;
              this.defaultLayout.changeTheme("");
              this.$message.success(this.$t("RESET_SUCCESS"));
            })
            .catch(() => {
              this.resetBtnLoading = false;
            });
        },
      });
    },
    // 提取配置
    extractConfig(local = false) {
      const config = {};
      const mySetting = this.$store.state.setting;
      const dftSetting = local ? deepMerge(setting, sysConfig) : setting;
      Object.keys(mySetting).forEach((key) => {
        const dftValue = dftSetting[key];
        const myValue = mySetting[key];
        if (dftValue !== undefined && !fastEqual(dftValue, myValue)) {
          config[key] = myValue;
        }
      });
      return Object.keys(config).length ? config : null;
    },
  },
};
</script>

<style lang="less" scoped>
@import (optional, once) "../../theme/index.less";
.side-setting {
  min-height: 100%;
  background-color: @base-bg-color;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
  position: relative;
  .select-item {
    width: 120px;
  }
  /deep/ .ant-list-item {
    display: block;
  }
}
</style>
