<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <el-form
                    ref="addEditFormRef"
                    :model="addEditForm"
                    :rules="addEditFormRules"
                    size="large"
                    label-position="left"
                    label-suffix="："
                >
                    <el-collapse v-model="activeCollapse">
                        <el-collapse-item name="basic-info">
                            <template #title>
                                <div class="section-title">
                                    <el-icon><Document /></el-icon>
                                    <span>考核类别设置</span>
                                </div>
                            </template>
                            <div class="section-content">
                                <el-descriptions :column="2" border>
                                    <el-descriptions-item>
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            考核类别名称
                                        </template>
                                        <el-form-item prop="name">
                                            <el-input
                                                v-model="addEditForm.name"
                                                placeholder="请输入"
                                                clearable
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <template #label> 权重 </template>
                                        <el-form-item prop="weight">
                                            <el-input
                                                placeholder="请输入"
                                                clearable
                                                type="number"
                                                v-model.number="addEditForm.weight"
                                                @input="handleWeightInput"
                                                min="1"
                                                max="100"
                                            >
                                                <template #suffix>
                                                    <span>%</span>
                                                </template>
                                            </el-input>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label> 描述 </template>
                                        <el-form-item prop="remarks">
                                            <el-input
                                                v-model="addEditForm.remarks"
                                                placeholder="请输入"
                                                type="textarea"
                                                :autosize="{ minRows: 4, maxRows: 6 }"
                                                clearable
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            启用/禁用
                                        </template>
                                        <el-form-item prop="status">
                                            <el-switch
                                                active-text="启用"
                                                inline-prompt
                                                inactive-text="禁用"
                                                v-model="addEditForm.status"
                                                active-value="1"
                                                inactive-value="0"
                                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </el-form>
            </div>
        </div>

        <!-- 底部按钮 -->
        <div class="footer">
            <el-button type="primary" @click="handleSubmit" :loading="btnLoading">确定</el-button>
            <el-button @click="handleCancel">取消</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { type FormRules } from 'element-plus'
import { onMounted, reactive, ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
    dataAdd,
    dataUpdate,
    dataDetail,
} from '@/api/supplierMonitor/BasicManagement/AssessmentCategory'
interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

const route = useRoute()
const router = useRouter()

// 表单相关
const btnLoading = ref(false)
const addEditFormRef = ref()
const detailLoading = ref(false)
const activeCollapse = ref(['basic-info', 'score-category'])

// 编辑相关
const isEdit = computed(() => route.name === 'edit')
const editId = computed(() => route.params.id as string)

// 表单数据
const addEditForm = reactive<AddEditForm>({
    name: '',
    status: '1',
    remarks: '',
    weight: ''
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    status: [{ required: true, message: '请选择启用/禁用', trigger: 'change' }],
})
// 取消
const handleCancel = () => {
    router.push({ name: 'AssessmentCategory' })
}
const handleWeightInput = (value) => {
    const num = value.replace(/[^\d]/g, '')
    if (num) {
        const intNum = parseInt(num)
        addEditForm.weight = intNum > 100 ? 100 : (intNum < 1 ? 1 : intNum)
    } else {
        addEditForm.weight = ''
    }
}

// 提交
const handleSubmit = () => {
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                const value = addEditForm.id
                    ? await dataUpdate({ ...addEditForm })
                    : await dataAdd({ ...addEditForm })
                if (value.state) {
                    ElMessage.success('保存成功')
                    router.push({ name: 'AssessmentCategory' })
                }
            } finally {
                btnLoading.value = false // 无论成功或失败，都关闭加载状态
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}
// 获取详情数据
const getDetail = async (id: string | number) => {
    try {
        detailLoading.value = true
        const value = await dataDetail(id)
        Object.assign(addEditForm, value)
    } finally {
        detailLoading.value = false // 无论成功或失败，都关闭加载状态
    }
}

onMounted(() => {
    // 如果是编辑模式，获取详情数据
    if (route.query.id) {
        getDetail(route.query.id)
    }
})
</script>

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