<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"
                    label-position="left"
                    label-suffix="："
                    size="large"
                >
                    <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"
                                                clearable
                                                placeholder="请输入"
                                            />
                                        </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
                                                v-model="addEditForm.totalScore"
                                                clearable
                                                placeholder="请输入"
                                                type="number"
                                            />
                                        </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"
                                                :autosize="{ minRows: 4, maxRows: 6 }"
                                                clearable
                                                maxlength="200"
                                                placeholder="请输入"
                                                show-word-limit
                                                type="textarea"
                                            />
                                        </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"
                                                :autosize="{ minRows: 4, maxRows: 6 }"
                                                clearable
                                                maxlength="200"
                                                placeholder="请输入"
                                                show-word-limit
                                                type="textarea"
                                            />
                                        </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
                                                v-model="addEditForm.status"
                                                active-text="启用"
                                                active-value="1"
                                                inactive-text="禁用"
                                                inactive-value="0"
                                                inline-prompt
                                                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 :icon="Plus" type="primary" @click="handleAdd">
                                        新增
                                    </el-button>
                                    <el-button
                                        :disabled="addEditForm.detailsMaps.length <= 1"
                                        :icon="Delete"
                                        type="danger"
                                        @click="handleDelete"
                                    >
                                        删除
                                    </el-button>
                                </div>

                                <!-- 评分项表格 -->
                                <el-table
                                    ref="scoreTableRef"
                                    :data="addEditForm.detailsMaps"
                                    :default-expand-all="true"
                                    :tree-props="{
                                        children: 'children',
                                        hasChildren: 'hasChildren',
                                        expandColumnKey: 'classificationName'
                                    }"
                                    row-key="id"
                                    @selection-change="handleSelectionChange"
                                >
                                    <el-table-column align="center" type="selection" width="55" />
                                    <el-table-column label="序号" width="80">
                                        <template #default="{ $index }">
                                            {{ $index + 1 }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="类别"
                                        prop="classificationName"
                                        width="180"
                                    >
                                        <template #default="{ row }">
                                            <el-input
                                                v-if="row.isParent"
                                                v-model="row.classificationName"
                                                :autosize="{ minRows: 2, maxRows: 4 }"
                                                clearable
                                                placeholder="请输入类别"
                                                type="textarea"
                                            />
                                            <div v-else></div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="评审内容" min-width="200" prop="name">
                                        <template #default="{ row }">
                                            <el-input
                                                v-model="row.name"
                                                :autosize="{ minRows: 2, maxRows: 4 }"
                                                clearable
                                                placeholder="请输入评审内容"
                                                type="textarea"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        align="center"
                                        label="分值"
                                        prop="score"
                                        width="100"
                                    >
                                        <template #default="{ row }">
                                            <el-input-number
                                                v-model="row.score"
                                                controls-position="right"
                                                style="width: 100%"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        align="center"
                                        fixed="right"
                                        label="操作"
                                        width="160"
                                    >
                                        <template #default="{ row }">
                                            <div class="operation-buttons">
                                                <el-link
                                                    v-if="row.isParent"
                                                    type="primary"
                                                    underline="never"
                                                    @click="addChildItem(row)"
                                                >
                                                    添加子项
                                                </el-link>
                                                <el-link
                                                    :disabled="
                                                        addEditForm.detailsMaps.length <= 1 &&
                                                        row.isParent
                                                    "
                                                    type="danger"
                                                    underline="never"
                                                    @click="deleteItem(row)"
                                                >
                                                    删除
                                                </el-link>
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </el-form>
            </div>
        </div>

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

<script lang="ts" setup>
import { Delete, Document, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormRules } from 'element-plus'
import { getOrgUserList } from '@/api/system/user'
import {
    dataAdd,
    dataDetail,
    dataUpdate
} from '@/api/supplierMonitor/ConfigManagement/AccessReviewConfig'
import { ref } from 'vue'

interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

interface ScoreItem {
    id?: string
    classificationName: string
    name: string
    ratingId: string
    score: number
    isParent: boolean
    children?: ScoreItem[]
}

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

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

// 表单数据
const addEditForm = reactive<AddEditForm>({
    name: '',
    totalScore: '',
    desc: '',
    remarks: '',
    status: '1',
    detailsMaps: [
        {
            classificationName: '',
            name: '',
            panelList: [],
            score: 0,
            isParent: true,
            children: []
        }
    ]
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入评价体系名称', trigger: 'blur' }],
    totalScore: [{ required: true, message: '请输入总分', trigger: 'blur' }],
    desc: [{ required: true, message: '请输入评审要求', trigger: 'blur' }],
    status: [{ required: true, message: '请选择启用/禁用', trigger: 'change' }]
})

const getDetail = async (id: string) => {
    // 获取详情逻辑
    detailLoading.value = true
    const { ...rest } = (await dataDetail(id)) as AddEditForm
    Object.assign(addEditForm, {
        ...rest
    })
    addEditForm.detailsMaps = Object.entries(addEditForm.detailsMap).map(([key, items]) => {
        const parent = items[0]
        if (parent.panelList && Array.isArray(parent.panelList)) {
            parent.panelList = parent.panelList.map((panelItem: any) => {
                return typeof panelItem === 'object' && panelItem.ratingId
                    ? panelItem.ratingId
                    : panelItem
            })
        }
        const children = items.slice(1).map((child) => {
            if (child.panelList && Array.isArray(child.panelList)) {
                child.panelList = child.panelList.map((panelItem: any) => {
                    return typeof panelItem === 'object' && panelItem.ratingId
                        ? panelItem.ratingId
                        : panelItem
                })
            }
            return {
                ...child,
                isParent: false
            }
        })

        return {
            ...parent,
            isParent: true,
            children: children
        }
    })
    detailLoading.value = false
}

// 表格相关
const scoreTableRef = ref()
const selectedRows = ref<ScoreItem[]>([])

// 评分人选项
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 scrollTableToBottom = () => {
    nextTick(() => {
        const tableEl = scoreTableRef.value?.$el as HTMLElement | undefined

        if (!tableEl) return

        const rows = tableEl.querySelectorAll('.el-table__row')
        const lastRow = rows[rows.length - 1] as HTMLElement | undefined

        if (lastRow) {
            lastRow.scrollIntoView({ behavior: 'smooth', block: 'center' })
            return
        }

        const bodyWrapper = tableEl.querySelector('.el-table__body-wrapper') as HTMLElement | null

        if (bodyWrapper) {
            bodyWrapper.scrollTo({ top: bodyWrapper.scrollHeight, behavior: 'smooth' })
            return
        }

        document.scrollingElement?.scrollTo({
            top: document.scrollingElement.scrollHeight,
            behavior: 'smooth'
        })
    })
}

const handleAdd = () => {
    const newItem: ScoreItem = {
        classificationName: '',
        name: '',
        panelList: [],
        score: 0,
        isParent: true,
        children: []
    }

    addEditForm.detailsMaps.push(newItem)
    scrollTableToBottom()
}

// 添加子级项
const addChildItem = (parent: ScoreItem) => {
    const newChild: ScoreItem = {
        classificationName: parent.classificationName,
        name: '',
        ratingId: '',
        score: 0,
        isParent: false
    }
    if (!parent.children) {
        parent.children = []
    }
    parent.children.push(newChild)
    scrollTableToBottom()
}

// 删除项（单个删除，带确认）
const deleteItem = (item: ScoreItem) => {
    const message = item.isParent
        ? `确定要删除父级"${item.classificationName}"及其所有子级吗？`
        : '确定要删除此项吗？'

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

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

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

    // 统计要删除的父级和子级数量
    const parentCount = 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.detailsMaps.some((parent: ScoreItem) => {
                if (!parent.children) return false
                return parent.children.indexOf(childItem) !== -1
            })
            if (stillExists) {
                removeItemFromData(childItem)
            }
        }

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

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

// 提交
const resultList = (data) => {
    // 处理 panelList 转换：将数组格式转换成对象数组格式
    const processPanelList = (item: any) => {
        if (item.panelList && Array.isArray(item.panelList)) {
            item.panelList = (item.panelList || [])
                .map((panelItem: any) => {
                    let correspondingObj = reviewerOptions.value.find(
                        (obj: any) => obj.userId === panelItem
                    )
                    if (correspondingObj) {
                        return {
                            ratingId: panelItem,
                            ratingName: correspondingObj.fullname,
                            ratingAccount: correspondingObj.account
                        }
                    }
                    return panelItem
                })
                .filter(Boolean)
        }
    }

    let list = data.reduce((acc, { children, ...parent }) => {
        // 处理父项的 panelList
        processPanelList(parent)

        const key = parent.classificationName
        acc[key] = acc[key] || []
        acc[key].push(parent)

        if (children) {
            // 处理子项的 panelList
            children.forEach((child: any) => {
                processPanelList(child)
            })
            acc[key].push(...children)
        }

        return acc
    }, {})
    return list
}

// 验证评分项表格数据
const validateDetailsMaps = (): { valid: boolean; message: string } => {
    // 如果 detailsMaps 为空或不存在，不需要验证
    if (!addEditForm.detailsMaps || addEditForm.detailsMaps.length === 0) {
        return { valid: true, message: '' }
    }

    // 遍历所有项（包括父级和子级）进行字段验证
    for (const item of addEditForm.detailsMaps) {
        // 验证父级项字段
        if (item.isParent) {
            // 类别（仅父级需要）
            if (!item.classificationName || String(item.classificationName).trim() === '') {
                return {
                    valid: false,
                    message: '当前评分项数据未填完整，请填写之后再点保存'
                }
            }
        }

        // 评审内容（所有项都需要）
        if (!item.name || String(item.name).trim() === '') {
            return {
                valid: false,
                message: '当前评分项数据未填完整，请填写之后再点保存'
            }
        }

        // 分值（所有项都需要，且必须大于0）
        if (item.score === null || item.score === undefined || Number(item.score) <= 0) {
            return {
                valid: false,
                message: '分值必须大于0分'
            }
        }

        // 验证子级项
        if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            for (const child of item.children) {
                // 评审内容
                if (!child.name || String(child.name).trim() === '') {
                    return {
                        valid: false,
                        message: '当前评分项数据未填完整，请填写之后再点保存'
                    }
                }

                // 分值
                if (child.score === null || child.score === undefined || Number(child.score) <= 0) {
                    return {
                        valid: false,
                        message: '分值必须大于0分'
                    }
                }
            }
        }
    }

    // 所有字段验证通过后，计算分值总和
    let totalScoreSum = 0
    for (const item of addEditForm.detailsMaps) {
        // 累加父级项的分值
        totalScoreSum += Number(item.score) || 0

        // 累加子级项的分值
        if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            for (const child of item.children) {
                totalScoreSum += Number(child.score) || 0
            }
        }
    }

    // 比较分值总和与总分
    const totalScore = Number(addEditForm.totalScore) || 0
    if (totalScoreSum !== totalScore) {
        return {
            valid: false,
            message: `评分项分值总和(${totalScoreSum})与总分(${totalScore})不一致，请检查后重试`
        }
    }

    return { valid: true, message: '' }
}

const handleSubmit = () => {
    // 先验证评分项表格
    const detailsMapsValidation = validateDetailsMaps()
    if (!detailsMapsValidation.valid) {
        ElMessage.warning(detailsMapsValidation.message)
        return
    }

    // 再验证表单其他字段
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                let params = {
                    ...addEditForm,
                    detailsMap: resultList(addEditForm.detailsMaps)
                }
                delete params.detailsMaps
                const { state } = addEditForm.id ? await dataUpdate(params) : await dataAdd(params)
                if (state) {
                    ElMessage.success('保存成功')
                    handleCancel()
                }
            } finally {
                btnLoading.value = false
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

onMounted(() => {
    const storedData = localStorage.getItem('user')
    if (storedData) {
        userDetail.value = JSON.parse(storedData)
    }
    getReviewerOptions()
    // 如果是编辑模式，获取详情数据
    if (route.query.id && typeof route.query.id === 'string') {
        getDetail(route.query.id)
    }
})
</script>

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

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