<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <div class="main-content">
                    <div class="main-layout">
                        <div class="left-tree">
                            <tree-side
                                ref="treeRef"
                                :customIcon="true"
                                :dataLoading="treeLoading"
                                :default-expand-all="true"
                                :defaultProps="defaultProps"
                                :tabList="['评分项']"
                                :treeData="treeData"
                                :isAll="true"
                                :current="currentClassType"
                                :current-node-key="currentNodeKey"
                                isDeselect
                                @operateEvent="getClass"
                                node-key="performanceEvaluationDetailsId"
                                @node-click="nodeClick"
                            >
                                <template v-slot:treeIcon="{ data }">
                                    <el-icon>
                                        <Folder v-if="data.grade === '1'" />
                                        <Film v-else />
                                    </el-icon>
                                </template>
                            </tree-side>
                        </div>
                        <div class="right-table">
                            <div class="content-area">
                                <el-form
                                    ref="addEditFormRef"
                                    :model="addEditForm"
                                    :rules="addEditFormRules"
                                    size="large"
                                    label-position="left"
                                    label-suffix="："
                                >
                                    <el-collapse v-model="activeCollapse">
                                        <!-- 基本信息 !-->
                                        <el-collapse-item name="basic-info">
                                            <template #title>
                                                <div class="section-title">
                                                    <el-icon><Document /></el-icon>
                                                    <span>基本信息</span>
                                                </div>
                                            </template>
                                            <div class="section-content">
                                                <el-descriptions :column="2" border>
                                                    <el-descriptions-item>
                                                        <template #label>
                                                            <span class="required-asterisk">*</span>
                                                            评价体系名称
                                                        </template>
                                                        <el-form-item
                                                            prop="valuationConfigurationName"
                                                        >
                                                            {{
                                                                addEditForm.valuationConfigurationName
                                                            }}
                                                        </el-form-item>
                                                    </el-descriptions-item>
                                                    <el-descriptions-item>
                                                        <template #label>
                                                            <span class="required-asterisk">*</span>
                                                            评价年度
                                                        </template>
                                                        <el-form-item prop="assessmentYear">
                                                            {{ addEditForm.assessmentYear }}
                                                        </el-form-item>
                                                    </el-descriptions-item>
                                                    <el-descriptions-item>
                                                        <template #label>
                                                            <span class="required-asterisk">*</span>
                                                            评价类型
                                                        </template>
                                                        <el-form-item prop="assessmentType">
                                                            {{
                                                                dictionaryEscape(
                                                                    'khpj-khlx',
                                                                    addEditForm.assessmentType
                                                                )
                                                            }}
                                                        </el-form-item>
                                                    </el-descriptions-item>
                                                    <el-descriptions-item>
                                                        <template #label>
                                                            <span class="required-asterisk">*</span>
                                                            评价周期
                                                        </template>
                                                        <el-form-item prop="assessmentYear">
                                                            <div
                                                                v-if="addEditForm.assessmentQuater"
                                                            >
                                                                <span
                                                                    >{{
                                                                        addEditForm.assessmentYear
                                                                    }}年</span
                                                                >
                                                                <span
                                                                    >{{
                                                                        addEditForm.assessmentQuater
                                                                    }}季度</span
                                                                >
                                                            </div>
                                                            <div
                                                                v-else-if="
                                                                    addEditForm.assessmentMonth
                                                                "
                                                            >
                                                                <span
                                                                    >{{
                                                                        addEditForm.assessmentYear
                                                                    }}年</span
                                                                >
                                                                <span
                                                                    >{{
                                                                        addEditForm.assessmentMonth
                                                                    }}月</span
                                                                >
                                                            </div>
                                                            <div v-else>
                                                                {{ addEditForm.assessmentYear }}年
                                                            </div>
                                                        </el-form-item>
                                                    </el-descriptions-item>
                                                    <el-descriptions-item :span="2">
                                                        <template #label> 评审要求 </template>
                                                        <el-form-item prop="totalScore">
                                                            {{ addEditForm.desc }}
                                                        </el-form-item>
                                                    </el-descriptions-item>
                                                </el-descriptions>
                                            </div>
                                        </el-collapse-item>
                                        <div class="score-section">
                                            <div class="section-title">
                                                <span>评分</span>
                                                <span v-if="form.score !== undefined">{{
                                                    `（满分${form.score}）`
                                                }}</span>
                                            </div>
                                            <div class="section-content">
                                                <div class="score-actions">
                                                    <el-button
                                                        type="primary"
                                                        @click="openBatchScoreDialog"
                                                        >批量评分</el-button
                                                    >
                                                    <el-button type="danger" @click="clearAllScores"
                                                        >清除评分</el-button
                                                    >
                                                </div>
                                                <el-table
                                                    :data="supplierList"
                                                    border
                                                    stripe
                                                    v-loading="tableLoaing"
                                                    row-key="id"
                                                    :default-expand-all="true"
                                                    ref="reviewTableRef"
                                                >
                                                    <el-table-column
                                                        label="序号"
                                                        align="center"
                                                        width="80"
                                                    >
                                                        <template #default="{ $index }">
                                                            {{ $index + 1 }}
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column
                                                        prop="supplierName"
                                                        align="center"
                                                        label="供方名称"
                                                        min-width="300"
                                                    >
                                                    </el-table-column>
                                                    <el-table-column
                                                        label="评分人"
                                                        min-width="120"
                                                        prop="ratingName"
                                                        align="center"
                                                    >
                                                        <template #default="{ row }">
                                                            <span v-if="!row.isParent">{{
                                                                row.ratingName
                                                            }}</span>
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column
                                                        label="评分"
                                                        min-width="160"
                                                        prop="operationScore"
                                                        align="center"
                                                    >
                                                        <template #default="{ row }">
                                                            <el-input-number
                                                                v-model="row.operationScore"
                                                                style="width: 100%"
                                                                :max="form.score"
                                                                :min="0"
                                                                controls-position="right"
                                                                placeholder="请输入评分"
                                                            />
                                                        </template>
                                                    </el-table-column>
                                                </el-table>
                                            </div>
                                        </div>
                                    </el-collapse>
                                </el-form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 批量评分弹窗 -->
        <el-dialog v-model="batchScoreVisible" title="批量评分" width="400px">
            <el-form>
                <el-form-item label="评分值">
                    <el-input-number
                        v-model="batchScore"
                        :min="0"
                        :max="form.score || 100"
                        style="width: 100%"
                        placeholder="请输入评分值"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="batchScoreVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmBatchScore">确定</el-button>
            </template>
        </el-dialog>

        <!-- 底部按钮 -->
        <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 { reactive, ref, onMounted, computed } from 'vue'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { useRoute, useRouter } from 'vue-router'
import { dataDetail, dataAdd,dataSupplierList } from '@/api/supplierMonitor/PerformanceManagement/PerformanceScoring'
import TreeSide from '@/components/TreeSide/index.vue'
import { Document, Folder, Film } from '@element-plus/icons-vue'
import { dataTable } from '@/api/supplierMonitor/BasicManagement/AssessmentCategory'
interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

interface ScoreItem {
    id: string
    category: string
    reviewContent: string
    defaultReviewer: string
    score: number
    weight: number
    isParent: boolean
    children?: ScoreItem[]
}

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

// 表单相关
const btnLoading = ref(false)
const tableLoaing = ref(false)
const addEditFormRef = ref()
const form = ref({})
const detailLoading = ref(false)
const activeCollapse = ref(['basic-info', 'score-info', 'evaluation-info'])
const classCatory = ref([])
// 编辑相关
const isEdit = computed(() => route.name === 'edit')
const editId = computed(() => route.params.id as string)

// 表单数据
const currentStep = ref(1)

const addEditForm = reactive<AddEditForm>({
    supplierName: '',
    evaluationSystemName: '',
    reviewRequirements: '',
    cycleType: '',
    cyclePeriod: '',
    details: []
})

const detailForm = ref({
    auditHistoryData: []
})
const supplierList = ref([])
// 表单验证规则
const addEditFormRules = reactive<FormRules>({})

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

// 左侧树形结构相关
const treeLoading = ref(false)
const currentClassType = ref('')
const currentNodeKey = ref('')
const defaultProps = {
    children: 'children',
    label: 'name',
    value:'performanceEvaluationDetailsId',
}
const treeData = ref([])

// 批量评分相关
const batchScoreVisible = ref(false)
const batchScore = ref(null)

// 获取分类
const getClass = (data: any) => {
    console.log('获取分类:', data)
}

// 节点点击
const nodeClick = (data: any) => {
    form.value = { ...data }
    currentNodeKey.value = data.id || data.code
    if (data.grade === '2') {
        getSupplierList(data)
    }
}
const getSupplierList = async (data: any) => {
    try {
        tableLoaing.value = true
        const res = await dataSupplierList(data.performanceEvaluationId,data.performanceEvaluationDetailsId)
        if (res.state) {
            supplierList.value = res.value
            supplierList.value.forEach((item) => {
                item.isParent = true
            })
        }
    } finally {
        tableLoaing.value = false // 无论成功或失败，都关闭加载状态
    }
}


// 打开批量评分弹窗
const openBatchScoreDialog = () => {
    if (!currentNodeKey.value || !form.value.grade || form.value.grade === '1') {
        ElMessage.warning('请先选择左侧树的子级评分项')
        return
    }
    batchScore.value = null
    batchScoreVisible.value = true
}

// 确认批量评分
const confirmBatchScore = () => {
    if (batchScore.value === null || batchScore.value === undefined) {
        ElMessage.warning('请输入评分值')
        return
    }

    if (form.value.score && batchScore.value > form.value.score) {
        ElMessage.warning(`评分值不能超过${form.value.score}分`)
        return
    }

    // 给supplierList中所有供应商赋值
    supplierList.value.forEach((supplier) => {
        supplier.operationScore = batchScore.value
    })

    batchScoreVisible.value = false
    ElMessage.success('批量评分成功')
}

// 清除所有评分
const clearAllScores = () => {
    supplierList.value.forEach((supplier) => {
        supplier.operationScore = null
    })
    ElMessage.success('清除评分成功')
}

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

// 验证评分是否填写完整
const validateScores = () => {
    const getAllItems = (items) => {
        let allItems = []
        items.forEach((item) => {
            // 包括所有项目（父级和子级）
            allItems.push(item)
            if (item.children && item.children.length > 0) {
                allItems = allItems.concat(getAllItems(item.children))
            }
        })
        return allItems
    }

    const allItems = getAllItems(addEditForm.details)
    const unScoredItems = allItems.filter(
        (item) =>
            item.operationScore === null ||
            item.operationScore === undefined ||
            item.operationScore === '' ||
            item.operationScore === 0
    )

    return unScoredItems
}

// 提交
const handleSubmit = () => {
    // 验证是否选中左侧树子级
    if (!currentNodeKey.value || !form.value.grade || form.value.grade === '1') {
        ElMessage.warning('请先选择左侧树的子级评分项')
        return
    }
    
    // 验证supplierList中是否有评分
    const unScoredSuppliers = supplierList.value.filter(
        (supplier) => supplier.operationScore === null || supplier.operationScore === undefined || supplier.operationScore === ''
    )
    if (unScoredSuppliers.length > 0) {
        ElMessage.warning(`还有${unScoredSuppliers.length}个供应商未填写评分，请完成所有评分后再提交`)
        return
    }
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                const value = await dataAdd(supplierList.value)
                if (value.state) {
                    ElMessage.success('保存成功')
                    // 更新当前节点的isOpt状态为已评标
                    updateNodeOptStatus(currentNodeKey.value, 1)
                    // router.push({ name: 'PerformanceScoring' })
                }
            } finally {
                btnLoading.value = false // 无论成功或失败，都关闭加载状态
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

// 更新节点评标状态
const updateNodeOptStatus = (nodeId: string, status: number) => {
    const updateNodeInTree = (nodes: any[]) => {
        for (let node of nodes) {
            if (node.id === nodeId || node.performanceEvaluationDetailsId === nodeId) {
                node.isOpt = status
                // 更新节点名称中的评标状态
                const baseName = node.performanceEvaluationDetailsName || node.name.replace(/<span class="status-tag[^>]*">[^<]*<\/span>/, '').trim()
                const isEvaluated = status === 1
                const statusHtml = isEvaluated 
                    ? '<span class="status-tag evaluated">已评分</span>'
                    : '<span class="status-tag not-evaluated">未评分</span>'
                node.name = `${baseName} ${statusHtml}`
                return true
            }
            if (node.children && node.children.length > 0) {
                if (updateNodeInTree(node.children)) {
                    return true
                }
            }
        }
        return false
    }
    updateNodeInTree(treeData.value)
}

// 获取详情数据
const getDetail = async (id: string | number) => {
    try {
        detailLoading.value = true
        const data = await dataDetail(id)
        Object.assign(addEditForm, data.value)
        addEditForm.details.forEach((item) => {
            item.name = item.assessmentIndicatorTypeName
            // 确保 isOpt 字段存在，默认为 0（未评标）
            if (item.isOpt === undefined || item.isOpt === null) {
                item.isOpt = 0
            }
        })
        if (addEditForm.status == 2 || addEditForm.status == 3) {
            currentStep.value = 1
        }
        if (addEditForm.status == 4) {
            currentStep.value = 2
        }
        if (addEditForm.status == 5) {
            currentStep.value = 3
        }
        if (addEditForm.status == 1) {
            currentStep.value = 4
        }
        initScoreDetails()
    } finally {
        detailLoading.value = false // 无论成功或失败，都关闭加载状态
    }
}
// 获取评价类别分类
const getCategory = async () => {
    try {
        let params = {
            pageBean: {
                page: -1,
                pageSize: -1
            },
            querys: []
        }
        const data = await dataTable(params)
        classCatory.value = data.rows
    } finally {
    }
}
// 初始化评分项树形数据
const initScoreDetails = () => {
    classCatory.value.forEach((category) => {
        category.children = []
        category.grade = '1'
        // 确保父级节点有唯一标识
        if (!category.id && category.code) {
            category.id = category.code
        }
    })
    addEditForm.details.forEach((item) => {
        classCatory.value.forEach((category) => {
            if (category.code === item.assessmentIndicatorTypeCode) {
                const isEvaluated = item.isOpt === 1 || item.isOpt === '1'
                const statusHtml = isEvaluated 
                    ? '<span class="status-tag evaluated">已评分</span>'
                    : '<span class="status-tag not-evaluated">未评分</span>'
                category.children.push({
                    ...item,
                    name: `${item.performanceEvaluationDetailsName} ${statusHtml}`,
                    grade: '2',
                    isParent: true,
                    // 确保子级节点有唯一标识
                    id: item.performanceEvaluationDetailsId,
                    // 确保 isOpt 字段存在，默认为 0（未评标）
                    isOpt: item.isOpt !== undefined ? item.isOpt : 0
                })
            }
        })
    })
    treeData.value = classCatory.value
}

onMounted(() => {
    getCategory()
    // 如果是编辑模式，获取详情数据
    if (route.query.id) {
        getDetail(route.query.id)
    }
})
</script>

<style lang="scss" scoped>
.form-content {
    height: 100vh;
    display: flex;
    flex-direction: column;

    .page-form {
        flex: 1;
        overflow: hidden;
        padding: 16px;
        width: 100%;
    }
}

.review-actions {
    display: flex;
    padding: 10px 0 10px 10px;
}

.step-container {
    width: 100%;
    margin-bottom: 20px;
}

.review-requirements {
    padding: 16px;
    .review-requirements-title {
        color: var(--theme-text-primary);
        margin-bottom: 5px;
        font-size: 14px;
        font-weight: bold;
    }
    ul {
        list-style: none;
        li {
            color: var(--theme-text-primary);
            line-height: 25px;
            font-size: 14px;
        }
    }
}
.base-more {
    display: flex;
    align-items: center;
    margin-right: 10px;
    cursor: pointer;
    color: #1a8cff;
}

.main-content {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.main-layout {
    display: flex;
    flex: 1;
    gap: 16px;
    min-height: 0;
}

.left-tree {
    width: 280px;
    flex-shrink: 0;
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    overflow: hidden;

    :deep(.tree-side-content) {
        height: 100%;
        overflow-y: auto;
    }

    &::-webkit-scrollbar {
        width: 6px;
    }

    &::-webkit-scrollbar-track {
        background: #f5f5f5;
    }

    &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;

        &:hover {
            background: #a8a8a8;
        }
    }
}

.right-table {
    flex: 1;
    min-width: 0;
    background: #fff;
    border-radius: 6px;
    overflow: hidden;

    .content-area {
        height: 100%;
        overflow-y: auto;
        padding: 0;
    }

    &::-webkit-scrollbar {
        width: 6px;
    }

    &::-webkit-scrollbar-track {
        background: #f5f5f5;
    }

    &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;

        &:hover {
            background: #a8a8a8;
        }
    }
}

.section-title {
    display: flex;
    align-items: center;
    font-weight: bold;
    
    .el-icon {
        margin-right: 8px;
    }
}

.score-section {
    margin-bottom: 16px;
    padding: 0 16px;

    .section-title {
        padding: 16px 0 8px 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        position: sticky;
        top: 0;
        z-index: 100;
        background: #EEEEEE;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        margin: 0 -16px;
        padding-left: 16px;
        padding-right: 16px;
    }

    .section-content {
        padding: 0;
    }

    .score-actions {
        position: sticky;
        top: 56px;
        z-index: 99;
        background: #fff;
        padding: 8px 0;
        margin: 0 -16px;
        padding-left: 16px;
        padding-right: 16px;
    }
}

// 评分折叠栏吸顶效果
:deep(.el-collapse-item[name='score-info']) {
    .el-collapse-item__header {
        position: sticky;
        top: 0;
        z-index: 100;
        background: #fff;
        border-bottom: 1px solid #e4e7ed;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        margin-bottom: 0;
    }
}

.section-content {
    padding: 16px;
}

.custom-tree-node {
    display: flex;
    align-items: center;
    width: 100%;
    
    .node-label {
        margin-left: 8px;
        margin-right: 8px;
    }
}

// 评标状态样式
:deep(.status-tag) {
    display: inline-block;
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 4px;
    margin-left: 8px;
    
    &.not-evaluated {
        background-color: #f56c6c;
        color: white;
    }
    
    &.evaluated {
        background-color: #409eff;
        color: white;
    }
}
</style>
