<template>
  <el-form
ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px"
    style="padding: 10px;" :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>
    <!-- 暂时注释20240411 -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="所在店铺" prop="shopId">
          <!-- {{shoplist}} -->
          <div class="el-input el-input--default is-disabled el-input__inner" style="padding: 1px 11px;">
            {{ shoplist[0]?.name }}
          </div>
          <!-- <el-select v-model="formData.shopId" placeholder="请选择">
            <el-option v-for="item in shoplist" :key="item.id" :label="item.name" :value="item.id" />
          </el-select> -->
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="formData.mobile" maxlength="11" placeholder="请输入手机号" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" maxlength="11" placeholder="请输入用户名" />
        </el-form-item>
        
      </el-col>
      <el-col :span="12" v-if="openType != 'create'">
        <el-form-item label="创建时间" prop="createTime">
          <div class="el-input el-input--default is-disabled el-input__inner" style="padding: 1px 11px;">
            {{ formatDate(formData.createTime, 'YYYY-MM-DD HH:mm') }}
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="12"  v-if="openType == 'create'">
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入用户密码" maxlength="50" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="openType != 'create'">
      <el-col :span="12">
        <el-form-item label="创建人" prop="createTime">
          <!-- <el-input v-model="formData.createTime" maxlength="11" placeholder="请输入手机号码" /> -->
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态" prop="status">
          <div class="el-input el-input--default is-disabled el-input__inner" style="padding: 1px 11px;">
            {{ formData.status == 1 ? "停用" : "在用" }}
          </div>
          <!-- <el-input v-model="formData.status" maxlength="50" /> -->
        </el-form-item>
      </el-col>

    </el-row>



    <el-row>
      <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"
              :label="dict.label" :value="dict.value" />
          </el-select>
        </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="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> -->
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import * as UserApi from '@/api/system/user'
import { ShopApi } from '@/api/system/sale/shop'
import { formatDate } from '@/utils/formatTime'

import { FormRules } from 'element-plus'
import { useAppStore } from '@/store/modules/app'
// 从缓存中获取merId
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const merId = wsCache.get('merId');
const appStore = useAppStore()
const mobile = computed(() => appStore.getMobile)
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: '',
  name:'',
  deptId: '',
  mobile: '',
  email: '',
  id: undefined,
  username: '',
  password: '',
  sex: undefined,
  postIds: [],
  remark: '',
  status: CommonStatusEnum.ENABLE,
  roleIds: [],
  categoryId: 2,
  shopId: 0,
  avatar: ''
})
const formRules = reactive<FormRules>({
  username: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
  // shopId: [{ required: true, message: '所在店铺不能为空', trigger: 'blur' }],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    {
      required: true,
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref([] as PostApi.PostVO[]) // 岗位列表
const props = defineProps({
  isDetail: {
    type: Boolean,
    default: false
  },
  obj: {
    default: {}
  },
  openType: {
    default: 'create'
  },
  merchantId: {
    default: 0
  },
  avatar: {
    type: String,
    default: ''
  }
})
watch(props, (newVal) => {
  formData.value.avatar = newVal.avatar
  // console.log(formData.value.avatar)
}, { immediate: true })
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  formType.value = type

  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }

}
const shoplist = ref({})
onMounted(async () => {
  open(props.openType, props.obj.id)
  shoplist.value = await ShopApi.getAllUserByMer(merId)
  formData.value.shopId = shoplist.value[0].id
  
  // 如果是新建的时候 就选中该商户下的默认第一个店铺的id
  
})
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log(formData.value.shopId)
  // 校验表单
  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'))
    }
    dialogVisible.value = false
    result.value = true
    // 发送操作成功的事件
    // emit('success')
  } finally {
    formLoading.value = false
  }
  return result.value
}
defineExpose({ submitForm }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    nickname: '',
    deptId: '',
    mobile: '',
    email: '',
    id: undefined,
    username: '',
    password: '',
    sex: undefined,
    postIds: [],
    remark: '',
    status: CommonStatusEnum.ENABLE,
    roleIds: [],
    categoryId: 2,
    shopId: 0,
    avatar: ''
  }
  formRef.value?.resetFields()
}
</script>
<style src="@/styles/PcComponents.css"  lang="scss" scoped></style>
