<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="id"
                                @node-click="nodeClick"
                            >
                                <template v-slot:treeIcon="{ data }">
                                    <div class="custom-tree-node">
                                        <el-icon>
                                            <Folder v-if="data.grade === '1'" />
                                            <Film v-else />
                                        </el-icon>
                                    </div>
                                </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">
                                                <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"
                                                    >
                                                    </el-table-column>
                                                </el-table>
                                            </div>
                                        </div>
                                    </el-collapse>
                                </el-form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部按钮 -->
        <div class="footer">
            <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 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 supplierList = ref([])
// 表单验证规则
const addEditFormRules = reactive<FormRules>({})
// 左侧树形结构相关
const treeLoading = ref(false)
const currentClassType = ref('')
const currentNodeKey = ref('')
const defaultProps = {
    children: 'children',
    label: 'name'
}
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 handleCancel = () => {
    router.push({ name: 'PerformanceScoring' })
}

// 获取详情数据
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
        })
        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) {
                category.children.push({
                    ...item,
                    name: item.performanceEvaluationDetailsName,
                    grade: '2',
                    isParent: true,
                    // 确保子级节点有唯一标识
                    id: item.id || `${category.code}_${item.performanceEvaluationDetailsName}`
                })
            }
        })
    })
    treeData.value = classCatory.value
    console.log(treeData.value, 'treeData')
}

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;
        margin: 0 -16px;
        padding-left: 16px;
        padding-right: 16px;
    }

    .section-content {
        padding: 0;
        margin-top: 8px;
    }

    .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;
}
</style>
