<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="name">
                                            <el-select
                                                v-model="addEditForm.supplierGradeName"
                                                filterable
                                                @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="name">
                                            <el-select
                                                v-model="addEditForm.materialTypeName"
                                                @change="changeClass"
                                                clearable
                                                filterable
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in matClassification"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </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
                                            />
                                        </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="addEditForm.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 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-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-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-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 { dataSupplierClass } from '@/api/supplierMonitor/BasicManagement/SupplierLevelConfig'
import { dataMaterialClass } 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 supplierTypeScope = ref([])
const matClassification = 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: '',
    materialTypeName:'',
    materialTypeId:'',
    materialTypeCode: '',
    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' }]
})

// 表格相关
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) => {
    const message = item.isParent
        ? `确定要删除父级"${item.name}"及其所有子级吗？`
        : '确定要删除此项吗？'

    ElMessageBox.confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        removeItemFromData(item)
        ElMessage.success('删除成功')
    })
}

// 从数据中移除项（不显示确认）
const removeItemFromData = (item: ScoreItem) => {
    if (item.isParent) {
        // 删除父级项（会自动删除所有子级）
        const index = addEditForm.scoreTableData.indexOf(item)
        if (index !== -1) {
            addEditForm.details.splice(index, 1)
        }
    } else {
        // 删除子级项
        for (const parent of addEditForm.details) {
            if (parent.children) {
                const childIndex = parent.children.indexOf(item)
                if (childIndex !== -1) {
                    parent.children.splice(childIndex, 1)
                    break
                }
            }
        }
    }
}

const changeScopes = (value: any) => {
    const selectedItem = supplierTypeScope.value.find((item: any) => item.value === value)
    if (selectedItem) {
        addEditForm.supplierGradeName = selectedItem.label
        addEditForm.supplierGradeId = selectedItem.supplierGradingConfigurationId
        addEditForm.supplierGradeCode = selectedItem.code
        // 检查是否已选择物资分类
        if (addEditForm.materialTypeName) {
            const materialItem = matClassification.value.find((item: any) => item.value === addEditForm.materialTypeName)
            if (materialItem) {
                addEditForm.name = `${selectedItem.label}${materialItem.label}绩效考核`
            } else {
                addEditForm.name = `${selectedItem.label}绩效考核`
            }
        } else {
            addEditForm.name = `${selectedItem.label}绩效考核`
        }
    }
}
const changeClass = (value: any) => {
    if (value) {
        // 选中了物资分类
        const selectedItem = matClassification.value.find((item: any) => item.value === value)
        addEditForm.materialTypeName = selectedItem.label
        addEditForm.materialTypeId = selectedItem.value
        addEditForm.materialTypeCode = selectedItem.code
        if (selectedItem) {
            addEditForm.name = `${addEditForm.supplierGradeName}${selectedItem.label}绩效考核`
        }
    } else {
        // 清空了物资分类
        addEditForm.name = `${addEditForm.supplierGradeName}绩效考核`
    }
}
// 设置总分值最大值
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 dataMaterialClass(params)
    matClassification.value = rows.map((item: any) => ({
        label: item.name,
        value: item.id,
        code: item.code
    }))
}
// 获取供应商分类
const getSupplierClass = async () => {
    let params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: [
            { group: 'main', operation: 'EQUAL', property: 'status', relation: 'AND', value: '1' }
        ]
    }
    const { total = 0, rows = [] } = await dataSupplierClass(params)
    supplierTypeScope.value = rows.map((item: any) => ({
        label: item.name,
        value: item.id,
        code: item.code,
        supplierGradingConfigurationId: item.id
    }))
}
// 查询评分项考核类别
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) {
        appraisalList.value.forEach((item) => {
            addEditForm.details.push({
                id: `parent-${item.assessmentIndicatorTypeId}`,
                name: item.assessmentIndicatorTypeName,
                assessmentIndicatorTypeCode: item.assessmentIndicatorTypeCode,
                assessmentIndicatorTypeId: item.assessmentIndicatorTypeId,
                assessmentIndicatorTypeName: item.assessmentIndicatorTypeName,
                score: 0,
                weight: 0,
                content: '',
                children: [],
                isParent: true
            })
        })
    }
}
// 提交
const handleSubmit = () => {
    // 提取children和item的值到新数组，删除children并去重
    const newDetails = []
    addEditForm.details.forEach((item) => {
        const { children, ...itemWithoutChildren } = item
        newDetails.push(itemWithoutChildren)
        if (children && children.length > 0) {
            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
                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

        // 清空现有的details
        addEditForm.details = []

        // 重新构建数据结构
        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: '',
                score: 0,
                weight: 0
            }
            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()}`
                })
            }
        })

        addEditForm.details = groupedDetails
    } finally {
        detailLoading.value = false
    }
}
onMounted(async () => {
    const storedData = localStorage.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 getAppraisalList()
    await getSupplierClass()
    await MaterialClass()
    // 如果是编辑模式，获取详情数据
    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>
