<template>
  <t-layout class="app-container">
    <t-header class="app-nav">
      <t-head-menu
        theme="light"
        :default-value="menuValue"
        @change="changeHandler"
      >
        <template #logo>
          <img src="../assets/logo.png" height="32" alt="logo" />
        </template>
        <t-menu-item value="homeIndex"> 首页 </t-menu-item>
        <t-menu-item value="runDataIndex"> 运行数据 </t-menu-item>
        <t-menu-item value="logsDataIndex"> 日志数据 </t-menu-item>
        <template #operations>
          <t-space>
            <t-tooltip placement="bottom" content="全屏">
              <t-button
                theme="default"
                shape="square"
                variant="text"
                @click="toggleFullScreen"
              >
                <t-icon name="fullscreen-2" size="24" />
              </t-button>
            </t-tooltip>

            <t-button theme="default" variant="text">
              <template #icon>
                <t-icon
                  class="header-user-avatar"
                  name="user-circle"
                  size="18"
                />
              </template>
              {{ userName }}
            </t-button>
          </t-space>
          <t-button theme="default" variant="text" @click="updatedPassword">
            <template #icon>
              <t-icon class="header-user-avatar" name="edit" />
            </template>
            修改密码
          </t-button>
          <t-button variant="text" @click="handleLogout">
            <template #icon><t-icon name="poweroff" /></template>
            退出登录
          </t-button>
        </template>
      </t-head-menu>
    </t-header>
    <t-content class="app-content">
      <div class="app-main">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <keep-alive>
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </t-content>
    <!-- 修改密码 -->
    <t-dialog
      header="修改密码"
      v-model:visible="visible"
      :cancel-btn="null"
      :confirm-btn="null"
    >
      <t-form
        ref="form"
        :data="formData"
        :rules="rules"
        @reset="onReset"
        @submit="onSubmit"
      >
        <t-form-item label="原密码" name="oldPasswd">
          <t-input
            v-model="formData.oldPasswd"
            :readonly="true"
            type="password"
          ></t-input>
        </t-form-item>

        <t-form-item label="新密码" name="passwd">
          <t-input v-model="formData.passwd" type="password"></t-input>
        </t-form-item>
        <t-form-item label="确认密码" name="surePassword">
          <t-input v-model="formData.surePassword" type="password"></t-input>
        </t-form-item>
        <t-form-item>
          <t-space size="small">
            <t-button theme="primary" type="submit">确定</t-button>
            <t-button theme="default" variant="base" type="reset"
              >取消</t-button
            >
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </t-layout>
</template>
<script lang="ts" setup>
import { ref, computed, reactive, nextTick } from 'vue';
import screenfull from 'screenfull';
import { useUserStore } from '@/store';
import { useRouter, useRoute } from 'vue-router';
import { editPassword } from '@/api/login';
import { MessagePlugin } from 'tdesign-vue-next';
const route = useRoute();
const { push } = useRouter();
const userStore = useUserStore();
const isFullscreen = ref(false);
const menuValue = computed(() => route.name);
const userName = computed(() => userStore.userInfo.nickname || '');
const visible = ref(false);
const form = ref(null);
const passwordValidator = (val) => {
  if (val === userStore.userInfo.passwd) {
    return { result: false, message: '新密码不能和旧密码一致', type: 'error' };
  }
  return true;
};

const rePasswordValidator = (val) => {
  if (val !== formData.passwd) {
    return { result: false, message: '两次密码不一致', type: 'error' };
  }
  return true;
};
const formData = reactive({
  username: '',
  oldPasswd: '',
  passwd: '',
  surePassword: '',
});
const rules = {
  passwd: [
    { required: true, message: '新密码必填' },
    { validator: passwordValidator },
  ],
  surePassword: [
    { required: true, message: '确认密码必填' },
    { validator: rePasswordValidator },
  ],
};
const changeHandler = (active: string) => {
  push({ name: active });
};
/** 全屏切换 */
const toggleFullScreen = () => {
  isFullscreen.value = !isFullscreen.value;
  if (menuValue.value == 'homeIndex') {
    screenfull.toggle(document.querySelector('.home-container'));
  } else {
    screenfull.toggle();
  }
};
/**修改密码 */
const updatedPassword = () => {
  visible.value = true;
  nextTick(() => {
    form.value.clearValidate();
    formData.username = userStore.userInfo.username;
    formData.oldPasswd = userStore.userInfo.passwd;
    formData.passwd = '';
    formData.surePassword = '';
  });
};
const onSubmit = async ({ validateResult, firstError, e }) => {
  e.preventDefault();
  if (validateResult === true) {
    const { username, oldPasswd, passwd } = formData;
    const resp = await editPassword({ username, oldPasswd, passwd });
    MessagePlugin.success(resp.data);
    userStore.userInfo.passwd = passwd;

    setTimeout(() => {
      visible.value = false;
      form.value.reset();
    }, 500);
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
  }
};
/**取消 */
const onReset = () => {
  visible.value = false;
};
/** 退出登录 */
const handleLogout = async () => {
  await userStore.logout();
  push({
    path: '/login',
  });
};
</script>
<style lang="less" scoped>
.app-container {
  width: 100%;
  height: 100vh;
}
.app-nav {
  padding: 0 25px;
  border-bottom: 1px solid #e5e6eb;
}
.app-content {
  padding: 20px 28px;
  box-sizing: border-box;
  .app-main {
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 6px;
    // padding: 15px;
    // box-sizing: border-box;
  }
}
:deep(.t-button--variant-text) {
  padding: 0 10px;
}
.operations-dropdown-container-item {
  width: 100%;
  display: flex;
  align-items: center;

  :deep(.t-dropdown__item-text) {
    display: flex;
    align-items: center;
  }

  .t-icon {
    font-size: var(--td-comp-size-xxxs);
    margin-right: var(--td-comp-margin-s);
  }
}
</style>
