<template>
  <Drawer
    :drawer-visible="drawerVisible"
    width="480px"
    :title="title"
    :loading="submitLoading"
    confirm-btn-text="保存"
    :cancel-btn="false"
    @confirm="handleConfirm"
    @close="close"
  >
    <t-form ref="formRef" label-align="top" class="login-form" :rules="rules" :data="formData">
      <t-form-item label="用户姓名" name="userName">
        <t-input maxlength="20" v-model="formData.userName" placeholder="请输入用户姓名"> </t-input>
      </t-form-item>
      <t-form-item label="手机号码" name="mobile">
        <t-input
          v-model="formData.mobile"
          maxlength="11"
          @input="
            (v: any) => {
              formData.mobile = v.target.value.replace(/[^0-9]/g, '')
            }
          "
          placeholder="请输入手机号码"
        >
        </t-input>
      </t-form-item>
      <t-form-item label="用户角色" name="roleIds">
        <t-select v-model="formData.roleIds" multiple filterable clearable>
          <t-option v-for="v in roleList" :key="v.roleId" :label="v.roleName" :value="v.roleId" />
        </t-select>
      </t-form-item>
      <t-form-item label="用户备注" name="remark">
        <t-textarea :maxlength="200" v-model="formData.remark" placeholder="请输入用户备注"> </t-textarea>
      </t-form-item>
    </t-form>
  </Drawer>
</template>

<script setup lang="ts" name="user-edit">
import { FormProps, FormInstanceFunctions, CustomValidator } from 'tdesign-vue-next'
import { isPhoneNumber } from '@/utils'
import { ResRoleList, ReqUser, ResUserList } from '@/api/interface/user-roles/index'
import { getRoleList, postUserAddUpd } from '@/api/modules/user-roles/index'

const drawerVisible = ref(false)
const submitLoading = ref(false)

const formRef = useTemplateRef<FormInstanceFunctions>('formRef')
const formData = reactive<ReqUser>({
  userName: '',
  mobile: '',
  userId: '',
  roleIds: [],
  remark: ''
})

const validateTelePhone: CustomValidator = async val => {
  if (!isPhoneNumber(val)) {
    return {
      result: false,
      message: '请输入正确的手机号码！',
      type: 'error'
    }
  } else {
    return {
      result: true,
      message: '',
      type: 'success'
    }
  }
}

const rules: FormProps['rules'] = {
  userName: [
    {
      required: true,
      message: '请填写用户姓名！',
      trigger: 'blur'
    }
  ],
  mobile: [
    { required: true, message: '请填写用户手机号码！', type: 'error' },
    {
      validator: validateTelePhone
    }
  ],
  roleIds: [
    {
      required: true,
      message: '请选择用户角色！',
      trigger: 'change'
    }
  ]
}

const title = ref('新增用户')
const open = (val: ResUserList | null) => {
  drawerVisible.value = true
  if (val) {
    title.value = '编辑用户'
    for (const key in formData) {
      if (Object.prototype.hasOwnProperty.call(val, key)) {
        ;(formData as any)[key] = val[key]
      }
      const roleIds = val.roles || []
      formData.roleIds = roleIds.map((item: { id: string }) => item.id)
    }
  } else {
    title.value = '新增用户'
  }
  getRoleListData()
}
const close = () => {
  formRef.value?.reset()
  drawerVisible.value = false
}

const roleList = ref<ResRoleList[]>([])
const getRoleListData = () => {
  getRoleList({ status: 2 }).then(res => {
    roleList.value = res.data
  })
}

// 确认
const handleConfirm = () => {
  formRef.value?.validate().then(val => {
    if (val === true) {
      submitLoading.value = true
      postUserAddUpd(formData)
        .then(() => {
          close()
          emit('success')
        })
        .finally(() => {
          submitLoading.value = false
        })
    }
  })
}

const emit = defineEmits<{
  success: []
}>()

// onMounted(() => {
//   getRoleListData()
// })

defineExpose({
  open,
  close
})
</script>
