<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      status-icon
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="国家代码" prop="countryCode">
            <PhoneNumberInput
              @updateValue="updateValue"
              v-model="formData.countryCode"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="账号" prop="username">
            <el-input
              v-model="formData.username"
              placeholder="请输入账号 用于登录"
              :disabled="formType == 'record'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item v-if="formData.id === undefined" label="密码" prop="password">
            <el-input
              v-model="formData.password"
              placeholder="请输入用户密码"
              show-password
              type="password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="虚拟会员" prop="userType">
            <el-select v-model="formData.userType" placeholder="请选择">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.INFRA_YES_NO)"
                :key="dict.value as string"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item v-if="formData.id === undefined" label="上级编号" prop="parentId">
            <el-input
              v-model="formData.parentId"
              placeholder="请输入上级编号 表中的ID"
              type="number"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item v-if="formData.id === undefined" label="支付密码" prop="payPassword">
            <el-input v-model="formData.payPassword" placeholder="请输入支付密码 默认123456" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-divider> 下面的内容是选填的 </el-divider>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="formData.sex" placeholder="请选择">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value as string"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import * as MemberUserApi from '@/api/member/user'
import PhoneNumberInput from '@/components/PhoneNumberInput/src/PhoneNumberInput.vue'

defineOptions({ name: 'SystemUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  nickname: '',
  deptId: '',
  parentId: '',
  mobile: '',
  email: '',
  id: undefined,
  username: '',
  password: '',
  payPassword: '',
  userType: undefined,
  sex: undefined,
  postIds: [],
  remark: '',
  status: CommonStatusEnum.ENABLE,
  roleIds: [],
  avatar: '',
  countryCode: ''
})

// 校验用户名
const checkUserName = async (_rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('账号不能为空'))
  }
  if (formType.value == 'create') {
    const data = await MemberUserApi.getUserByUsername(value)
    if (data) {
      callback(new Error('账号已存在'))
    }
  }
}

// 校验上级编号
const checkParentUser = async (_rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('上级编号不能为空'))
  }
  if (value != 0) {
    const data = await MemberUserApi.getUser(value)
    if (!data) {
      callback(new Error('上级编号不存在'))
    }
  }
}

const formRules = reactive({
  username: [{ required: true, validator: checkUserName, trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  countryCode: [{ required: true, message: '国家代码不能为空', trigger: 'blur' }],
  userType: [{ required: true, message: '是否虚拟会员不能为空', trigger: 'blur' }],
  parentId: [{ required: true, validator: checkParentUser, trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MemberUserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MemberUserApi.UserVO
    if (formType.value === 'create') {
      data.countryCode = data.countryCode.replace('+', '')
      await MemberUserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      let userUpdateVO: MemberUserApi.UserUpdateVO = {
        id: formData.value.id as unknown as number,
        nickname: formData.value.nickname,
        remark: formData.value.remark,
        email: formData.value.email,
        countryCode: formData.value.countryCode.replace('+', ''),
        sex: formData.value.sex as unknown as number,
        avatar: formData.value.avatar,
        status: formData.value.status,
        userType: formData.value.userType
      }
      await MemberUserApi.updateUser(userUpdateVO)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    nickname: '',
    deptId: '',
    parentId: '',
    mobile: '',
    email: '',
    userType: 0,
    id: undefined,
    username: '',
    password: '',
    payPassword: '',
    sex: undefined,
    postIds: [],
    remark: '',
    status: CommonStatusEnum.ENABLE,
    roleIds: [],
    avatar: '',
    countryCode: ''
  }
  formRef.value?.resetFields()
}

const updateValue = (countryCode) => {
  formData.value.countryCode = countryCode
}
</script>
