<script lang="ts" setup>
import { Modal, message } from 'ant-design-vue/es';
import { onMounted, reactive } from 'vue';
import useAppStore from '@/store/modules/app';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { transferStaticFile, uploadFileChunk } from '@/api/tool/file';
import { FileType } from 'ant-design-vue/es/upload/interface';
import { UploadRequestOption } from 'ant-design-vue/es/vc-upload/interface';
import { useRouter } from 'vue-router';
const appStore = useAppStore();
const router = useRouter();
const { t, currentLocale, optionsLocale } = useI18n();

type StateType = {
  edite: boolean;
  loading: boolean;
  language: string;
  filePath: string;
};

let state: StateType = reactive({
  edite: false,
  loading: false,
  language: '',
  filePath: '',
});

/**上传前检查或转换压缩 */
function fnBeforeUpload(file: FileType) {
  if (state.loading) return false;
  const isType = ['application/pdf'].includes(file.type);
  if (!isType) {
    message.error(t('views.system.setting.uploadFormat', { format: 'pdf' }), 3);
  }
  return isType;
}

/**上传变更 */
function fnUpload(up: UploadRequestOption) {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.setting.sysHelpDocTipContentUpload'),
    onOk() {
      // 发送请求
      const hide = message.loading(t('common.loading'), 0);
      state.loading = true;
      uploadFileChunk(up.file as File, 5, 'default').then(res => {
        state.loading = false;
        hide();
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success(t('views.system.setting.uploadSuccess'), 3);
          state.filePath = res.data.fileName;
        } else {
          message.error(res.msg, 3);
        }
      });
    },
  });
}

/**进入可编辑 */
function fnEdit(v: boolean) {
  state.edite = v;
  if (!v) {
    state.filePath = '';
  }
}

/**提交保存 */
function fnSave() {
  const item = optionsLocale.find(s => s.value === state.language);
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.setting.sysHelpDocTipContent', {
      lang: item?.label,
    }),
    onOk() {
      // 发送请求
      const hide = message.loading(t('common.loading'), 0);
      state.loading = true;
      transferStaticFile({
        language: state.language,
        uploadPath: state.filePath,
        staticPath: appStore.helpDoc,
      }).then(res => {
        state.loading = false;
        hide();
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success(t('views.system.setting.saveSuccess'), 3);
          fnEdit(false);
        } else {
          message.error(res.msg, 3);
        }
      });
    },
  });
}

/**系统使用手册跳转 */
function fnClickHelpDoc(language?: string) {
  const routeData = router.resolve({ name: 'HelpDoc' });
  let href = routeData.href;
  if (language) {
    href = `${routeData.href}?language=${language}`;
  }
  window.open(href, '_blank');
}

onMounted(() => {
  state.language = currentLocale.value;
});
</script>

<template>
  <a-row>
    <a-col :lg="12" :md="12" :xs="24" style="margin-bottom: 30px">
      <a-form layout="vertical">
        <template v-if="state.edite">
          <a-form-item>
            <a-upload
              name="file"
              list-type="text"
              accept=".pdf"
              :max-count="1"
              :show-upload-list="false"
              :before-upload="fnBeforeUpload"
              :custom-request="fnUpload"
            >
              <a-button type="link" :disabled="state.loading">
                {{ t('views.system.setting.uploadFile') }}
              </a-button>
            </a-upload>
            <span
              v-perms:has="['system:setting:i18n']"
              v-show="appStore.i18nOpen"
            >
              <a-select
                v-model:value="state.language"
                style="width: 100px"
                size="small"
              >
                <a-select-option
                  v-for="opt in optionsLocale"
                  :key="opt.value"
                  :value="opt.value"
                >
                  {{ opt.label }}
                </a-select-option>
              </a-select>
            </span>
          </a-form-item>

          <a-form-item>
            <a-button
              type="primary"
              :disabled="state.filePath === ''"
              @click="fnSave"
            >
              {{ t('views.system.setting.saveSubmit') }}
            </a-button>
            <a-button style="margin-left: 10px" @click="fnEdit(false)">
              {{ t('common.cancel') }}
            </a-button>
          </a-form-item>
        </template>

        <template v-else>
          <a-form-item>
            <a-space direction="horizontal" :size="16">
              <a-button type="link" @click="fnClickHelpDoc(state.language)">
                <template #icon>
                  <QuestionCircleOutlined />
                </template>
                {{ t('views.system.setting.sysHelpDocOpen') }}
              </a-button>
              <span
                v-perms:has="['system:setting:i18n']"
                v-show="appStore.i18nOpen"
              >
                <a-select
                  v-model:value="state.language"
                  style="width: 100px"
                  size="small"
                >
                  <a-select-option
                    v-for="opt in optionsLocale"
                    :key="opt.value"
                    :value="opt.value"
                  >
                    {{ opt.label }}
                  </a-select-option>
                </a-select>
              </span>
            </a-space>
          </a-form-item>
          <a-button type="default" @click="fnEdit(true)">
            {{ t('common.editText') }}
          </a-button>
        </template>
      </a-form>
    </a-col>
    <a-col :lg="12" :md="12" :xs="24">
      <a-typography>
        <a-typography-paragraph>
          {{ t('views.system.setting.sysHelpDocInstruction') }}
        </a-typography-paragraph>
      </a-typography>
    </a-col>
  </a-row>
</template>

<style lang="less" scoped></style>
