<template>
  <div class="xl:w-screen-xl m-auto py-4 mt-12 px-4 sm:px-0 sm:mt-2">
    <el-page-header :icon="ArrowLeft" @back="goBack">
      <template #content>
        <span class="text-large font-600"> 用户中心 </span>
      </template>
      <div class="login-layout m-auto mt-10 sm:w-screen-xl w-full">
        <div class="m-auto flex sm:flex-row flex-col sm:px-0">
          <!-- 用户菜单 -->
          <UserMenu :activeIndex="activeIndex" @done="onDone" class="sm:flex hidden"/>
          <div class="flash bg-white rounded-lg w-full">
            <div class="title text-xl text-gray-700 md:px-8 p-4 md:mt-3 font-500">修改密码</div>
            <div class="sm:w-screen-md w-full sm:px-4 sm:py-2">
              <Password :form="form"/>
            </div>
          </div>
        </div>
      </div>
    </el-page-header>
  </div>
</template>
<script setup lang="ts">
import { ArrowLeft,View,Search } from '@element-plus/icons-vue'
import {useConfigInfo, useToken, useWebsite} from "~/composables/configState";
import useFormData from '@/utils/use-form-data';
import type {User} from '@/api/system/user/model';
import {ref} from 'vue'
import {useServerRequest} from "~/composables/useServerRequest";
import type {ApiResult} from "~/api";
import UserMenu from "./components/UserMenu.vue";
import Password from './components/Password.vue';
import type {CaptchaResult} from "~/api/passport/login/model";

// 配置信息
const runtimeConfig = useRuntimeConfig();
const route = useRoute();
const router = useRouter();
const website = useWebsite()
const config = useConfigInfo();
const token = useToken();
const userInfo = ref<User>();
const activeIndex = ref('');

// 验证码 base64 数据
const captcha = ref('');
// 验证码内容, 实际项目去掉
const text = ref('');
// 图形验证码
const imgCode = ref('');
// 发送验证码按钮loading
const codeLoading = ref(false);
// 验证码倒计时时间
const countdownTime = ref(0);
// 验证码倒计时定时器
let countdownTimer: number | null = null;

// 配置信息
const {form, assignFields} = useFormData<User>({
  userId: undefined,
  nickname: '',
  username: '',
  phone: '',
  mobile: '',
  sex: '',
  sexName: '',
  email: '',
  oldPassword: '',
  password: '',
  password2: '',
  code: '',
  smsCode: '',
  comments: '',
  remember: true
});

useHead({
  title: `用户中心 - ${config.value?.siteName}`
});


/* 发送短信验证码 */
const sendCode = async () => {
  if (!form.phone) {
    ElMessage.error('请输入手机号码');
    return;
  }
  imgCode.value = text.value;
  codeLoading.value = true;

  const {data: smsCode} = await useServerRequest<ApiResult<CaptchaResult>>('/sendSmsCaptcha', {
    baseURL: runtimeConfig.public.apiServer, method: "post", body: {
      phone: form.phone
    }
  });
  if (smsCode.value) {
    codeLoading.value = false;
    countdownTime.value = 30;
    // 开始对按钮进行倒计时
    countdownTimer = window.setInterval(() => {
      if (countdownTime.value <= 1) {
        countdownTimer && clearInterval(countdownTimer);
        countdownTimer = null;
      }
      countdownTime.value--;
    }, 1000);
  }
};

const onSubmit = async () => {
  const {data: modify} = await useServerRequest<ApiResult<User>>('/auth/password', {
    baseURL: runtimeConfig.public.apiServer,
    method: 'put',
    body: form
  })
  if (modify.value?.code == 0) {
    ElMessage.success('修改成功')
  }
}

const onDone = (index: string) => {
  activeIndex.value = index;
}

const reload = async () => {
  // 未登录状态(是否强制登录)
  const token = localStorage.getItem('token');
  if (!token || token == '') {
    navigateTo('/passport/login');
    return false;
  }
  const {data: response} = await useServerRequest<ApiResult<User>>('/auth/user', {baseURL: runtimeConfig.public.apiServer})
  if (response.value?.data) {
    userInfo.value = response.value?.data;
    assignFields(response.value?.data);
  }
}

const goBack = () => {
  router.back(); // 返回上一页
}

watch(
    () => route.path,
    (path) => {
      activeIndex.value = path;
      reload();
    },
    {immediate: true}
);
</script>
