<script setup lang="ts">
import { fnToStepName, stepState } from '../hooks/useStep';
import useI18n from '@/hooks/useI18n';
import { nextTick, onMounted, reactive, watch } from 'vue';
import useAppStore from '@/store/modules/app';
import { parseUrlPath } from '@/plugins/file-static-url';
import { Modal, message } from 'ant-design-vue/es';
import { transferStaticFile, uploadFile } from '@/api/tool/file';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { sessionGet } from '@/utils/cache-session-utils';
import { FileType } from 'ant-design-vue/es/upload/interface';
import { UploadRequestOption } from 'ant-design-vue/es/vc-upload/interface';
import { changeValue } from '@/api/system/config';
import { bootloaderAccount } from '@/api/system/quick-start/bootloader';
const { t, currentLocale } = useI18n();
const appStore = useAppStore();

type StateType = {
  confirmLoading: boolean;
  /**图片 */
  filePath: string; // 是否上传文件
  type: 'brand' | 'icon';
  icon: string;
  brand: string;
  /**系统名称 */
  title: string;
  titleOld: string;
  /**国际化切换 */
  open: boolean;
  openOld: boolean;
  /**管理员账号密码 */
  username: string;
  password: string;
};

const state: StateType = reactive({
  confirmLoading: false,
  filePath: '',
  type: appStore.logoType,
  icon: getLogoURL('icon'),
  brand: getLogoURL('brand'),
  title: appStore.appName,
  titleOld: appStore.appName,
  open: appStore.i18nOpen,
  openOld: appStore.i18nOpen,
  username: 'admin',
  password: 'Abcd@1234..',
});

// LOGO地址
function getLogoURL(type: 'brand' | 'icon') {
  let url =
    type === 'brand'
      ? parseUrlPath(appStore.filePathBrand)
      : parseUrlPath(appStore.filePathIcon);
  if (url.indexOf('{language}') === -1) {
    return url;
  }
  // 语言参数替换
  const local = currentLocale.value;
  const lang = local.split('_')[0];
  return url.replace('{language}', lang || 'en');
}

/**上传前检查或转换压缩 */
function fnBeforeUpload(file: FileType) {
  if (state.confirmLoading) return false;
  const isJpgOrPng = ['image/jpeg', 'image/png'].includes(file.type);
  if (!isJpgOrPng) {
    message.error(`${t('components.UploadModal.onlyAllow')} jpg、png`, 3);
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error(`${t('components.UploadModal.allowFilter')} 2MB`, 3);
  }
  return isJpgOrPng && isLt2M;
}

/**上传变更 */
function fnUpload(up: UploadRequestOption) {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.quickStart.sysUploadLogo'),
    onOk() {
      // 发送请求
      const hide = message.loading(t('common.loading'), 0);
      state.confirmLoading = true;
      let formData = new FormData();
      formData.append('file', up.file);
      formData.append('subPath', 'default');
      uploadFile(formData).then(res => {
        state.confirmLoading = false;
        hide();
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success(t('views.system.quickStart.sysUploadOk'), 3);
          state.filePath = res.data.fileName;
          // 兼容旧前端可改配置文件
          const baseUrl = import.meta.env.PROD
            ? sessionGet('baseUrl') || import.meta.env.VITE_API_BASE_URL
            : import.meta.env.VITE_API_BASE_URL;
          if (state.type === 'icon') {
            state.icon = `${baseUrl}${res.data.fileName}`;
          }
          if (state.type === 'brand') {
            state.brand = `${baseUrl}${res.data.fileName}`;
          }
        } else {
          message.error(res.msg, 3);
        }
      });
    },
  });
}

/**保存管理员账号信息 */
function fnSaveAcount() {
  // 发送保存
  state.confirmLoading = true;
  bootloaderAccount(state.username, state.password).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      message.success(t('common.operateOk'));
    } else {
      message.warning(res.msg);
    }
    state.confirmLoading = false;
  });
}

/**保存系统信息 */
function fnSaveSystem() {
  const language = currentLocale.value;
  const reqArr = [changeValue({ key: 'sys.logo.type', value: state.type })];
  // 改变LOGO地址
  if (state.filePath) {
    let changeFilePath = appStore.filePathIcon;
    if (state.type === 'brand') {
      changeFilePath = appStore.filePathBrand;
    }
    reqArr.push(
      transferStaticFile({
        language: language,
        uploadPath: state.filePath,
        staticPath: changeFilePath,
      })
    );
  }
  // 改变系统名称
  if (state.title !== state.titleOld) {
    reqArr.push(changeValue({ key: 'sys.title', value: state.title }));
  }
  // 改变语言切换
  if (state.open !== state.openOld) {
    reqArr.push(changeValue({ key: 'sys.i18n.open', value: `${state.open}` }));
    reqArr.push(changeValue({ key: 'sys.i18n.default', value: `${language}` }));
  }

  // 发送保存
  state.confirmLoading = true;
  Promise.all(reqArr).then(resArr => {
    message.success(t('views.system.quickStart.sysSaveOk'));
    state.confirmLoading = false;
  });
}

/**返回上一步 */
function fnStepPrev() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.quickStart.sysPrevTip'),
    onOk() {
      fnToStepName('Start');
    },
  });
}

/**下一步操作 */
function fnStepNext(stepName: 'NeInfoConfig' | 'Done') {
  if (stepName === 'NeInfoConfig') {
    Modal.confirm({
      title: t('common.tipTitle'),
      content: t('views.system.quickStart.sysNextNe'),
      onOk() {
        fnToStepName('NeInfoConfig');
      },
    });
  }
  if (stepName === 'Done') {
    Modal.confirm({
      title: t('common.tipTitle'),
      content: t('views.system.quickStart.sysNextDone'),
      onOk() {
        stepState.setupNE = false;
        fnToStepName('Done');
      },
    });
  }
}

/**检查系统名称是否超出范围进行滚动 */
function fnCheckAppNameOverflow() {
  const container: HTMLDivElement | null = document.querySelector(
    '.header-icon > .app-name'
  );
  if (!container) return;
  const text: HTMLDivElement | null = container.querySelector('.marquee');
  if (!text) return;
  if (text.offsetWidth > container.offsetWidth) {
    text.classList.add('app-name_scrollable');
    text.setAttribute('data-content', text.innerText);
  } else {
    text.classList.remove('app-name_scrollable');
  }
}

watch(
  () => state.title,
  () => nextTick(fnCheckAppNameOverflow)
);

onMounted(() => {
  fnCheckAppNameOverflow();
});
</script>

<template>
  <div class="ne">
    <h2>{{ t('views.system.quickStart.sysTitle') }}</h2>

    <a-form
      :label-col="{ span: 4 }"
      :label-wrap="true"
      :wrapper-col="{ span: 10 }"
      style="flex: 1"
    >
      <a-divider orientation="left">
        {{ t('views.system.quickStart.sysAdmin') }}
      </a-divider>
      <a-form-item :label="t('views.system.user.account')" name="username">
        <a-input v-model:value="state.username" :maxlength="30">
          <template #prefix>
            <UserOutlined />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item :label="t('views.system.user.loginPwd')" name="password">
        <a-input-password v-model:value="state.password" :maxlength="26">
          <template #prefix>
            <LockOutlined />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 4, span: 10 }">
        <a-button
          type="primary"
          :loading="state.confirmLoading"
          @click="fnSaveAcount()"
        >
          {{ t('views.system.quickStart.sysSave') }}
        </a-button>
      </a-form-item>

      <a-divider orientation="left">
        {{ t('views.system.quickStart.sysInfo') }}
      </a-divider>
      <a-form-item
        :label="t('views.system.quickStart.sysLogo')"
        :help="t('views.system.quickStart.sysLogoTip')"
        :wrapper-col="{ span: 18 }"
      >
        <a-space direction="horizontal" :size="18">
          <a-radio-group v-model:value="state.type" button-style="solid">
            <a-radio value="brand">
              {{ t('views.system.setting.sysLogoBrand') }}
            </a-radio>
            <a-radio value="icon">
              {{ t('views.system.setting.sysLogoIcon') }}
            </a-radio>
          </a-radio-group>
          <a-upload
            name="file"
            list-type="picture"
            accept=".jpg,.png"
            :max-count="1"
            :show-upload-list="false"
            :before-upload="fnBeforeUpload"
            :custom-request="fnUpload"
          >
            <a-button type="link" :loading="state.confirmLoading">
              {{ t('views.system.setting.sysLogoUpload') }}
            </a-button>
          </a-upload>
        </a-space>
        <div class="header">
          <div class="header-brand" v-show="state.type === 'brand'">
            <img :width="174" :height="48" :src="state.brand" />
          </div>
          <div class="header-icon" v-show="state.type === 'icon'">
            <img :src="state.icon" />
            <h1 class="app-name" :title="state.title">
              <span class="marquee app-name_scrollable">
                {{ state.title }}
              </span>
            </h1>
          </div>
          <div class="header-menu">
            <IconFont type="icon-pcduan" style="margin-right: 10px"></IconFont>
            {{ t('router.index') }}
          </div>
        </div>
      </a-form-item>
      <a-form-item
        :label="t('views.system.quickStart.sysName')"
        :help="t('views.system.quickStart.sysNameTip')"
      >
        <a-input
          v-model:value="state.title"
          allow-clear
          :maxlength="20"
          :placeholder="t('common.inputPlease')"
        ></a-input>
      </a-form-item>
      <a-form-item
        label="国际化切换"
        help="进入系统后是否显示国际化切换，默认锁定当前语言"
        v-if="false"
      >
        <a-switch
          :checked-children="t('common.switch.open')"
          :un-checked-children="t('common.switch.shut')"
          v-model:checked="state.open"
        ></a-switch>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 4, span: 10 }">
        <a-button
          type="primary"
          :loading="state.confirmLoading"
          @click="fnSaveSystem()"
        >
          {{ t('views.system.quickStart.sysSave') }}
        </a-button>
      </a-form-item>
    </a-form>

    <div class="ne-oper">
      <a-space direction="horizontal" :size="18">
        <a-button @click="fnStepPrev()">
          {{ t('views.system.quickStart.stepPrev') }}
        </a-button>

        <a-button type="primary" @click="fnStepNext('NeInfoConfig')">
          {{ t('views.system.quickStart.stepNext') }}
        </a-button>
        <a-button type="dashed" @click="fnStepNext('Done')">
          {{ t('views.system.quickStart.skip') }}
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<style lang="less" scoped>
.header {
  display: flex;
  align-content: center;
  height: 48px;
  padding-left: 16px;
  background-color: #001529;

  &-brand {
    width: 174px;
    height: 48px;
    margin-right: 12px;
    border: 1px var(--ant-primary-color) solid;
  }
  &-icon {
    display: flex;
    align-content: center;
    min-width: 174px;
    height: 100%;
    align-items: center;
    margin-right: 16px;
    border: 1px var(--ant-primary-color) solid;

    & > img {
      height: 32px;
      width: 32px;
      vertical-align: middle;
      border-style: none;
      border-radius: 6.66px;
    }
    & > .app-name {
      overflow: hidden;
      /* text-overflow: ellipsis; */
      white-space: nowrap;
      width: 148px;
      color: #fff;
      margin: 0 0 0 12px;
      font-weight: 600;
      font-size: 18px;

      > .app-name_scrollable {
        padding-right: 12px;
        display: inline-block;
        animation: scrollable-animation linear 6s infinite both;
        &::after {
          content: attr(data-content);
          position: absolute;
          top: 0;
          right: -100%;
          transition: right 0.3s ease;
        }

        @keyframes scrollable-animation {
          0% {
            transform: translateX(0);
          }

          100% {
            transform: translateX(calc(-100% - 12px));
          }
        }
      }
    }
  }

  &-menu {
    width: 90px;
    line-height: 40px;
    color: #ffffff;
    align-self: center;
    text-align: center;
  }
}

.ne {
  height: 78vh;
  overflow-x: hidden;
  overflow-y: auto;
  display: flex;
  flex-direction: column;

  &-oper {
    padding-top: 24px;
    text-align: end;
  }
}
</style>
