<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
                                                    >
                                                    <el-input
                                                        v-model="supplierSearchText"
                                                        placeholder="搜索供方名称"
                                                        clearable
                                                        style="width: 200px;margin-left: 50px;"
                                                        @input="handleSupplierSearch"
                                                    >
                                                        <template #prefix>
                                                            <el-icon><Search /></el-icon>
                                                        </template>
                                                    </el-input>
                                                </div>
                                                <el-table
                                                    :data="filteredSupplierList"
                                                    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, ElLoading } 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, Search } 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 supplierSearchText = 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 filteredSupplierList = computed(() => {
    if (!supplierSearchText.value) {
        return supplierList.value
    }
    return supplierList.value.filter(supplier => 
        supplier.supplierName && supplier.supplierName.toLowerCase().includes(supplierSearchText.value.toLowerCase())
    )
})

// 处理供方搜索
const handleSupplierSearch = () => {
    // 搜索逻辑已通过computed属性实现
}

// 获取分类
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) {
            const loading = ElLoading.service({
                lock: true,
                text: '正在保存评分...',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            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
                loading.close()
            }
        } 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 = () => {
    if (!addEditForm.details || addEditForm.details.length === 0) {
        console.warn('评分项数据为空')
        return
    }

    // 过滤并初始化分类数据
    const detailCodes = addEditForm.details.map(item => item.assessmentIndicatorTypeCode)
    const filteredCategories = classCatory.value.filter(category => 
        detailCodes.includes(category.code)
    )

    // 构建树形结构
    const treeNodes = filteredCategories.map(category => ({
        ...category,
        id: category.id || category.code,
        grade: '1',
        children: addEditForm.details
            .filter(item => item.assessmentIndicatorTypeCode === category.code)
            .map(item => {
                const isEvaluated = item.isOpt === 1 || item.isOpt === '1'
                const statusHtml = isEvaluated 
                    ? '<span class="status-tag evaluated">已评分</span>'
                    : '<span class="status-tag not-evaluated">未评分</span>'
                return {
                    ...item,
                    id: item.performanceEvaluationDetailsId,
                    name: `${item.performanceEvaluationDetailsName || item.name || '未命名'} ${statusHtml}`,
                    grade: '2',
                    isParent: true,
                    isOpt: item.isOpt !== undefined ? item.isOpt : 0
                }
            })
    }))

    treeData.value = treeNodes
    console.log('初始化评分项完成:', treeData.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;
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 8px;
    }
}

// 评分折叠栏吸顶效果
: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: flex-start;
    width: 100%;
    
    .node-label {
        margin-left: 8px;
        margin-right: 8px;
        flex: 1;
        word-wrap: break-word;
        word-break: break-all;
        white-space: normal;
        line-height: 1.4;
    }
}

// 评标状态样式
:deep(.el-tree-node__content) {
    height: auto !important;
    min-height: 26px;
    padding: 4px 0;
    align-items: flex-start;
    
    .el-tree-node__label {
        word-wrap: break-word;
        word-break: break-all;
        white-space: normal;
        line-height: 1.4;
        flex: 1;
    }
}

: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>
