<script lang="tsx" setup>
import { FormSchema, Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { reactive, ref, watch, useTemplateRef } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import { updateAdmin, getCodeKey, postVerify } from '@/api/system/admin'
import Verify from '@/components/verifition/Verify.vue'
const verify = useTemplateRef('verifys')

const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({})
  }
})

const { required, phone } = useValidator()

const formSchema = reactive<FormSchema[]>([
  {
    field: 'phone',
    label: '手机号',
    component: 'Input',
    colProps: {
      span: 24
    }
  },
  {
    field: 'code',
    label: '验证码',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      slots: {
        append: () => <ElButton onClick={() => getCode()}>验证码</ElButton>
      }
    }
  }
])

const rules = reactive({
  phone: [required('请输入手机号'), phone()],
  code: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getElFormExpose, getFormData } = formMethods

watch(
  () => props.userInfo,
  (value) => {
    setValues(value)
  },
  {
    immediate: true,
    deep: true
  }
)
const getCode = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validateField(['phone']).catch((err) => {
    console.log(err)
  })
  if (valid) {
    verify.value?.show()
  }
}
const success = async (codeKey) => {
  const { data } = await getCodeKey()
  const upData = await getFormData()
  await postVerify({
    phone: upData.phone,
    type: 'admin_update',
    key: data.key,
    captchaType: 'clickWord',
    captchaVerification: codeKey.captchaVerification
  })
  ElMessage.success('发送成功')
}
const emit = defineEmits(['success'])
const saveLoading = ref(false)
const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    ElMessageBox.confirm('是否确认修改?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          saveLoading.value = true
          const upData = await getFormData()
          await updateAdmin({
            phone: upData.phone,
            code: upData.code
          })
          emit('success')
          // 这里可以调用修改用户信息接口
          ElMessage.success('修改成功')
        } catch (error) {
          console.log(error)
        } finally {
          saveLoading.value = false
        }
      })
      .catch(() => {})
  }
}
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
  <Verify
    @success="success"
    captchaType="clickWord"
    :imgSize="{ width: '330px', height: '155px' }"
    ref="verifys"
  />
  <BaseButton type="primary" @click="save">保存</BaseButton>
</template>
