<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 :span="2">
                                        <template #label> <span class="required-asterisk">*</span>供应商分类 </template>
                                        <el-form-item prop="supplierCategoryName">
                                            <el-select
                                                v-model="addEditForm.supplierCategoryName"
                                                @change="changeClass"
                                                clearable
                                                filterable
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in matClassification"
                                                    :key="item.id"
                                                    :label="item.name"
                                                    :value="item.id"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            评价名称
                                        </template>
                                        <el-form-item prop="name">
                                            <el-input
                                                v-model="addEditForm.name"
                                                placeholder="根据所选供应商分类自动填充"
                                                clearable
                                            >
                                            <template #prepend>{{ addEditForm.class }}</template>
                                            </el-input>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            总分
                                        </template>
                                        <el-form-item prop="totalScore">
                                            <el-input
                                                @input="handleWeightInput"
                                                v-model="addEditForm.totalScore"
                                                placeholder="请输入"
                                                clearable
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            评审要求
                                        </template>
                                        <el-form-item prop="desc">
                                            <el-input
                                                v-model="addEditForm.desc"
                                                placeholder="请输入"
                                                type="textarea"
                                                :autosize="{ minRows: 4, maxRows: 6 }"
                                                clearable
                                                maxlength="200"
                                                show-word-limit
                                            />
                                        </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
                                                maxlength="200"
                                                show-word-limit
                                            />
                                        </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-item name="score-level-items">
                            <template #title>
                                <div class="section-title">
                                    <el-icon><Document /></el-icon>
                                    <span>绩效评价等级</span>
                                </div>
                            </template>
                            <div class="section-content">
                                <!-- 评分项表格 -->
                                <el-table
                                    ref="scoreTableRef"
                                    :data="addEditForm.intervals"
                                    row-key="id"
                                >
                                    <el-table-column label="序号" width="80" align="center">
                                        <template #default="{ $index }">
                                            {{ $index + 1 }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="level"
                                        label="等级名称"
                                        width="180"
                                        align="center"
                                    >
                                        <template #default="{ row }">
                                            <div>{{ dictionaryEscape('fzdj', row.level) }}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="maxScore"
                                        label="最大值"
                                        min-width="200"
                                        align="center"
                                    >
                                        <template #default="{ row }">
                                            <el-input
                                                v-model="row.maxScore"
                                                placeholder="请输入"
                                                clearable
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="minScore"
                                        label="最小值(含最小值)"
                                        min-width="200"
                                        align="center"
                                    >
                                        <template #default="{ row }">
                                            <el-input
                                                v-model="row.minScore"
                                                placeholder="请输入"
                                                clearable
                                            />
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </el-collapse-item>
                        <el-collapse-item name="score-items">
                            <template #title>
                                <div class="section-title">
                                    <el-icon><Document /></el-icon>
                                    <span>评分项</span>
                                </div>
                            </template>
                            <div class="section-content">
                                <!-- 评分项表格 -->
                                <el-table
                                    ref="scoreTableRef"
                                    :data="details"
                                    row-key="id"
                                    :tree-props="{
                                        children: 'children',
                                        hasChildren: 'hasChildren',
                                        expandColumnKey: 'name'
                                    }"
                                    :default-expand-all="true"
                                    @selection-change="handleSelectionChange"
                                >
                                    <el-table-column label="序号" width="80">
                                        <template #default="{ $index }">
                                            {{ $index + 1 }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="center" prop="name" label="类别" width="180">
                                        <template #default="{ row }">
                                            <div v-if="row.isParent">{{ row.name }}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="content"
                                        label="评审内容"
                                        min-width="200"
                                    >
                                        <template #default="{ row }">
                                            <el-input
                                                v-if="!row.isParent"
                                                v-model="row.content"
                                                placeholder="请输入评审内容"
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 4 }"
                                                clearable
                                            />
                                        </template>
                                    </el-table-column>

                                    <el-table-column
                                        prop="score"
                                        label="分值"
                                        width="100"
                                        align="center"
                                    >
                                        <template #default="{ row }">
                                            <el-input-number
                                                v-if="!row.isParent"
                                                v-model="row.score"
                                                :max="100"
                                                :min="1"
                                                style="width: 100%"
                                                controls-position="right"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="weight"
                                        label="权重"
                                        width="100"
                                        align="center"
                                    >
                                        <template #default="{ row }">
                                            <el-input-number
                                                v-if="!row.isParent"
                                                v-model="row.weight"
                                                :max="100"
                                                style="width: 100%"
                                                controls-position="right"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="操作"
                                        width="120"
                                        fixed="right"
                                        align="center"
                                    >
                                        <template #default="{ row }">
                                            <div class="operation-buttons">
                                                <el-icon
                                                    v-if="row.isParent"
                                                    size="20"
                                                    color="#409EFF"
                                                    style="cursor: pointer"
                                                    @click="addChildItem(row)"
                                                    ><CirclePlusFilled
                                                /></el-icon>
                                                <el-icon
                                                    v-if="!row.isParent"
                                                    size="20"
                                                    color="#F56C6C"
                                                    style="cursor: pointer"
                                                    @click="deleteItem(row)"
                                                    ><RemoveFilled
                                                /></el-icon>
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </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 { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { getOrgUserList } from '@/api/system/user'
import {
    dataAdd,
    dataDetail,
    dataUpdate,
    getAppraisal,
} from '@/api/supplierMonitor/PerformanceManagement/PerformanceConfig'
import { dataTable } from '@/api/supplierMonitor/BasicManagement/SupplierClassificationConfig'
import { add } from 'lodash'
interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

interface ScoreItem {
    id: string
    name: string
    content: string
    ratingName: string
    ratingAccount: string
    ratingId: string
    score: number
    weight: number
    isParent: boolean
    assessmentIndicatorTypeId: string
    assessmentIndicatorTypeCode: string
    assessmentIndicatorTypeName: string
    children?: ScoreItem[]
}

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

// 表单相关
const addEditFormRef = ref()
const detailLoading = ref(false)
const activeCollapse = ref(['basic-info', 'score-items', 'score-level-items'])
const appraisalList = ref<any[]>([])
const btnLoading = ref(false)
const userDetail = ref({})
const matClassification = ref([])
const details = ref([])
// 编辑相关
const isEdit = computed(() => route.name === 'edit')
const editId = computed(() => route.params.id as string)

// 表单数据
const addEditForm = reactive<AddEditForm>({
    name: '',
    totalScore: '',
    desc: '',
    remarks: '',
    status: '1',
    enterpriseCode: '',
    enterpriseId: '',
    enterpriseName: '',
    supplierCategoryName:'',
    supplierCategoryId:'',
    supplierCategoryCode: '',
    supplierGradeCode: '',
    supplierGradeId: '',
    supplierGradeName: '',
    details: [],
    intervals: [
        {
            level: '1',
            maxScore: '100',
            minScore: '95'
        },
        {
            level: '2',
            maxScore: '95',
            minScore: '85'
        },
        {
            level: '3',
            maxScore: '85',
            minScore: '75'
        },
        {
            level: '4',
            maxScore: '75',
            minScore: '60'
        },
        {
            level: '5',
            maxScore: '60',
            minScore: '0'
        }
    ]
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入绩效评价名称', trigger: 'blur' }],
    totalScore: [{ required: true, message: '请输入总分', trigger: 'blur' }],
    desc: [{ required: true, message: '请输入评审要求', trigger: 'blur' }],
    supplierCategoryName: [{ required: true, message: '请选择供应商分类', trigger: 'blur' }]
})

// 表格相关
const selectedRows = ref<ScoreItem[]>([])
const selectedScoreLevelRows = ref<any[]>([])
// 表格选择变化
const handleSelectionChange = (selection: ScoreItem[]) => {
    selectedRows.value = selection
}
// 添加子级项
const addChildItem = (parent: ScoreItem) => {
    const newChild: ScoreItem = {
        id: `${parent.id}-${Date.now()}`,
        name: '',
        content: '',
        ratingName: '',
        ratingAccount: '',
        ratingId: '',
        score: 0,
        weight: 0,
        isParent: false,
        assessmentIndicatorTypeCode: parent.assessmentIndicatorTypeCode,
        assessmentIndicatorTypeId: parent.assessmentIndicatorTypeId,
        assessmentIndicatorTypeName: parent.assessmentIndicatorTypeName
    }

    if (!parent.children) {
        parent.children = []
    }
    parent.children.push(newChild)
    ElMessage.success('新增子级项成功')
}

// 删除子级项
const deleteItem = (item: ScoreItem) => {
    ElMessageBox.confirm('确定要删除此项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        for (const parent of details.value) {
            if (parent.children) {
                const childIndex = parent.children.indexOf(item)
                if (childIndex !== -1) {
                    parent.children.splice(childIndex, 1)
                    ElMessage.success('删除成功')
                    break
                }
            }
        }
    })
}

// 更新考核名称
const updateAssessmentName = () => {
    const materialName = addEditForm.supplierCategoryName || ''
    addEditForm.class = `${materialName}`
    addEditForm.name = `绩效评价`
}



const changeClass = (value: any) => {
    if (value) {
        const selectedItem = matClassification.value.find((item: any) => item.id === value)
        if (selectedItem) {
            addEditForm.supplierCategoryName = selectedItem.name
            addEditForm.supplierCategoryId = selectedItem.id
            addEditForm.supplierCategoryCode = selectedItem.code
        }
    } else {
        addEditForm.supplierCategoryName = ''
        addEditForm.supplierCategoryId = ''
        addEditForm.supplierCategoryCode = ''
    }
    updateAssessmentName()
}
// 设置总分值最大值
const handleWeightInput = (value) => {
    const num = value.replace(/[^\d]/g, '')
    if (num) {
        const intNum = parseInt(num)
        addEditForm.totalScore = intNum > 100 ? 100 : intNum < 1 ? 1 : intNum
    } else {
        addEditForm.totalScore = ''
    }
}
// 取消
const handleCancel = () => {
    router.push({ name: 'PerformanceConfig' })
}
// 获取物资分类
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 dataTable(params)
    matClassification.value = rows
}

// 查询评分项考核类别
const getAppraisalList = async () => {
    let params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: [
            { group: 'main', operation: 'EQUAL', property: 'status', relation: 'AND', value: '1' }
        ]
    }
    const { total = 0, rows = [] } = await getAppraisal(params)
    appraisalList.value = rows
    appraisalList.value.forEach((item: any) => {
        item.assessmentIndicatorTypeCode = item.code
        item.assessmentIndicatorTypeId = item.id
        item.assessmentIndicatorTypeName = item.name
    })

    // 只在新增模式下初始化details
    if (!route.query.id) {
        details.value = []
        appraisalList.value.forEach((item) => {
            details.value.push({
                id: `parent-${item.assessmentIndicatorTypeId}`,
                name: item.assessmentIndicatorTypeName,
                assessmentIndicatorTypeCode: item.assessmentIndicatorTypeCode,
                assessmentIndicatorTypeId: item.assessmentIndicatorTypeId,
                assessmentIndicatorTypeName: item.assessmentIndicatorTypeName,
                content: '',
                children: [],
                isParent: true
            })
        })
    }
}
// 提交
const handleSubmit = () => {
    // 只保存子项的内容
    const newDetails = []
    details.value.forEach((item) => {
        if (item.children && item.children.length > 0) {
            item.children.forEach((child) => {
                const { children: _, ...childWithoutChildren } = child
                newDetails.push(childWithoutChildren)
            })
        }
    })
    addEditForm.details = newDetails
    addEditForm.details.forEach((item) => {
        if (item.id) {
            delete item.id
        }
    })
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                addEditForm.name = addEditForm.class+addEditForm.name
                const value = addEditForm.id
                    ? await dataUpdate({ ...addEditForm })
                    : await dataAdd({ ...addEditForm })
                if (value.state) {
                    ElMessage.success('保存成功')
                    router.push({ name: 'PerformanceConfig' })
                }
            } 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.value)
        addEditForm.intervals = value.value.intervals
        addEditForm.class = value.value.supplierCategoryName

        // 重新构建数据结构
        const groupedDetails = []
        const codeMap = new Map()

        // 先创建所有父级项
        appraisalList.value.forEach((appraisalItem) => {
            const parentItem = {
                id: `parent-${appraisalItem.assessmentIndicatorTypeId}`,
                name: appraisalItem.assessmentIndicatorTypeName,
                assessmentIndicatorTypeCode: appraisalItem.assessmentIndicatorTypeCode,
                assessmentIndicatorTypeId: appraisalItem.assessmentIndicatorTypeId,
                assessmentIndicatorTypeName: appraisalItem.assessmentIndicatorTypeName,
                children: [],
                isParent: true,
                content: '',
            }
            groupedDetails.push(parentItem)
            codeMap.set(appraisalItem.assessmentIndicatorTypeCode, parentItem)
        })

        // 然后将详情数据分配到对应的父级下
        value.value.details.forEach((item: any) => {
            const parent = codeMap.get(item.assessmentIndicatorTypeCode)
            if (parent) {
                parent.children.push({
                    ...item,
                    isParent: false,
                    id: item.id || `child-${Date.now()}-${Math.random()}`
                })
            }
        })

        details.value = groupedDetails
    } finally {
        detailLoading.value = false
    }
}
onMounted(async () => {
    const storedData = sessionStorage.getItem('user')
    if (storedData) {
        userDetail.value = JSON.parse(storedData)
    }
    addEditForm.enterpriseCode = userDetail.value.userDetail.org[0].orgCode
    addEditForm.enterpriseId = userDetail.value.userDetail.org[0].orgId
    addEditForm.enterpriseName = userDetail.value.userDetail.org[0].orgName

    // 先获取评分项类别列表
    await MaterialClass()
    await getAppraisalList()
    
    // 如果是编辑模式，获取详情数据
    if (route.query.id) {
        await getDetail(route.query.id)
    }
})
</script>

<style lang="scss" scoped>
.table-actions {
    margin: 16px 0 16px 16px;
}

// 隐藏树形表格的缩进
:deep(.el-table__indent) {
    display: none !important;
}
</style>
