<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    @ok="handSubmit"
    :title="t('routes.personalSetting.updateBtn')"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { useI18n } from '/@/hooks/web/useI18n';
  import { encodeStr } from '/@/utils/encodeUtil';
  import { defineComponent, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { updatePasswordApi } from '/@/api/sys/user';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();

  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    setup(props) {
      const { t } = useI18n();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          label: 'id',
          show: false,
        },
        {
          field: 'password',
          component: 'StrengthMeter',
          label: t('routes.personalSetting.password'),
          labelWidth: 120,
          required: true,
          colProps: { span: 18 },
        },
      ];

      const [
        registerForm,
        {
          setFieldsValue,
          validate,
          resetFields,
          // setProps
        },
      ] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        setFieldsValue({
          id: data.id,
        });
      }
      async function handSubmit() {
        const { id, password } = await validate();
        await updatePasswordApi({ id, newPassword: encodeStr(window.btoa(password)) });
        createMessage.success(t('common.optSuccess'));
        resetFields();
        closeModal();
      }
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }

      return {
        handSubmit,
        register,
        t,
        schemas,
        registerForm,
        handleVisibleChange,
        resetFields,
      };
    },
  });
</script>
