<script setup lang="ts">
import type { VxeFormInstance, VxeFormProps } from 'vxe-pc-ui'

import { useUserStore } from '@vben/stores'

import hud from '#/utils/hud'

import { mj_form_input } from '../mj/mj-table'

defineOptions({ name: 'UpdateAdminKey' })
const props = withDefaults(
  defineProps<{
    modelValue?: boolean
  }>(),
  {
    modelValue: false,
  },
)
const emits = defineEmits(['update:modelValue', 'ok'])
const { userInfo } = storeToRefs(useUserStore())
const show = computed({
  get() {
    return props.modelValue
  },
  async set(newVal) {
    emits('update:modelValue', newVal)
  },
})

const formRef = ref<VxeFormInstance<FormData>>()
const form = {
  rules: {
    adminKey: [
      {
        required: true,
        message: '密码不能为空',
      },
    ],
  },
  titleWidth: 80,
  items: [
    {
      field: 'adminKey',
      title: '密令',
      itemRender: {
        name: mj_form_input,
        props: { clearable: true },
      },
      span: 24,
    },
    {
      span: 24,
      slots: {
        default: 'operation',
      },
    },
  ],
  data: {},
} as VxeFormProps<any>

async function ok() {
  const error = await formRef.value?.validate()
  if (error) return
  userInfo.value.adminKey = form.data?.adminKey
  hud.success('设置成功')
  emits('update:modelValue', false)
}
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title: '设置管理员密令',
      width: '500px',
    }"
  >
    <VxeForm ref="formRef" v-bind="form">
      <template #operation>
        <el-button type="primary" class="sure-btn" @click="ok">确定</el-button>
      </template>
    </VxeForm>
  </mj-modal>
</template>

<style lang="scss" scoped>
.sure-btn {
  width: 100%;
}
</style>
