<script setup>
import { ElMessage } from 'element-plus'
import { org_add, org_detail, org_edit } from '../api'
const props = defineProps({
  deptId: '',
  deptType: '',
  deptLevel: '',
  currentName: '',
})

const emit = defineEmits(['close'])

const ruleFormRef = ref(null)
const ruleForm = ref({
  bmmc: '',
})
const rules = {
  bmmc: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
  ],
}

if (props.deptType == 2)
  initDetailInfo()

async function initDetailInfo() {
  const res = await org_detail({ uo_id: props.deptId })
  if (res.code == 1) {
    const data = res.data.one_info
    ruleForm.value = {
      bmmc: data.uo_name,
      uo_pid: data.uo_pid,
    }
  }
}

const handleCancel = (type) => {
  emit('close', type)
}

const handleSubmit = async (formEl) => {
  if (!formEl)
    return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      if (props.deptType == 1) {
        const obj = {
          user_org: {
            uo_pid: props.deptId,
            uo_name: ruleForm.value.bmmc,
          },
        }
        await org_add(obj)
      }
      else if (props.deptType == 2) {
        const obj = {
          uo_id: props.deptId,
          user_org: {
            uo_pid: ruleForm.value.uo_pid,
            uo_name: ruleForm.value.bmmc,
          },
        }
        await org_edit(obj)
      }
      ElMessage.success('保存成功！')
      handleCancel(1)
    }
  })
}
</script>

<template>
  <div class="addAndEdit px-50px">
    <el-form ref="ruleFormRef" class="mb-10" label-position="top" :model="ruleForm" :rules="rules">
      <el-form-item v-if="deptLevel > 2 || (deptLevel == 2 && deptType == 1)">
        {{ currentName }}
      </el-form-item>
      <el-form-item label="部门名称" prop="bmmc">
        <el-input v-model="ruleForm.bmmc" />
      </el-form-item>
    </el-form>

    <div class="flex_center space-x-12">
      <el-button size="large" @click="handleCancel(2)">
        取消
      </el-button>
      <el-button size="large" type="primary" @click="handleSubmit(ruleFormRef)">
        确定
      </el-button>
    </div>
  </div>
</template>

<style>
</style>
