<script setup lang="ts">
import { onMounted } from 'vue';
import { fetchUserPassWord } from '@/service/api';
import { useAuthStore } from '@/store/modules/auth';
import { useForm } from '@/components/zt/Form/hooks/useForm';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
const appAuthStore = useAuthStore();

const [registerForm, { setFieldsValue }] = useForm({
  schemas: [
    {
      field: 'username',
      component: 'NInput',
      label: '用户名',
      giProps: {
        span: '6 xl:4'
      },
      componentProps: {
        readonly: true
      }
    },
    {
      field: 'mobile',
      component: 'NInput',
      label: '手机号',
      giProps: {
        span: '6 xl:4'
      },
      componentProps: {
        readonly: true
      }
    },
    {
      field: 'email',
      component: 'NInput',
      label: '邮箱',
      giProps: {
        span: '6 xl:4'
      },
      componentProps: {
        readonly: true
      }
    }
  ],
  showActionButtonGroup: false,
  layout: 'horizontal',
  gridProps: {
    cols: 6,
    xGap: 24
  }
});
onMounted(() => {
  setFieldsValue(appAuthStore.userInfo);
});

const [registerModalForm, { openModal, getFieldsValue, closeModal, setSubLoading }] = useModalFrom({
  modalConfig: {
    title: '修改密码',
    width: 800,
    isShowHeaderText: false,
    height: 300
  },
  formConfig: {
    labelWidth: 120,
    schemas: [
      {
        field: 'password',
        label: '旧密码',
        component: 'NInput',
        required: true,
        componentProps: {
          type: 'password',
          showPasswordOn: 'click'
        }
      },
      {
        field: 'newPassword',
        label: '新密码',
        component: 'NInput',
        required: true,
        componentProps: {
          type: 'password',
          showPasswordOn: 'click'
        }
      },
      {
        field: 'confirmPassword',
        label: '确认密码',
        component: 'NInput',
        required: true,
        componentProps: {
          type: 'password',
          showPasswordOn: 'click'
        }
      }
    ]
  }
});
async function handleSubmit() {
  const form = await getFieldsValue();
  const obj = {
    newPassword: form.newPassword,
    password: form.password
  };
  const { error } = await fetchUserPassWord(obj);

  if (!error) {
    closeModal();

    appAuthStore.resetStore();
  } else {
    setSubLoading(false);
  }
}
</script>

<template>
  <LayoutTable>
    <NCard title="个人中心" :bordered="false" size="small" class="card-wrapper">
      <BasicForm @register-form="registerForm"></BasicForm>
      <template #footer>
        <NSpace justify="end">
          <NButton type="primary" @click="openModal">修改密码</NButton>
        </NSpace>
      </template>
    </NCard>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
