<template>
    <popup
        class="mr-2"
        width="450px"
        ref="popupRef"
        :center="true"
        :async="true"
        :clickModalClose="false"
        @confirm="handleConfirm(groupFormRef)"
        @open="getCommentDetail"
        :title="title"
        @close="handleClose(groupFormRef)"
    >
        <template #trigger>
            <el-button v-if="type === 'add'" type="primary">{{ title }}</el-button>
            <el-link v-else type="primary" :underline="false">
                {{ title }}
            </el-link>
        </template>
        <div style="height: 300px">
            <el-form ref="groupFormRef" :model="groupForm" label-width="80px" :rules="formRules">
                <el-form-item label="组别:" prop="groupName">
                    <el-input v-model="groupForm.groupName" placeholder="请输入" :rows="10" />
                </el-form-item>
                <el-form-item label="备注:" prop="remark">
                    <el-input type="textarea" v-model="groupForm.remark" placeholder="请输入备注" :rows="10" />
                </el-form-item>
            </el-form>
        </div>
    </popup>
</template>

<script lang="ts" setup>
import Popup from '@/components/popup/index.vue'
import { ref } from 'vue'
import feedback from '@/utils/feedback'
import type { ElForm } from 'element-plus'
import { apiDistributorGroupDetail, apiDistributorGroupAdd, apiDistributorGroupEdit } from '@/api/distributor/group'
import { useRequest } from '@/hooks/useFetchData'

const emit = defineEmits(['refresh'])

const props = withDefaults(
    defineProps<{
        id: string | number //组别ID
        title: string
        type: string //按钮类型
    }>(),
    {
        id: '',
        title: '',
        type: 'add'
    }
)

const groupForm = ref({
    groupName: '',
    remark: '',
    id: ''
})
type FormInstance = InstanceType<typeof ElForm>
const groupFormRef = ref()
const formRules = {
    groupName: { required: true, message: '请输入组别', trigger: 'blur' }
}
const popupRef = ref<any>(null)

// 提交数据
const handleConfirm = (formEl: FormInstance | undefined): void => {
    if (!formEl) return
    formEl.validate((valid): boolean | undefined => {
        if (!valid) return false
        const { runFn } = useRequest({
            apiFn: !props.id ? apiDistributorGroupAdd : apiDistributorGroupEdit,
            onSuccess: res => {
                emit('refresh')
                feedback.msgSuccess('操作成功')
                popupRef.value.visible = false
            },
            onError: err => {}
        })
        runFn(groupForm.value)
    })
}
// 组别详情
const getCommentDetail = () => {
    if (props.id) getDetail(props.id)
}
// 获取组别详情
const getDetail = async (id: number | string): Promise<void> => {
    ;(groupForm.value as object) = await apiDistributorGroupDetail({ id })
}

// 弹窗关闭
const handleClose = (formEl: FormInstance | undefined): void => {
    if (!formEl) return
    formEl.resetFields()
}
</script>
