<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="step-container">
                        <el-steps
                            :active="currentStep"
                            align-center
                            finish-status="success"
                            process-status="finish"
                        >
                            <el-step title="1 考核创建"></el-step>
                            <el-step title="2 绩效考核评分"></el-step>
                            <el-step title="3 绩效考核评价"></el-step>
                            <el-step title="4 完成"></el-step>
                        </el-steps>
                    </div>
                    <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="supplierName"
                                                    >{{ addEditForm.supplierName || '-' }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <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>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    发起人
                                                </template>
                                                <el-form-item prop="initiatorName">
                                                    {{ addEditForm.initiatorName }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    总分值
                                                </template>
                                                <el-form-item prop="totalScore">
                                                    {{ addEditForm.totalScore }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                        </el-descriptions>
                                        <div class="review-requirements">
                                            <div class="review-requirements-title">评审要求:</div>
                                            <!-- <ul>
                                                <li>1、没有做到:0分;</li>
                                                <li>2、部分做到,只有部分证据:半满分;</li>
                                                <li>3、完全做到,而且证据充分:满分。</li>
                                                <li>
                                                    【注:如果不涉及或不适用,请用"NA"在"评分栏"中标明,并默认为满分。】
                                                </li>
                                            </ul> -->
                                            <div>{{ addEditForm.desc }}</div>
                                        </div>
                                    </div>
                                </el-collapse-item>

                                <!-- 评分项 !-->
                                <el-collapse-item name="score-info">
                                    <template #title>
                                        <div class="section-title">
                                            <el-icon><Document /></el-icon>
                                            <span>评分项</span>
                                        </div>
                                    </template>
                                    <div class="section-content">
                                        <el-table
                                            :data="addEditForm.details"
                                            border
                                            stripe
                                            row-key="id"
                                            :tree-props="{
                                                children: 'children',
                                                hasChildren: 'hasChildren',
                                                expandColumnKey: 'name'
                                            }"
                                            :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="name"
                                                align="center"
                                                label="类别"
                                                width="180"
                                            >
                                                <template #default="{ row }">
                                                    <div v-if="row.isParent">{{ row.name }}</div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                label="评审内容"
                                                prop="performanceEvaluationDetailsName"
                                                min-width="200"
                                            />
                                            <!-- <el-table-column
                                                label="评审人"
                                                width="120"
                                                prop="ratingName"
                                                align="center"
                                            >
                                            </el-table-column> -->
                                            <el-table-column
                                                label="分值"
                                                width="100"
                                                prop="score"
                                                align="center"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                label="评分"
                                                width="200"
                                                prop="operationScore"
                                                align="center"
                                            >
                                                <template #default="{ row }">
                                                    <el-input-number
                                                        v-model="row.operationScore"
                                                        style="width: 100%"
                                                        :max="row.score"
                                                        controls-position="right"
                                                    />
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </el-collapse-item>

                                <!-- 供应商考核评价 !-->
                                <!-- <el-collapse-item name="evaluation-info">
                                    <template #title>
                                        <div class="section-title">
                                            <el-icon><Document /></el-icon>
                                            <span>供应商考核评价</span>
                                        </div>
                                    </template>
                                    <div class="section-content">
                                        <el-table :data="detailForm.auditHistoryData" border stripe>
                                            <el-table-column
                                                label="序号"
                                                prop="index"
                                                width="80"
                                                align="center"
                                            />
                                            <el-table-column
                                                label="审核环节"
                                                align="center"
                                                prop="step"
                                            />
                                            <el-table-column
                                                label="审批意见"
                                                align="center"
                                                prop="comments"
                                            />
                                            <el-table-column
                                                label="办理人"
                                                align="center"
                                                prop="handler"
                                            />
                                            <el-table-column
                                                label="时间"
                                                align="center"
                                                prop="time"
                                            />
                                        </el-table>
                                    </div>
                                </el-collapse-item> -->
                            </el-collapse>
                        </el-form>
                    </div>
                </div>
            </div>
        </div>

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

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { type FormRules } from 'element-plus'
import { reactive, ref, onMounted } from 'vue'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { useRoute, useRouter } from 'vue-router'
import { dataDetail,dataAdd } from '@/api/supplierMonitor/PerformanceManagement/PerformanceScoring'
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 addEditFormRef = ref()
const detailLoading = ref(false)
const activeCollapse = ref(['basic-info', 'score-info', 'evaluation-info'])

// 编辑相关
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 addEditFormRules = reactive<FormRules>({
    supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
    evaluationSystemName: [{ required: true, message: '请输入绩效考核体系', trigger: 'blur' }],
    reviewRequirements: [{ required: true, message: '请输入考核年度', trigger: 'blur' }],
    cycleType: [{ required: true, message: '请输入周期类型', trigger: 'blur' }],
    cyclePeriod: [{ required: true, message: '请输入考核周期', trigger: 'blur' }]
})

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

// 取消
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 = () => {
    // 验证评分
    const unScoredItems = validateScores()
    if (unScoredItems.length > 0) {
        ElMessage.warning(`还有${unScoredItems.length}个项目未填写评分，请完成所有评分后再提交`)
        return
    }
    
    const newDetails = []
    addEditForm.details.forEach((item) => {
        const { children, ...itemWithoutChildren } = item
        newDetails.push(itemWithoutChildren)
        if (children && children.length > 0) {
            children.forEach((child) => {
                const { children: _, ...childWithoutChildren } = child
                newDetails.push(childWithoutChildren)
            })
        }
    })
    addEditForm.details = newDetails
    console.log(addEditForm, 'addEditForm')
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                const value = await dataAdd(addEditForm.details)
                if (value.state) {
                    ElMessage.success('保存成功')
                    router.push({ name: 'PerformanceScoring' })
                }
            } finally {
                btnLoading.value = false // 无论成功或失败，都关闭加载状态
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}
// 获取详情数据
const getDetail = async (id: string | number) => {
    try {
        detailLoading.value = true
        const data = await dataDetail(id)
        Object.assign(addEditForm, data.value)
        const groupedDetails = []
        const codeMap = new Map()
        data.value.details.forEach((item: any) => {
            if (codeMap.has(item.assessmentIndicatorTypeCode)) {
                const parent = codeMap.get(item.assessmentIndicatorTypeCode)
                parent.children.push({ ...item, isParent: false })
            } else {
                const parentItem = { ...item, children: [], isParent: true }
                groupedDetails.push(parentItem)
                codeMap.set(item.assessmentIndicatorTypeCode, parentItem)
            }
        })
        addEditForm.details = groupedDetails
        addEditForm.details.forEach((item) => {
            item.name = item.assessmentIndicatorTypeName
        })
        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
        }
    } finally {
        detailLoading.value = false // 无论成功或失败，都关闭加载状态
    }
}
onMounted(() => {
    // 如果是编辑模式，获取详情数据
    if (route.query.id) {
        getDetail(route.query.id)
    }
})
</script>

<style lang="scss" scoped>
.form-content {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start !important;

    .page-form {
        overflow-y: hidden;
        overflow-y: auto;
        padding: 0 20px;

        /* 隐藏滚动条样式 */
        &::-webkit-scrollbar {
            width: 0;
            height: 0;
        }

        &::-webkit-scrollbar-track {
            background: transparent;
        }

        &::-webkit-scrollbar-thumb {
            background: transparent;
        }

        /* Firefox 隐藏滚动条 */
        scrollbar-width: none;
        -ms-overflow-style: none;
    }
}

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