<script lang="ts" setup>
import { IconChevronLeft } from '@computing/opendesign-icons';
import CustomizeInfo from './CustomizeInfo.vue';
import CustomizeStyle from './CustomizeStyle/CustomizeStyle.vue';
import CustomizeCard from './CustomizeCard.vue';
import CustomizeStep from './CustomizeStep.vue';
import CustomizeGuide from './CustomizeGuide.vue';
import CustomizeService from '@/services/customize/customize.service';
import { onMounted, reactive, ref } from 'vue';
import { Step } from './customize.model';
import CustomizeIcon from './components/CustomizeIcon.vue';
import Dialog from '@/components/Dialog/Dialog.vue';
import CustomAert from '@/components/CustAlert/CustAlert.vue';
import FileUpload from '@/components/FileUpload/FileUpload.vue';
import { DefaultConfig } from './customize.model';
import { setThemeStoreData, showSuccessMessage } from '@/utils/composition';
import { UploadFile } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();
const dialogVisible = ref(false);
const activeStep = ref(Step.step0);
const customizeService = new CustomizeService();
const configJson = reactive({ time: '' });

const uploadDialogRef = ref();
const uploadRef = ref();
const resetRef = ref();
let fileInstance: any = null;
const uploadDialogConfig = reactive({
  modalClass: 'customize-dialog',
  title: '上传定制文件',
  content: '',
  okButton: { id: 'secondConfirm_ok_btn', label: '确认', hide: false },
  cancelButton: { id: 'secondConfirm_cancel_btn', label: '取消', hide: false },
});
const fileUpload = reactive({
  accept: '.json',
  url: '',
  isAutoUpload: false,
  placeholder: '点击添加文件',
  onAddItem: (file: UploadFile, list: UploadFile[], msg?: any, upload?: any): boolean => {
    fileInstance = null;
    const fileName = file.name;
    if (/^\s*$/.test(fileName.split('.')[0])) {
      uploadRef.value.setError('文件名不能为空。');
      uploadDialogRef.value.disable();
      return false;
    }

    const subfix = file.name.split('.').reverse()[0];
    // 文件格式错误
    if (fileUpload.accept.indexOf(subfix) < 0) {
      uploadRef.value.setError('上传文件类型错误。');
      uploadDialogRef.value.disable();
      return false;
    }

    if (file.size && file.size > 1024 * 1024) {
      uploadRef.value.setError('文件超出大小限制。');
      uploadDialogRef.value.disable();
      return false;
    }

    fileInstance = file.raw;
    uploadRef.value.clearError();
    uploadDialogRef.value.enable();
    return true;
  },
});

function startUpload(file: any) {
  // 读取本地json文件模拟上传操作
  const reader = new FileReader();
  reader.addEventListener('load', e => {
    const data = JSON.parse(e?.target?.result as string);
    customizeService.initCustomize(null, data, true);
    setThemeStoreData(data);
    localStorage.setItem('customizeStyle', JSON.stringify(data));
  });
  reader.readAsBinaryString(file);
  showSuccessMessage('操作成功');
}

function closeDialog(result: boolean) {
  if (result) {
    dialogVisible.value = false;
  } else {
    activeStep.value = Step.step0;
  }
}

function openUploadDialog() {
  uploadDialogRef.value.show();
  uploadDialogRef.value.disable();
}

// 恢复默认弹窗
const resetConfig = reactive({
  title: '恢复默认',
  content: '执行该操作定制平台将恢复默认主题设计，当前定制方案将被擦除，请确认是否继续？',
  okButton: { id: 'secondConfirm_ok_btn', label: '确认', hide: false },
  cancelButton: { id: 'secondConfirm_cancel_btn', label: '取消', hide: false },
});

function resetCustomConfig() {
  resetRef.value.show();
}

function closeModal(value: boolean) {
  uploadDialogRef.value.hide();
  if (value && fileInstance !== null) {
    startUpload(fileInstance);
  }
}

function closeResetModal(value: boolean) {
  if (value) {
    customizeService.initCustomize(null, JSON.parse(JSON.stringify(DefaultConfig)), true);
    setThemeStoreData(JSON.parse(JSON.stringify(DefaultConfig)));
    localStorage.removeItem('ptc');
    localStorage.removeItem('ptc2');
    localStorage.removeItem('customizeStyle');
    localStorage.removeItem('customizeConfig');
    configJson.time = '';
    showSuccessMessage('操作成功');
    setTimeout(() => {
      router.push('/navigate/home').then(() => {
        window.location.reload();
      });
    }, 1000);
  }
  resetRef.value.hide();
}

// 保存时，将配置字段数据保存
function mergeConfigJson(data: any) {
  Object.assign(configJson, data);
}

onMounted(() => {
  const customizeStyle = localStorage.getItem('customizeStyle');
  if (customizeStyle) {
    const customJson = JSON.parse(customizeStyle);
    configJson.time = customJson.time;
  }
});
</script>

<template>
  <CustomizeIcon @click="dialogVisible = true" />

  <div v-show="dialogVisible" v-reqKeepAlive.dialog>
    <el-dialog
      v-model="dialogVisible"
      width="1200px"
      :class="'cusomize-dialog'"
      :close-on-click-modal="false"
      :append-to-body="false"
      center
    >
      <template #title>
        <header slot="title">
          <div
            v-if="activeStep !== Step.step0"
            id="backIcon"
            class="dialog-title-back"
            @click="activeStep = Step.step0"
          >
            <el-icon :size="24">
              <IconChevronLeft />
            </el-icon>
            <span>返回</span>
          </div>
          <div id="dailogSubtitle" class="dialog-subtitle"></div>
          <div v-if="activeStep === Step.step0" class="dialog-title">openUBMC WebUI定制工具</div>
        </header>
      </template>
      <section class="customize-container">
        <template v-if="activeStep === Step.step0">
          <div class="cusomize-welcome-container">
            <img class="welcome-icon" src="/image/customize-icon.svg" />
            <ul class="welcome-title-container">
              <li class="welcome-title">
                欢迎来到 openUBMC WebUI定制工具
                <div class="welcome-menu-container">
                  <el-button
                    id="uploadConfig"
                    type="primary"
                    size="small"
                    @click="openUploadDialog"
                  >
                    上传
                  </el-button>
                  <el-button id="resetConfig" size="small" @click="resetCustomConfig">
                    恢复默认
                  </el-button>
                </div>
              </li>
              <li class="welcome-sub-title">
                对openUBMC
                Web全量页面进行品牌差异化定制。0代码定制过程，所见即所得，支持实时预览，快速打造具有竞争力的openUBMC
                Web版本。
                <div class="welcome-sub-menu-container">
                  上次保存时间：
                  <span id="lastSaveTime" class="custom-savetime">
                    {{ configJson.time || '--' }}
                  </span>
                </div>
              </li>
            </ul>
          </div>
          <div class="cusomize-main-container">
            <div class="customize-step cusomize-width-3-5 customize-guide-step cusomize-margin">
              <div class="customize-guide-step-background"></div>
              <img class="customize-guide-number" src="@/assets/assets-bmc/default/step-1.svg" />
              <ul class="customize-guide-content">
                <li class="customize-guide-title">进行定制</li>
                <li class="customize-guide-subtitle">使用对应工具进行全局页面的定制设计</li>
              </ul>
            </div>
            <div class="customize-step cusomize-width-1-5 customize-guide-step cusomize-margin">
              <div class="customize-guide-step-background"></div>
              <img class="customize-guide-number" src="@/assets/assets-bmc/default/step-2.svg" />
              <ul class="customize-guide-content">
                <li class="customize-guide-title">生成方案</li>
                <li class="customize-guide-subtitle">将方案导出为配置文件</li>
              </ul>
            </div>
            <div class="customize-step cusomize-width-1-5 column3 customize-guide-step">
              <div class="customize-guide-step-background"></div>
              <img class="customize-guide-number" src="@/assets/assets-bmc/default/step-3.svg" />
              <ul class="customize-guide-content">
                <li class="customize-guide-title">完成定制</li>
                <li class="customize-guide-subtitle">将方案导出为配置文件</li>
              </ul>
            </div>
            <div
              id="brandInfoTool"
              class="customize-step cusomize-width-1-5 cusomize-margin-1-2 custom-item"
              @click="activeStep = Step.step1"
            >
              <CustomizeStep :step="Step.step1" />
            </div>
            <div
              id="brandStyleTool"
              class="customize-step cusomize-width-1-5 cusomize-margin-1-2 custom-item"
              @click="activeStep = Step.step2"
            >
              <CustomizeStep :step="Step.step2" />
            </div>
            <div
              id="homeCardTool"
              class="customize-step cusomize-width-1-5 cusomize-margin-3-4 custom-item"
              @click="activeStep = Step.step3"
            >
              <CustomizeStep :step="Step.step3" />
            </div>
            <div
              id="fileExportTool"
              class="customize-step cusomize-width-1-5 cusomize-margin-3-4 custom-item"
            >
              <CustomizeStep :step="Step.step4" @click="activeStep = Step.step4" />
            </div>
            <div
              id="customActiveGuide"
              class="customize-step cusomize-width-1-5 column3 custom-disabled-item"
            >
              <CustomizeStep :step="Step.step5" />
            </div>
          </div>
        </template>
        <template v-if="activeStep === Step.step1">
          <teleport to="#dailogSubtitle">品牌信息定制工具</teleport>
          <CustomizeInfo @back="activeStep = Step.step0" @save="mergeConfigJson" />
        </template>
        <template v-if="activeStep === Step.step2">
          <teleport to="#dailogSubtitle">品牌风格定制工具</teleport>
          <CustomizeStyle @back="activeStep = Step.step0" @save="mergeConfigJson" />
        </template>
        <template v-if="activeStep === Step.step3">
          <teleport to="#dailogSubtitle">首页卡片自定义工具</teleport>
          <CustomizeCard @back="activeStep = Step.step0" @save="mergeConfigJson" />
        </template>
        <template v-if="activeStep === Step.step4">
          <teleport to="#dailogSubtitle">定制文件导出工具</teleport>
          <CustomizeTool @close="closeDialog" />
        </template>
        <template v-if="activeStep === Step.step5">
          <teleport to="#dailogSubtitle">定制生效指南</teleport>
          <CustomizeGuide />
        </template>
      </section>
    </el-dialog>
  </div>

  <!-- 上传 -->
  <Dialog ref="uploadDialogRef" :config="uploadDialogConfig" @close="closeModal">
    <template #other>
      <CustomAert :content="'配置文件格式支持.json。'" />
      <div class="custom-upload-label">
        <dl class="tab-config">
          <dt>配置文件</dt>
          <dd><FileUpload ref="uploadRef" :data="fileUpload" /></dd>
        </dl>
      </div>
    </template>
  </Dialog>

  <!-- 恢复默认 -->
  <Dialog ref="resetRef" :config="resetConfig" @close="closeResetModal"></Dialog>
</template>

<style lang="scss">
.cusomize-dialog {
  min-height: 734px;
  .el-dialog__body {
    padding: 0;
    min-height: 678px;
    display: block;
    margin-right: 0;
  }
}
</style>

<style lang="scss" scoped>
.icon-style {
  color: var(--o-text-color-tertiary);
  &:hover {
    color: var(--o-color-primary-secondary);
  }
}
.dialog-subtitle {
  vertical-align: super;
  text-align: center;
  float: left;
  width: 100%;
  left: 0;
  position: absolute;
  font-size: 16px;
  font-weight: 900;
  color: var(--o-text-color-primary);
  line-height: 24px;
  z-index: -1;
}

.dialog-title-back {
  float: left;
  cursor: pointer;
  .el-icon {
    vertical-align: middle;
    color: var(--o-text-color-tertiary);
    margin-right: 4px;
  }
  span {
    vertical-align: middle;
    font-size: 14px;
    color: var(--o-text-color-secondary);
  }
  .dialog-split {
    border-left: 1px solid var(--o-border-color-light);
    display: inline-block;
    height: 24px;
    margin: 0 10px;
    font-size: 16px;
    color: var(--o-text-color-primary);
    line-height: 24px;
  }
}
.dialog-title {
  display: inline-block;
  font-size: 16px;
  color: var(--o-text-color-primary);
  line-height: 24px;
  font-weight: bold;
}
.customize-container {
  height: 678px;
  max-height: 678px;
  overflow: hidden;
  padding: 24px;

  .cusomize-welcome-container {
    margin-bottom: 24px;
    padding-top: 8px;
    vertical-align: top;
    .welcome-icon {
      width: 46px;
      height: 46px;
      background: url('/image/customize-icon.svg') no-repeat center;
      background-size: cover;
      display: inline-block;
    }
    .welcome-title-container {
      margin-left: 16px;
      display: inline-block;
      width: calc(100% - 62px);
      .welcome-title {
        font-size: 18px;
        color: var(--o-text-color-primary);
        letter-spacing: 0;
        line-height: 24px;
        margin-bottom: 8px;
        .welcome-menu-container {
          float: right;
        }
      }
      .welcome-sub-title {
        font-size: 12px;
        color: var(--o-text-color-secondary);
        letter-spacing: 0;
        line-height: 16px;
        .welcome-sub-menu-container {
          float: right;
          .custom-savetime {
            display: inline-block;
            min-width: 118px;
          }
        }
      }
    }
  }

  .cusomize-main-container {
    padding: 24px;
    overflow: hidden;
    background-color: rgba(244, 246, 250, 0.5);
    border-radius: var(--o-border-radius);

    .cusomize-margin {
      margin-right: 32px;
    }
    .cusomize-margin-1-2 {
      margin-right: 24px;
    }
    .cusomize-margin-3-4 {
      margin-right: 32px;
    }
    .cusomize-width-3-5 {
      width: 642px;
    }

    .cusomize-width-1-5 {
      width: 198px;
      &.column3 {
        width: 200px;
      }
    }
    .customize-step {
      float: left;
      height: 388px;
      &.custom-item {
        border: 1px solid var(--o-bg-color-base);
        background-color: var(--o-bg-color-base);
        transition: all 0.2s;
        cursor: pointer;
        margin-top: 24px;
        border-radius: var(--o-border-radius);
        &:hover {
          border: 1px solid var(--o-color-primary);
          border-radius: 4px;
          margin-top: 16px;
          box-shadow: var(--o-box-shadow-tip);
        }
      }

      &.custom-disabled-item {
        border: 1px solid var(--o-bg-color-base);
        background-color: var(--o-bg-color-base);
        transition: all 0.2s;
        cursor: not-allowed;
        margin-top: 24px;
        border-radius: var(--o-border-radius);
      }
    }

    .customize-guide-step-background {
      height: 90px;
      width: 100%;
      z-index: 1;
      position: relative;
      float: left;
      opacity: 0.25;
      background-color: var(--o-border-color-light);
    }

    .customize-guide-step {
      height: 90px;
      position: relative;
      border-top: 2px solid #0077ff;
      .customize-guide-number {
        float: left;
        position: absolute;
        left: 0;
        z-index: -1;
        margin-top: 12px;
        margin-left: 16px;
      }

      .customize-guide-content {
        left: 0;
        float: left;
        position: absolute;
        .customize-guide-title {
          width: 100%;
          font-size: 16px;
          color: var(--o-text-color-primary);
          text-align: center;
          line-height: 24px;
          font-weight: 600;
          float: left;
          margin-top: 32px;
          margin-left: 16px;
          text-align: left;
        }
        .customize-guide-subtitle {
          float: left;
          font-size: 12px;
          color: var(--o-text-color-tertiary);
          letter-spacing: 0;
          line-height: 16px;
          margin-left: 16px;
          margin-top: 2px;
        }
      }
    }
  }
}
.tab-config {
  display: flex;
  align-items: center;
  width: 100%;
  dt {
    flex-shrink: 0;
    padding-right: 24px;
  }
  dd {
    flex: 1;
  }
}
.custom-upload-label {
  margin-top: 16px;
  .el-form-item {
    margin-bottom: 0;
  }
}
:deep(.customize-dialog) {
  .el-icon {
    margin-right: 0 !important;
    vertical-align: top;
  }
  .dialog-content {
    display: block;
  }
}
:deep(.el-button.el-button--small) {
  min-width: 64px;
}

:deep(.file-upload) {
  .error-text {
    position: absolute;
  }
}
</style>
