<script setup lang="ts">
import { traduction } from '@/utils/language';
import { computed, onUnmounted, reactive, ref } from 'vue';
import useStore from '@/stores';
import { configLanguage, getLanguage } from '@/services/language-service';
import { IResponse } from '@/model/base-interface';
import { langOptions } from '@/utils/language';
import GlobalStoreService from '@/services/gloabal-store-service';
import Dialog from '@/components/Dialog/Dialog.vue';
import { getStoreData } from '@/utils/composition';

const globService = new GlobalStoreService();
const store = useStore();
const dialogRef = ref();
let resolveFunc: any = null;
let rejectFunc: any = null;
let timeStamp: any = null;

const isSystemLocked = computed(() => {
  return getStoreData('glob', 'systemLocked');
});
const langSupported = computed(() => getStoreData('loct', 'langSupported'));
const supportedLangKey = Object.keys(langSupported.value).filter(item => langSupported.value[item]);

// 表头信息
const columns = ref([
  {
    label: 'TABLE_TITLE_NUM',
    prop: 'num',
  },
  {
    label: 'LANGUAGE_CODE',
    prop: 'locale',
  },
  {
    label: 'LANGUAGE_NAME',
    prop: 'name',
  },
  {
    label: 'LANGUAGE_OPERATION',
    prop: 'opderator',
  },
]);

const dialogConfig = reactive({
  title: traduction('COMMON_CONFIRM'),
  content: traduction('COMMON_ASK_OK'),
});

const data = reactive([
  { locale: 'zh', label: '简体中文', enabled: true, show: false, id: 'switch_zh' },
  { locale: 'en', label: 'English', enabled: true, show: false, id: 'switch_en' },
  { locale: 'ja', label: '日本語', enabled: false, show: true, id: 'switch_ja' },
  { locale: 'fr', label: 'Français', enabled: false, show: true, id: 'switch_fr' },
  { locale: 'ru', label: 'Русский', enabled: false, show: true, id: 'switch_ru' },
].filter(item => supportedLangKey.includes(item.locale)));
let curRow = ref(data[0]);

init();

// 初始化数据
function init(isReset?: boolean) {
  globService.loading(true);
  getLanguage()
    .then((res: IResponse) => {
      const langSet = res.data.LanguageSet;
      if (langSet) {
        langSet.split(',').forEach((item: string) => {
          data.forEach(langItem => {
            if (langItem.locale === item) {
              langItem.enabled = true;
            }
          });
        });
      }

      // 操作完语言后，更新语言列表
      if (isReset) {
        resetLangOptions(langSet);
      }
    })
    .finally(() => {
      globService.loading(false);
    });
}

// 重设语言列表
function resetLangOptions(langSet: string) {
  const options = langOptions;
  const tempArr: any[] = [];
  options.forEach(item => {
    if (langSet.indexOf(item.id) > -1) {
      tempArr.push(item);
    }
  });
  store.state.glob.setGlobState({ type: 'langOptions', value: tempArr });
}

// 记录当前点击的switch所在的行
function recordRow(row: any) {
  curRow.value = row;
}

// 操作switch前，弹出确认信息
function confirmSwitch() {
  dialogRef.value.show();
  return new Promise((resolve, reject) => {
    resolveFunc = resolve;
    rejectFunc = reject;
  });
}

// 开启和关闭语言
function switchLanguage(reason: boolean) {
  dialogRef.value.hide();
  if (isSystemLocked.value) {
    return;
  }
  if (reason) {
    globService.loading(true);
    configLanguage(curRow.value.locale, !curRow.value.enabled)
      .then(
        () => {
          resolveFunc(true);
          store.state.event.setEventState({
            type: 'alertMessage',
            value: { type: 'success', message: traduction('COMMON_SUCCESS') },
          });

          // 若当前语言被关闭，则刷新浏览器重新确定选中语言, 若不是当前语言被关闭，则更新语言列表即可
          const locale = store.state.loct.locale;
          if (locale === curRow.value.locale) {
            timeStamp = setTimeout(() => {
              self.location.reload();
            }, 1000);
          } else {
            init(true);
          }
        },
        () => {
          rejectFunc(new Error());
          store.state.event.setEventState({
            type: 'alertMessage',
            value: { type: 'error', message: traduction('COMMON_FAILED') },
          });
        },
      )
      .finally(() => {
        globService.loading(false);
      });
  }

  onUnmounted(() => {
    if (timeStamp) {
      timeStamp = clearTimeout(timeStamp);
    }
  });
}
</script>
<template>
  <div class="root-container">
    <h3>{{ traduction('LANGUAGE_INFO') }}</h3>
    <el-table v-addId.table="'langTable'" :data="data" resizable border>
      <el-table-column :prop="'num'" :label="$t(columns[0].label)" :resizable="true">
        <template #default="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>

      <el-table-column :prop="'locale'" :label="$t(columns[1].label)" :resizable="true">
        <template #default="scope">
          <span class="locale-code">{{ scope.row.locale }}</span>
        </template>
      </el-table-column>

      <el-table-column :prop="'name'" :label="$t(columns[2].label)" :resizable="true">
        <template #default="scope">
          <span class="locale-name">{{ scope.row.label }}</span>
        </template>
      </el-table-column>

      <el-table-column :prop="'opderator'" :label="$t(columns[3].label)">
        <template #default="scope">
          <el-switch
            v-if="scope.row.show"
            :id="scope.row.id"
            v-model="scope.row.enabled"
            :disabled="isSystemLocked"
            :before-change="confirmSwitch"
            @click="recordRow(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <Dialog ref="dialogRef" :config="dialogConfig" @close="switchLanguage" />
</template>
<style lang="scss" scoped>
.root-container {
  margin-right: 24px;
  padding: 16px;
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  height: 100%;
}
h3 {
  font-size: 16px;
  line-height: 24px;
  margin-bottom: 16px;
}

:deep(.el-table__cell) {
  border-right: none;
}
</style>
