<!-- 添加 / 编辑 -->
<script name="AddGroupDialog" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IGroupInfo } from './group-info'
import { addGroup, updateGroup } from '@/api/basic/group'

const emit = defineEmits(['recordSaved'])

// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')

const title = ref('')

const infoFormRef = ref()

const groupInfo = ref<IGroupInfo>({
  id: '',
  groupName: '',
  deptid: '',
  deptName: '',
  descn: '',
  createUserId: '',
  createTime: '',
})

const groupInfoRules = ref({
  groupName: [{ required: true, message: '分组名称不能为空', trigger: 'blur' }],
  deptid: [{ required: true, message: '所属组织不能为空，请选择', trigger: ['blur', 'change'] }],
  descn: [{ required: true, message: '分组描述不能为空', trigger: 'blur' }],
}) // 表单验证规则

const showDialog = ref<boolean>(false)

// 逻辑
const resetForm = () => {
  sessionStorage.removeItem('groupInfo') // 返回列表时 将缓存中的数据删除

  groupInfo.value = {
    id: '',
    groupName: '',
    deptid: '',
    deptName: '',
    descn: '',
    createUserId: '',
    createTime: '',
  }

  infoFormRef.value.clearValidate()
  showDialog.value = false
}

// 添加
const saveInfo = () => {
  // 将创建时间改为提交的时间
  groupInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
  addGroup(groupInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')

      resetForm()
      emit('recordSaved')
      btnLoading.value = false
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
      btnLoading.value = false
    }
  })
}
// 编辑
const updateInfoById = () => {
  updateGroup(groupInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')

      resetForm()
      emit('recordSaved')
      btnLoading.value = false
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
      btnLoading.value = false
    }
  })
}

// 保存
const btnLoading = ref(false)
const saveForm = async () => {
  if (!infoFormRef) { return }

  await infoFormRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        btnLoading.value = true
        if (type.value === 'create') {
          saveInfo()
        }
        else if (type.value === 'update') {
          updateInfoById()
        }
      })
    }
  })
}

const initDialog = (params: any) => {
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

  switch (params.type) {
    case 'create':
      title.value = '新增分组'

      break
    case 'update':
      title.value = '编辑分组'
      groupInfo.value = JSON.parse(sessionStorage.getItem('groupInfo')!)

      break
    default:
      title.value = ''
      break
  }

  nextTick(() => {
    infoFormRef.value.clearValidate()
  })
  showDialog.value = true
}

defineExpose({
  initDialog,
})
</script>

<template>
  <el-dialog v-model="showDialog" :title="title" :append-to-body="true" :close-on-click-modal="false"
    @closed="resetForm" width="450px">
    <el-form ref="infoFormRef" :model="groupInfo" :rules="groupInfoRules" label-position="right" label-width="110px"
      border stripe>
      <el-row v-if="type === 'update'" :gutter="24">
        <el-col :span="22">
          <el-form-item label="分组编号">
            <el-input v-model="groupInfo.groupNo" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="分组名称" prop="groupName">
            <el-input v-model="groupInfo.groupName" placeholder="请输入分组名称" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="所属组织" prop="deptid">
            <dept-select v-model="groupInfo.deptid" placeholder="请选择所属组织" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="分组描述" prop="descn">
            <el-input v-model="groupInfo.descn" placeholder="请输入分组描述" type="textarea" :rows="3" clearable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
         <el-button :loading="btnLoading" :disabled="btnLoading" type="primary" @click="saveForm">
          保存
        </el-button>
        <el-button @click="resetForm">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
