<script lang="ts" setup>
import { message } from 'ant-design-vue/es';
import { reactive } from 'vue';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { bootloaderReset } from '@/api/system/quick-start/bootloader';
import useMaskStore from '@/store/modules/mask';
const maskStore = useMaskStore();
const { t } = useI18n();

type StateType = {
  open: boolean;
  count: number;
  timer: any;
};

let state: StateType = reactive({
  open: false,
  count: 10,
  timer: null,
});

/**对话框弹出显示 */
function fnModalVisible() {
  state.open = true;
  // 倒数
  state.timer = setInterval(() => {
    if (state.count < 0) {
      clearInterval(state.timer);
      state.timer = null;
    }
    state.count--;
  }, 1_000);
}

/**对话框提交确认 */
function fnModalOk() {
  // 发送请求
  maskStore.handleMaskType('reset');
  bootloaderReset().then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      fnModalCancel();
      maskStore.handleMaskType('reload');
    } else {
      maskStore.handleMaskType('none');
      message.error(res.msg, 3);
      clearInterval(state.timer);
      state.timer = null;
    }
  });
}

/**对话框取消操作 */
function fnModalCancel() {
  clearInterval(state.timer);
  state.timer = null;
  state.count = 10;
  state.open = false;
}
</script>

<template>
  <a-row>
    <a-col :lg="12" :md="12" :xs="24" style="margin-bottom: 30px">
      <a-button type="dashed" danger @click="fnModalVisible()">
        {{ t('common.reset') }}
      </a-button>
    </a-col>
    <a-modal
      :drag="true"
      :width="416"
      :destroyOnClose="true"
      :mask-closable="false"
      v-model:open="state.open"
      :title="t('common.tipTitle')"
      :ok-text="
        state.count > 0 ? `${t('common.ok')} ${state.count}` : t('common.ok')
      "
      :confirmLoading="state.count > 0"
      @ok="fnModalOk()"
      @cancel="fnModalCancel()"
    >
      <div style="color: #f5222d">
        {{ t('views.system.setting.resetTipContent') }}
      </div>
    </a-modal>

    <a-col :lg="12" :md="12" :xs="24">
      <a-typography>
        <a-typography-paragraph>
          {{ t('views.system.setting.resetInstruction') }}
        </a-typography-paragraph>
      </a-typography>
    </a-col>
  </a-row>
</template>

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