<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>
                                            <span class="required-asterisk">*</span>
                                            主供物资分类
                                        </template>
                                        <el-form-item prop="mainSupplierMaterialCategoryId">
                                            <el-select
                                                v-model="addEditForm.mainSupplierMaterialCategoryId"
                                                @change="changeScopes"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in supplierTypeScope"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label> 可供物资分类 </template>
                                        <el-form-item prop="selectList">
                                            <el-select
                                                v-model="addEditForm.selectList"
                                                multiple
                                                @change="changeList"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in supplierTypeScope"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </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 } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
    dataAdd,
    dataUpdate,
    dataDetail,
    dataMaterialClass
} from '@/api/supplierMonitor/BasicManagement/SupplierClassificationConfig'
interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

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

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

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

// 表单数据
const addEditForm = reactive<AddEditForm>({
    name: '',
    code: '',
    status: '1',
    remarks: '',
    mainSupplierMaterialCategoryCode: '',
    mainSupplierMaterialCategoryId: '',
    mainSupplierMaterialCategoryName: '',
    selectName: '',
    selectList: []
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    status: [{ required: true, message: '请选择启用/禁用', trigger: 'change' }],
    mainSupplierMaterialCategoryId: [
        { required: true, message: '请选择主供物资分类', trigger: 'change' }
    ]
})

// 取消
const handleCancel = () => {
    router.push({ name: 'SupplierClassificationConfig' })
}

// 提交
const handleSubmit = () => {
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                addEditForm.scopes = []
                if (addEditForm.selectList && addEditForm.selectList.length > 0) {
                    addEditForm.selectList.forEach((item: any) => {
                        supplierTypeScope.value.forEach((item2: any) => {
                            if (item2.value === item) {
                                addEditForm.scopes.push({
                                    supplierMaterialCategoryCode: item2.code,
                                    supplierMaterialCategoryId: item2.value
                                })
                            }
                        })
                    })
                }
                btnLoading.value = true
                const value = addEditForm.id
                    ? await dataUpdate({ ...addEditForm })
                    : await dataAdd({ ...addEditForm })
                if (value.state) {
                    ElMessage.success('保存成功')
                    router.push({ name: 'SupplierClassificationConfig' })
                }
            } 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)
        addEditForm.selectList = addEditForm.scopes.map((item: any) => {
            return item.supplierMaterialCategoryId
        })
        addEditForm.remarks = value.remarks
    } finally {
        detailLoading.value = false // 无论成功或失败，都关闭加载状态
    }
}
const MaterialClass = async () => {
    let params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: [
            { group: 'main', operation: 'EQUAL', property: 'status', relation: 'AND', value: '1' }
        ]
    }
    const { total = 0, rows = [] } = await dataMaterialClass(params)
    supplierTypeScope.value = rows.map((item: any) => ({
        label: item.name,
        value: item.id,
        code: item.code
    }))
}

const changeScopes = (val: any) => {
    supplierTypeScope.value.forEach((item: any) => {
        if (item.value === val) {
            addEditForm.mainSupplierMaterialCategoryCode = item.code
            addEditForm.mainSupplierMaterialCategoryName = item.label
        }
    })
    if (addEditForm.mainSupplierMaterialCategoryId) {
        addEditForm.remarks = `类供应商主要供应${addEditForm.mainSupplierMaterialCategoryName}`
    }
    if (addEditForm.mainSupplierMaterialCategoryId && addEditForm.selectName != '') {
        addEditForm.remarks = `类供应商主要供应${addEditForm.mainSupplierMaterialCategoryName},也可以供应${addEditForm.selectName}`
    }
}

const changeList = (val: any) => {
    let arr = []
    addEditForm.selectList = val
    if (addEditForm.selectList && addEditForm.selectList.length > 0) {
        addEditForm.selectList.forEach((item: any) => {
            supplierTypeScope.value.forEach((item2: any) => {
                if (item2.value === item) {
                    arr.push(item2.label)
                }
            })
        })
    }
    supplierTypeScope.value.forEach((item: any) => {
        if (item.value === addEditForm.mainSupplierMaterialCategoryId) {
            addEditForm.mainSupplierMaterialCategoryName = item.label
        }
    })
    addEditForm.selectName = arr.join(',')
    if (addEditForm.mainSupplierMaterialCategoryId && addEditForm.selectName != '') {
        addEditForm.remarks = `类供应商主要供应${addEditForm.mainSupplierMaterialCategoryName},也可以供应${addEditForm.selectName}`
    } else {
        addEditForm.remarks = `类供应商主要供应${addEditForm.mainSupplierMaterialCategoryName}`
    }
}
onMounted(() => {
    // 如果是编辑模式，获取详情数据
    const route = useRoute()
    if (route.query.id) {
        getDetail(route.query.id)
    }
    MaterialClass()
})
</script>

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