<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <el-form-item label="组织名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入组织名称" clearable :maxlength="100" />
                </el-form-item>
                <el-form-item label="组织负责人" prop="master">
                    <el-input v-model="formData.master" placeholder="请输入组织负责人" clearable :maxlength="100" />
                </el-form-item>


                <el-form-item label="组织状态" required prop="status">
                    <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { orgsEdit, orgsAdd, orgsDetail } from '@/api/org/organization'
import Popup from '@/components/popup/index.vue'
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑组织' : '新增组织'
})
const formData = reactive({
    id: "",
    name: '',
    master: '',
    status: 0
})

const formRules = {
    master: [
        {
            required: true,
            message: '请输入组织负责人',
            trigger: ['blur']
        }
    ],
    name: [
        {
            required: true,
            message: '请输入组织名称',
            trigger: ['blur']
        }
    ]
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit' ? await orgsEdit(formData) : await orgsAdd(formData)
    popupRef.value?.close()
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await orgsDetail({
        id: row.id
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
