<template>
  <div>
    <n-modal
      v-model:show="visiablePassword"
      style="width: 500px"
      preset="dialog"
      :showIcon="false"
      title="修改密码"
    >
      <!-- model={forms} ref={formsRef} label-placement="left" label-width="100" -->
      <n-form
        :model="forms"
        ref="formsRef"
        label-placement="left"
        label-width="auto"
        style="padding-top: 12px"
      >
        <n-form-item label="手机号" path="phone">
          <n-input v-model:value="forms.phone" placeholder="请输入手机号" disabled />
        </n-form-item>
        <n-form-item
          label="新密码"
          path="newPasswordFirst"
          :rule="[
            {
              required: true,
              message: '请选择输入新密码'
            },
            {
              pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
              message: '密码为6-20位数字和字母组合',
              trigger: 'blur'
            }
          ]"
        >
          <n-input
            v-model:value="forms.newPasswordFirst"
            type="password"
            show-password-on="click"
            placeholder="请选择输入新密码"
            autocomplete="off"
          />
        </n-form-item>
        <n-form-item
          label="再次输入"
          path="newPasswordSecond"
          :rule="[
            {
              validator: validatePass2,
              trigger: 'blur',
              required: true
            }
          ]"
        >
          <n-input
            v-model:value="forms.newPasswordSecond"
            type="password"
            show-password-on="click"
            placeholder="请再次输入密码"
            autocomplete="off"
          />
        </n-form-item>
        <n-form-item
          label="验证码"
          path="authCode"
          :rule="[
            {
              required: true,
              message: '请选择输入验证码'
            }
          ]"
        >
          <n-input-group>
            <n-input v-model:value="forms.authCode" placeholder="请选择输入验证码" />
            <n-button type="primary" v-if="!active" @click="onSendCode" :loading="codeLoading">
              获取验证码
            </n-button>
            <n-button type="default" v-else disabled>
              <n-countdown
                :render="renderCountdown"
                :duration="50 * 1000"
                :active="active"
                @finish="() => (active = false)"
              />
            </n-button>
          </n-input-group>
        </n-form-item>
        <n-space justify="end">
          <n-button type="default" @click="visiablePassword = false">取消</n-button>
          <n-button type="primary" :loading="btnLoading" @click="onSubmit">保存</n-button>
        </n-space>
      </n-form>
    </n-modal>
    <n-modal v-model:show="showSmsClass" style="">
      <SmsLogin
        :phone="forms.phone"
        type="PASSWORD"
        @close="() => (showSmsClass = false)"
        @sendCode="() => (active = true)"
      />
    </n-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from 'vue'
import { CountdownProps, useMessage } from 'naive-ui'
import { useUserStore } from '@/store/modules/user'
import { userUpdateInfo, sendSms, updatePassword } from '@/api/system/user'
import { TABS_ROUTES } from '@/store/mutation-types'
import { useRoute, useRouter } from 'vue-router'
import SmsLogin from '../smsLogin'

export default defineComponent({
  emits: ['updateInfo'],
  components: {
    SmsLogin
  },
  setup(props, { emit }) {
    const userStore = useUserStore()
    const message = useMessage()
    const formsRef = ref()
    const router = useRouter()
    const route = useRoute()

    const state = reactive({
      visiablePassword: false,
      btnLoading: false,
      showSmsClass: false,
      codeLoading: false,
      forms: {
        phone: null,
        newPasswordFirst: '',
        newPasswordSecond: '',
        authCode: ''
      } as any,
      active: false
    })

    const renderCountdown: CountdownProps['render'] = ({ hours, minutes, seconds }) => {
      return `${String(seconds).padStart(2, '00')}s后重试`
    }
    const openModal = () => {
      state.visiablePassword = true
      const userInfo: any = userStore.getUserInfo || {}
      state.forms.phone = userInfo.account.phone || null
    }

    const validatePass2 = (rule: any, value: any, callback: Function) => {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== state.forms.newPasswordFirst) {
        callback(new Error('两次输入密码不一致!'))
      } else if (!reg.test(value)) {
        callback(new Error('密码为6-20位数字和字母组合'))
      } else {
        callback()
      }
    }

    const onSendCode = async () => {
      try {
        // state.codeLoading = true
        // await sendSms({
        //   mobile: state.forms.phone,
        //   type: 'PASSWORD',
        //   clientId: 'jmedu-backend'
        // })
        // state.codeLoading = false
        // state.active = true
        // message.success('发送成功')
        state.showSmsClass = true
      } catch (e) {
        state.codeLoading = false
      }
    }

    const onSubmit = async () => {
      if (state.forms.newPasswordFirst !== state.forms.newPasswordSecond) {
        message.error('两次密码必须相同')
        return
      }
      formsRef.value.validate(async (error: any) => {
        if (error) return false
        try {
          state.btnLoading = true
          await updatePassword({
            code: state.forms.authCode,
            password: state.forms.newPasswordFirst
          })

          userStore.logout().then(() => {
            message.success('密码修改成功')
            // 移除标签页
            localStorage.removeItem(TABS_ROUTES)
            router
              .replace({
                name: 'Login',
                query: {
                  redirect: route.fullPath
                }
              })
              .finally(() => location.reload())
          })
        } catch {}
        state.btnLoading = false
      })
    }
    return {
      message,
      ...toRefs(state),
      openModal,
      onSubmit,
      formsRef,
      renderCountdown,
      validatePass2,
      onSendCode
    }
  }
})
</script>
