<template>
  <DesktopLayout v-if="data.show">
    <template #head>
      <div class="header-box bg-white dark:bg-dark-900">
        <div class="header">
          <DesignLogo />
          <div class="header-title">{{ title }}</div>
        </div>
        <DesignStepBox class="step">
          <a-steps :current="current">
            <a-step v-for="item in steps" :key="item.title" :title="item.title" />
          </a-steps>
        </DesignStepBox>
        <div class="button-box">
          <a-button :disabled="current == 0 || spinning" class="common-button" @click="prev">{{
            t('上一步')
          }}</a-button>
          <a-button
            :disabled="current == steps.length - 1 || spinning"
            class="common-button"
            @click="next"
            >{{ t('下一步') }}</a-button
          >
          <a-button
            :class="current == 0 ? '' : 'common-todo-button'"
            :disabled="current == 0 || spinning"
            @click="onSave(false)"
            >{{ t('暂存') }}</a-button
          >
          <a-button
            type="primary"
            :disabled="current == 0 || spinning"
            class="common-button"
            @click="onSave(true)"
            >{{ t('保存') }}</a-button
          >
          <a-button class="common-clean-button" @click="$emit('close')">{{ t('关闭') }}</a-button>
        </div>
      </div>
    </template>
    <template #steps>
      <div class="center-box" v-if="current == 1">
        <Menu @add="addComponent" @preview="onPreview" @bgimg="handleBgImage" />
      </div>
    </template>
    <Basic v-if="current == 0" ref="basic" :basicData="data.basicData" />
    <Design v-if="current == 1" ref="design" :list="data.list" :background="data.background" />
    <LoadingBox v-if="spinning" />
    <DesktopPreview
      v-if="preview.show"
      ref="previewRef"
      :list="preview.list"
      :background="data.background"
      @close="preview.show = false"
    />
  </DesktopLayout>
</template>

<script setup lang="ts">
  import { computed, onMounted, provide, reactive, ref } from 'vue';
  import { addDesktop, editDesktop, getDesktopInfo } from '/@/api/desktop/index';
  import { DesktopLayout, DesignStepBox } from '/@/components/Desktop';
  import Design from './designer/Design.vue';
  import Basic from './designer/Basic.vue';
  import Menu from './designer/Menu.vue';
  import DesktopPreview from './DesktopPreview.vue';
  import { DesignLogo } from '/@/components/ModalPanel/index';
  import { LoadingBox } from '/@/components/ModalPanel/index';
  import { BackgroundSetting, DesktopBasicData, DesktopInfoItem } from '/@/model/desktop/designer';
  import { message } from 'ant-design-vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { replaceJsonParseInfinity, replaceJsonStringifyInfinity } from '/@/utils/json';
  import { backgroundInfo } from './designer/config/info';

  const { t } = useI18n();
  let emits = defineEmits(['close']);
  const props = withDefaults(
    defineProps<{
      editId: string;
    }>(),
    {
      editId: '',
    },
  );
  const steps = [
    {
      title: t('基本配置'),
      content: t('基本配置'),
    },
    {
      title: t('桌面设计'),
      content: t('桌面设计'),
    },
  ];
  const basic = ref();
  const design = ref();
  const previewRef = ref();
  const current = ref<number>(0);
  const preview: {
    list: Array<DesktopInfoItem>;
    show: boolean;
  } = reactive({
    list: [],
    renderKey: 0,
    show: false,
  });
  const spinning = ref<boolean>(false);
  const data: {
    show: boolean;
    basicData: DesktopBasicData;
    jsonContent: string;
    list: Array<DesktopInfoItem>;
    background: BackgroundSetting;
  } = reactive({
    show: false,
    basicData: {
      code: '', //编码
      name: '', //名称
      icon: '', //图标
      parentId: '', //上级
      sortCode: 0, //排序
      isFirst: 0, //首屏
      isMenu: 0, //菜单
      remark: '', //描述
      backgroundUrl: '', //封面图片
      systemId: '', // 系统主键
    },
    jsonContent: '',
    list: [],
    background: backgroundInfo,
  });

  const title = computed(() => {
    return props.editId ? '编辑桌面设计' : t('新增桌面设计');
  });
  provide('changeDataDisplay', changeDataDisplay);
  onMounted(async () => {
    if (props.editId) {
      let { jsonContent, background, ...otherInfo } = await getDesktopInfo(props.editId);
      data.jsonContent = jsonContent;
      data.basicData = otherInfo;
      data.list = JSON.parse(jsonContent, replaceJsonParseInfinity);
      data.background = background ? JSON.parse(background) : backgroundInfo;
      data.show = true;
    } else {
      data.show = true;
    }
    // 清空数据
    window.localStorage.setItem('TableRecord', '');
  });
  const next = async () => {
    if (current.value == 0) {
      let validate = await basic.value.validateForm();
      if (validate) {
        data.basicData = basic.value.getBasicData();
        current.value++;
      }
    }
  };
  const prev = async () => {
    const { list, background } = await design.value.saveDesignData(false);
    data.list = list;
    data.background = background;
    current.value--;
  };

  const addComponent = (type) => {
    design.value.addComponent(type);
  };
  function handleBgImage() {
    design.value.setBackground();
  }
  function changeDataDisplay() {}
  function onPreview() {
    preview.list = design.value.getDesignData();
    preview.show = true;
  }
  async function onSave(close: boolean) {
    spinning.value = true;
    setTimeout(() => {
      save(close);
    }, 100);
  }
  async function save(close: boolean) {
    try {
      let { list, backgroundUrl, background } = await design.value.saveDesignData();
      data.jsonContent = JSON.stringify(list, replaceJsonStringifyInfinity);
      data.basicData.backgroundUrl = backgroundUrl;
      data.background = background;
    } catch (error) {}

    try {
      let res = false;
      if (data.basicData.id) {
        res = await editDesktop({
          ...data.basicData,
          jsonContent: data.jsonContent,
          background: JSON.stringify(data.background),
        });
      } else {
        res = await addDesktop({
          ...data.basicData,
          jsonContent: data.jsonContent,
          background: JSON.stringify(data.background),
        });
      }
      if (res) {
        if (data.basicData.isFirst) {
          const permissionStore = usePermissionStore();
          await permissionStore.changePermissionCode();
        }
        if (close) {
          message.success(t('保存成功'));
          emits('close');
        } else {
          message.success(t('编辑成功'));
        }
      }
      spinning.value = false;
    } catch (error) {
      spinning.value = false;
    }
  }
</script>

<style lang="less" scoped>
  .header-box {
    height: 70px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    position: relative;

    .header {
      display: flex;
      align-items: center;
      z-index: 999;
    }

    .step {
      position: absolute;
      left: 0;
      right: 0;
      flex: none;
      height: auto;
      margin: 0;
      border-radius: 0;
    }

    [data-theme='dark'] .header-title {
      color: #fff;
    }

    .header-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin-left: 20px;
    }

    .button-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    :deep(.common-button) {
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    :deep(.common-todo-button) {
      background-color: #ff8000;
      border-color: #ff8000;
      color: #fff;
    }

    :deep(.common-todo-button:hover) {
      background-color: #ff8000;
      border-color: #ff8000;
      color: #fff;
    }

    :deep(.common-todo-button:focus) {
      background-color: #ff8000;
      border-color: #ff8000;
      color: #fff;
    }

    :deep(.common-clean-button) {
      background-color: #ff8989;
      border-color: #ff8989;
      color: #fff;
    }

    :deep(.common-clean-button:hover) {
      background-color: #ff8989;
      border-color: #ff8989;
      color: #fff;
    }

    :deep(.common-clean-button:focus) {
      background-color: #ff8989;
      border-color: #ff8989;
      color: #fff;
    }

    :deep(.clean-icon) {
      background-color: @clear-color;
      border-color: @clear-color;
    }

    :deep(.button-box) {
      button {
        margin-left: 10px;
        width: 82px;
      }
    }
  }

  .center-box {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60px;
    margin: 10px 0;
    border-radius: 16px;
    background-color: #fff;
  }
</style>
