<template>
  <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading"
    :disabled="isDetail" :class="{ 'view': isDetail, 'mobile-card': mobile }">
    <el-row>
      <el-col :span="12">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户名" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入昵称" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号" />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- <el-form-item label="头像" prop="avatar">
        <UploadImg v-model="formData.avatar" :limit="1" :disabled="isDetail" :is-show-tip="false" />
      </el-form-item> -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="所在地" prop="areaId">
          <el-tree-select v-model="formData.areaId" :data="areaList" :props="defaultProps"
            :render-after-expand="true" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="formData.sex">
            <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)" :key="dict.value"
              :label="dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="创建时间">
          <el-input v-model="createTime" disabled="true" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="直推人">
          <el-input v-model="formData.recommenderdId" disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="身价">
          <el-input v-model="formData.currentMemberWorthValue" disabled="true" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="积分">
          <el-input v-model="formData.currentMemberPoints" disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="最后登陆时间">
          <el-input v-model="loginDate" disabled="true" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>


</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/member/user'
import * as AreaApi from '@/api/system/area'
import { defaultProps } from '@/utils/tree'
import { formatDate } from '@/utils/formatTime'
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const mobile = computed(() => appStore.getMobile)
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({
  id: undefined,
  mobile: undefined,
  password: undefined,
  status: undefined,
  nickname: undefined,
  avatar: undefined,
  name: undefined,
  sex: undefined,
  areaId: undefined,
  birthday: undefined,
  mark: undefined,
  tagIds: [],
  groupId: undefined
})
const props = defineProps({
  isDetail: {
    type: Boolean,
    default: false
  },
  obj: {
    default: {}
  },
  openType: {
    default: 'create'
  },
  avatar: {
    type: String,
    default: ''
  }
})
// 监听头像是否发生变化 发生变化传入formData中，提交时一起更新
watch(props,(newVal) =>{
  formData.value.avatar = newVal.avatar
},{immediate:true})
const formRules = reactive({
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const areaList = ref([]) // 地区列表
const createTime = computed(()=>{
  return formatDate(formData.value.createTime)
}) // 创建时间
const loginDate = computed(()=>{
  return formatDate(formData.value.loginDate)
}) // 最后登陆时间
/** 打开弹窗 */
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 UserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  const result = ref(false)
  try {
    const data = formData.value as unknown as UserApi.UserVO
    if (formType.value === 'create') {
      // 说明：目前暂时没有新增操作。如果自己业务需要，可以进行扩展
      // await UserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }
    result.value = true
  } finally {
    formLoading.value = false
  }
  return result.value
}
defineExpose({ submitForm }) // 提供 open 方法，用于打开弹窗
onMounted(() => {
  open(props.openType, props.obj.id)
})
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    mobile: undefined,
    password: undefined,
    status: undefined,
    nickname: undefined,
    avatar: undefined,
    name: undefined,
    sex: undefined,
    areaId: undefined,
    birthday: undefined,
    mark: undefined,
    tagIds: [],
    groupId: undefined
  }
  formRef.value?.resetFields()
}
</script>
<style src="@/styles/PcComponents.css"  lang="scss" scoped></style>
