<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-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-items">
                            <template #title>
                                <div class="section-title">
                                    <el-icon><Document /></el-icon>
                                    <span>评分项设置</span>
                                </div>
                            </template>
                            <div class="section-content">
                                <!-- 操作按钮区域 -->
                                <!-- <div class="table-actions">
                                    <el-button type="primary" :icon="Plus" @click="handleAdd">
                                        新增
                                    </el-button>
                                    <el-button type="success" :icon="Upload" @click="handleImport">
                                        导入
                                    </el-button>
                                    <el-button
                                        type="warning"
                                        :icon="Download"
                                        @click="handleExportTemplate"
                                    >
                                        导出模版
                                    </el-button>
                                    <el-button type="danger" :icon="Delete" @click="handleDelete">
                                        删除
                                    </el-button>
                                </div> -->

                                <!-- 评分项表格 -->
                                <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 type="selection" align="center" width="55" />
                                    <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="ratingId"
                                        label="默认评审人"
                                        width="150"
                                        align="center"
                                    >
                                        <template #default="{ row }">
                                            <el-select
                                                v-model="row.ratingId"
                                                placeholder="请选择"
                                                clearable
                                                @change="changeRatingName(row)"
                                            >
                                                <el-option
                                                    v-for="item in reviewerOptions"
                                                    :key="item.userId"
                                                    :label="item.fullname"
                                                    :value="item.userId"
                                                />
                                            </el-select>
                                        </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"
                                                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-item name="score-level-items">
                            <template #title>
                                <div class="section-title">
                                    <el-icon><Document /></el-icon>
                                    <span>分值等级设置</span>
                                </div>
                            </template>
                            <div class="section-content">
                                <!-- 操作按钮区域 -->
                                <!-- <div class="table-actions">
                                    <el-button
                                        type="primary"
                                        :icon="Plus"
                                        @click="handleAddScoreLevel"
                                    >
                                        新增
                                    </el-button>
                                    <el-button
                                        type="danger"
                                        :icon="Delete"
                                        @click="handleDeleteScoreLevel"
                                    >
                                        删除
                                    </el-button>
                                </div> -->

                                <!-- 评分项表格 -->
                                <el-table
                                    ref="scoreTableRef"
                                    :data="addEditForm.intervals"
                                    row-key="id"
                                    @selection-change="handleScoreLevelSelectionChange"
                                >
                                    <!-- <el-table-column type="selection" align="center" width="55" /> -->
                                    <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-column
                                        label="操作"
                                        width="120"
                                        fixed="right"
                                        align="center"
                                    >
                                        <template #default="{ row }">
                                            <div class="operation-buttons">
                                                <el-icon
                                                    size="20"
                                                    color="#F56C6C"
                                                    style="cursor: pointer"
                                                    @click="deleteSingleScoreLevelItem(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'
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 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:'',
    details: [],
    intervals: [
        {
            level: '1',
            maxScore: '100',
            minScore: '90'
        },
        {
            level: '2',
            maxScore: '90',
            minScore: '80'
        },
        {
            level: '3',
            maxScore: '80',
            minScore: '70'
        },
        {
            level: '4',
            maxScore: '70',
            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 reviewerOptions = ref([])
// 获取评审人
const getReviewerOptions = async () => {
    const params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: [
            {
                group: 'orgTree',
                operation: 'IN',
                property: 'ORG_ID_',
                relation: 'AND',
                value: userDetail.value.userDetail.org[0].orgId
            }
        ]
    }
    const { total = 0, rows = [] } = await getOrgUserList(params)
    reviewerOptions.value = rows
}
// 选择评审人
const changeRatingName = (row: ScoreItem) => {
    reviewerOptions.value.forEach((item: any) => {
        if (item.userId === row.ratingId) {
            row.ratingName = item.fullname
            row.ratingAccount = item.account
            row.ratingId = item.userId
        }
    })
}
// 表格选择变化
const handleSelectionChange = (selection: ScoreItem[]) => {
    selectedRows.value = selection
}

// 分值等级表格选择变化
const handleScoreLevelSelectionChange = (selection: any[]) => {
    selectedScoreLevelRows.value = selection
}

// 新增评分项
const handleAdd = () => {
    addParentItem()
}

// 添加父级项
const addParentItem = () => {
    const newItem: ScoreItem = {
        id: `parent-${Date.now()}`,
        name: '',
        content: '',
        ratingName: '',
        ratingAccount: '',
        ratingId: '',
        score: 0,
        weight: 0,
        isParent: true,
        children: []
    }

    addEditForm.details.push(newItem)
    ElMessage.success('新增父级项成功')
}

// 添加子级项
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 handleImport = () => {
    ElMessage.info('导入功能待实现')
}

// 导出模版
const handleExportTemplate = () => {
    ElMessage.info('导出模版功能待实现')
}

// 删除选中项
const handleDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的项')
        return
    }

    // 统计要删除的父级和子级数量
    const parentCount = selectedRows.value.filter((item) => item.isParent).length
    const childCount = selectedRows.value.filter((item) => !item.isParent).length

    let message = `确定要删除选中的 ${selectedRows.value.length} 项吗？`
    if (parentCount > 0) {
        message += `\n其中包括 ${parentCount} 个父级项及其所有子级`
    }

    ElMessageBox.confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 先删除父级项（会自动删除其子级）
        const parentItems = selectedRows.value.filter((item) => item.isParent)
        for (const parentItem of parentItems) {
            removeItemFromData(parentItem)
        }

        // 再删除剩余的子级项（排除已经被父级删除的子级）
        const childItems = selectedRows.value.filter((item) => !item.isParent)
        for (const childItem of childItems) {
            // 检查子级是否还存在（可能已经被父级删除）
            const stillExists = addEditForm.details.some((parent: ScoreItem) =>
                parent.children?.some((child: ScoreItem) => child.id === childItem.id)
            )
            if (stillExists) {
                removeItemFromData(childItem)
            }
        }

        // 清空选择
        selectedRows.value = []

        ElMessage.success('删除成功')
    })
}
// 设置总分值最大值
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 handleAddScoreLevel = () => {
    const newItem = {
        id: `score-level-${Date.now()}`,
        level: '',
        levelDescription: ''
    }
    addEditForm.intervals.push(newItem)
    ElMessage.success('新增分值等级项成功')
}

// 批量删除分值等级项
const handleDeleteScoreLevel = () => {
    if (selectedScoreLevelRows.value.length === 0) {
        ElMessage.warning('请选择要删除的分值等级项')
        return
    }

    ElMessageBox.confirm(
        `确定要删除选中的 ${selectedScoreLevelRows.value.length} 个分值等级项吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        // 获取要删除的ID列表
        const idsToDelete = selectedScoreLevelRows.value.map((item) => item.id)

        // 从后往前删除，避免索引变化问题
        for (let i = addEditForm.intervals.length - 1; i >= 0; i--) {
            if (idsToDelete.includes(addEditForm.intervals[i].id)) {
                addEditForm.intervals.splice(i, 1)
            }
        }

        // 清空选择
        selectedScoreLevelRows.value = []

        ElMessage.success('删除成功')
    })
}

// 单个删除分值等级项
const deleteSingleScoreLevelItem = (item: any) => {
    ElMessageBox.confirm('确定要删除此分值等级项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = addEditForm.intervals.findIndex((p: any) => p.id === item.id)
        if (index !== -1) {
            addEditForm.intervals.splice(index, 1)
        }
        ElMessage.success('删除成功')
    })
}

// 取消
const handleCancel = () => {
    router.push({ name: 'PerformanceConfig' })
}
// 查询评分项考核类别
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
        item.children = []
        item.isParent = true
        delete item.id
        delete item.code
    })
    appraisalList.value.forEach((item) => {
        addEditForm.details.push({
            name: item.assessmentIndicatorTypeName,
            performanceEvaluationConfigurationId: item.id,
            assessmentIndicatorTypeCode: item.assessmentIndicatorTypeCode,
            assessmentIndicatorTypeId: item.assessmentIndicatorTypeId,
            assessmentIndicatorTypeName: item.name,
            score: 0,
            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
        const groupedDetails = []
        const codeMap = new Map()
        value.value.details.forEach((item: any) => {
            if (codeMap.has(item.assessmentIndicatorTypeCode)) {
                const parent = codeMap.get(item.assessmentIndicatorTypeCode)
                parent.children.push({ ...item, isParent: false })
            } else {
                const parentItem = { ...item, children: [], isParent: true }
                groupedDetails.push(parentItem)
                codeMap.set(item.assessmentIndicatorTypeCode, parentItem)
            }
        })
        addEditForm.details = groupedDetails
        addEditForm.details.forEach((item) => {
            item.name = item.assessmentIndicatorTypeName
        })
    } finally {
        detailLoading.value = false
    }
}
onMounted(() => {
    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
    getAppraisalList()
    getReviewerOptions()
    // 如果是编辑模式，获取详情数据
    if (route.query.id) {
        getDetail(route.query.id)
    }
})
</script>

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

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