<template>
  <Dialog title="变更人员" v-model="dialogVisible" width="480">
    <el-form :model="formData" ref="formRef" :rules="formRules">
      <el-form-item label="执法人员" prop="userId">
        <el-select v-model="formData.userId" placeholder="请选择用户" filterable clearable>
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.realName"
            :value="item.id"
            popper-class="user-wrapper"
          >
            <el-avatar :src="item.avatar" :size="30" /> <span>{{ item.realName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { EnterpriseInspectionsApi } from '@/api/enterpriseinspections'
import { getSimpleUserZGList } from '@/api/system/user'

/** 企业检查记录表，用于记录与企业相关的环保检查信息。 表单 */
defineOptions({ name: 'EnterpriseInspectionsForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRules = ref({
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }]
})
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const formRef = ref() // 表单的引用
const formData: any = ref({
  userId: undefined,
  inspectionsId: undefined
})
const userList = ref()
const getUserList = async (deptId) => {
  userList.value = await getSimpleUserZGList({ deptId: deptId })
}

/** 打开弹窗 */
const open = async (param) => {
  formData.value.inspectionsId = param.id
  await getUserList(param.deptId)
  dialogVisible.value = true
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    await EnterpriseInspectionsApi.passOn(formData.value)
    message.success(t('更改成功'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>

<style scoped lang="scss"></style>
