<template>
    <div class="edit-add-detail"  v-loading="detailLoading"  element-loading-text="加载中...">
        <div class="form-content">
            <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">
                                                    <el-select
                                                        v-model="addEditForm.supplierName"
                                                        clearable
                                                        filterable
                                                        remote
                                                        @change="changeCompany"
                                                        :remote-method="remoteSearchSupplier"
                                                        :loading="supplierLoading"
                                                        placeholder="请输入"
                                                    >
                                                        <el-option
                                                            v-for="item in enterpriseList"
                                                            :key="item.orgId"
                                                            :label="item.companyName"
                                                            :value="item.companyCode"
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    绩效考核体系
                                                </template>
                                                <el-form-item prop="valuationConfigurationName">
                                                    <el-select
                                                        v-model="
                                                            addEditForm.valuationConfigurationName
                                                        "
                                                        filterable
                                                        placeholder="请选择"
                                                        @change="changeEvaluation"
                                                    >
                                                        <el-option
                                                            v-for="item in appraisalList"
                                                            :key="item.id"
                                                            :label="item.name"
                                                            :value="item.id"
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    考核年度
                                                </template>
                                                <el-form-item prop="assessmentYear">
                                                    <el-date-picker
                                                        v-model="addEditForm.assessmentYear"
                                                        type="year"
                                                        value-format="YYYY"
                                                        placeholder="请选择"
                                                    ></el-date-picker>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    考核类型
                                                </template>
                                                <el-form-item prop="assessmentType">
                                                    <el-select
                                                        v-model="addEditForm.assessmentType"
                                                        placeholder="请选择"
                                                        @change="handleAssessmentTypeChange"
                                                    >
                                                        <el-option
                                                            v-for="(item, i) in getDictionaryByCode(
                                                                'khpj-khlx'
                                                            )"
                                                            :key="i"
                                                            :label="item.name"
                                                            :value="item.value"
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    考核周期
                                                </template>
                                                <el-form-item
                                                    prop="assessmentMonth"
                                                    v-if="addEditForm.assessmentType == 1"
                                                >
                                                    <el-date-picker
                                                        v-model="addEditForm.assessmentMonth"
                                                        type="month"
                                                        value-format="YYYY-MM"
                                                        :default-value="
                                                            new Date(addEditForm.assessmentYear, 0)
                                                        "
                                                        :disabled-date="disabledDate"
                                                        placeholder="请选择"
                                                    ></el-date-picker>
                                                </el-form-item>
                                                <el-form-item
                                                    prop="assessmentQuater"
                                                    v-if="addEditForm.assessmentType == 2"
                                                >
                                                    <DatePopover
                                                        format="YYYY年Q季度"
                                                        value-format="YYYY-Q"
                                                        v-model="addEditForm.assessmentQuater"
                                                        placeholder="请选择季度"
                                                        :disabled-date="disabledDate"
                                                    ></DatePopover>
                                                </el-form-item>
                                                <el-form-item prop="assessmentYear">
                                                    <el-date-picker
                                                        v-model="addEditForm.assessmentYear"
                                                        type="year"
                                                        v-if="addEditForm.assessmentType == 3"
                                                        value-format="YYYY"
                                                        :default-value="
                                                            new Date(addEditForm.assessmentYear, 0)
                                                        "
                                                        :disabled-date="disabledDate"
                                                        placeholder="请选择"
                                                    ></el-date-picker>
                                                </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>
                                            <div>
                                                {{ addEditForm.desc }}
                                            </div>
                                            <!-- <ul>
                                                <li>1、没有做到:0分;</li>
                                                <li>2、部分做到,只有部分证据:半满分;</li>
                                                <li>3、完全做到,而且证据充分:满分。</li>
                                                <li>
                                                    【注:如果不涉及或不适用,请用"NA"在"评分栏"中标明,并默认为满分。】
                                                </li>
                                            </ul> -->
                                        </div>
                                        <div class="review-actions">
                                            <el-button type="primary" @click="assignReviewers">
                                                分配评审人
                                            </el-button>
                                            <el-button @click="clearReviewers">
                                                清空评审人
                                            </el-button>
                                        </div>

                                        <el-table
                                            :data="addEditForm.details"
                                            border
                                            stripe
                                            row-key="id"
                                            :tree-props="{
                                                children: 'children',
                                                hasChildren: 'hasChildren',
                                                expandColumnKey: 'name'
                                            }"
                                            :default-expand-all="true"
                                            @selection-change="handleSelectionChange"
                                            ref="reviewTableRef"
                                        >
                                            <el-table-column
                                                type="selection"
                                                width="55"
                                                align="center"
                                            />
                                            <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="content"
                                                min-width="300"
                                            />
                                            <el-table-column
                                                label="评审人"
                                                width="200"
                                                align="center"
                                            >
                                                <template #default="{ row }">
                                                    <el-select
                                                        v-model="row.ratingName"
                                                        placeholder="请选择"
                                                        clearable
                                                        @change="changeRatingName(row)"
                                                    >
                                                        <el-option
                                                            v-for="item in reviewerOptions"
                                                            :key="item.userId"
                                                            :label="item.fullname"
                                                            :value="item.userId"
                                                        />
                                                    </el-select>
                                                </template>
                                            </el-table-column>
                                        </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>
        <!-- 分配评审人弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            title="分配评审人"
            width="500"
            :before-close="handleClose"
            align-center
            :close-on-click-modal="false"
        >
            <div>
                <el-form ref="formRef" :model="form" label-width="80px">
                    <el-form-item label="评审人">
                        <el-select
                            v-model="form.ratingName"
                            filterable
                            placeholder="请选择"
                            clearable
                        >
                            <el-option
                                v-for="item in reviewerOptions"
                                :key="item.userId"
                                :label="item.fullname"
                                :value="item.userId"
                            />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">关 闭</el-button>
                    <el-button type="primary" @click="saveDialog"> 保 存 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import DatePopover from '@/components/DatePopover/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { type FormRules } from 'element-plus'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { reactive, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
    getEvaluationConfig,
    dataUpdate,
    dataAdd,
    dataDetail,
    getEvaluationConfigDetail,
    dataEnterpriseList
} from '@/api/supplierMonitor/PerformanceManagement/PerformanceEvaluation'
import { getOrgUserList } from '@/api/system/user'
interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}
interface formRef {
    [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[]
}

interface ReviewerOption {
    value: string
    label: string
    children?: ReviewerOption[]
}

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

// 表单相关
const addEditFormRef = ref()
const detailLoading = ref(false)
const activeCollapse = ref(['basic-info'])
const appraisalList = ref<any[]>([])
const enterpriseList = ref<any[]>([])
const supplierLoading = ref(false)
const dialogVisible = ref(false)
const btnLoading = ref(false)
const userDetail = ref<any>({})
// 编辑相关
const isEdit = computed(() => route.name === 'edit')
const editId = computed(() => route.params.id as string)
getDictionaryByCode
// 表单数据
const currentStep = ref(0)
const form = reactive<formRef>({
    ratingName: ''
})
const addEditForm = reactive<AddEditForm>({
    supplierName: '',
    valuationConfigurationName: '',
    assessmentYear: new Date().getFullYear().toString(),
    assessment: new Date().getFullYear().toString(),
    assessmentType: '3',
    valuationConfigurationCode: '',
    totalScore: '',
    enterpriseCode: '',
    enterpriseName:'',
    enterpriseId: '',
    valuationConfigurationId: '',
    desc: '',
    details: [],
    supplierEnterpriseId: '',
    supplierNumber: '',
    assessmentMonth: '',
    assessmentQuater: '',
    initiatorName:'',
    initiatorId:'',
    initiatorAccount:''
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    supplierName: [{ required: true, message: '请选择供应商名称', trigger: 'change' }],
    valuationConfigurationName: [
        { required: true, message: '请选择绩效考核体系', trigger: 'change' }
    ],
    assessmentYear: [{ required: true, message: '请选择考核年度', trigger: 'change' }],
    valuationConfigurationCode: [{ required: true, message: '请选择周期类型', trigger: 'change' }],
    valuationConfigurationId: [{ required: true, message: '请选择考核周期', trigger: 'change' }],
    assessmentQuater: [{ required: true, message: '请选择考核周期', trigger: 'change' }],
    assessmentMonth: [{ required: true, message: '请选择考核周期', trigger: 'change' }]
})

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

// 评审人选项
const reviewerOptions = ref<ReviewerOption[]>([])

// 获取评审人
const getReviewerOptions = async () => {
    const params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: [
            {
                group: 'orgTree',
                operation: 'IN',
                property: 'ORG_ID_',
                relation: 'AND',
                value: userDetail.value.userDetail.org[0].orgId
            }
        ]
    }
    const { total = 0, rows = [] } = await getOrgUserList(params)
    reviewerOptions.value = rows
}

// 表格选择变化
const handleSelectionChange = (selection: ScoreItem[]) => {
    selectedRows.value = selection
}

// 禁用日期函数
const disabledDate = (time: Date) => {
    if (!addEditForm.assessmentYear) return false
    return time.getFullYear() !== parseInt(addEditForm.assessmentYear)
}

// 取消
const handleCancel = () => {
    router.push({ name: 'PerformanceEvaluation' })
}
// 分配评审人
const assignReviewers = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要分配评审人的项目')
        return
    }
    dialogVisible.value = true
    // 这里可以弹出一个对话框让用户选择评审人，然后批量分配
}

// 清空评审人
const clearReviewers = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要清空评审人的项目')
        return
    }

    // 递归清空评审人
    const clearReviewer = (data, selectedId) => {
        for (let item of data) {
            if (item.id === selectedId) {
                item.ratingName = ''
                return true
            }
            if (item.children && item.children.length > 0) {
                if (clearReviewer(item.children, selectedId)) {
                    return true
                }
            }
        }
        return false
    }

    selectedRows.value.forEach((selectedRow) => {
        clearReviewer(addEditForm.details, selectedRow.id)
    })

    ElMessage.success(`已清空${selectedRows.value.length}个项目的评审人`)
}
// 批量保存评审人
const saveDialog = () => {
    if (!form.ratingName) {
        ElMessage.warning('请选择评审人')
        return
    }
    // 递归查找并更新评审人
    const updateReviewer = (data, selectedId, reviewer) => {
        for (let item of data) {
            if (item.id === selectedId) {
                item.ratingName = reviewer
                return true
            }
            if (item.children && item.children.length > 0) {
                if (updateReviewer(item.children, selectedId, reviewer)) {
                    return true
                }
            }
        }
        return false
    }
    selectedRows.value.forEach((selectedRow) => {
        updateReviewer(addEditForm.details, selectedRow.id, form.ratingName)
    })
    ElMessage.success(`已为${selectedRows.value.length}个项目分配评审人`)
    handleClose()
}
// 关闭分配评审人弹窗
const handleClose = () => {
    form.ratingName = ''
    dialogVisible.value = false
}
const changeRatingName = (row: ScoreItem) => {
    reviewerOptions.value.forEach((item) => {
        if(row.ratingName == item.userId){
            row.ratingName = item.fullname
            row.ratingAccount = item.account
            row.ratingId = item.userId
        }
    })
}
// 获取企业列表
const getEnterpriseList = async () => {
    let params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: []
    }
    const { total = 0, rows = [] } = await dataEnterpriseList(params)
    enterpriseList.value = rows
}
// 获取考核体系配置
const getEvaluationConfigData = async () => {
    detailLoading.value = true
    try {
        let params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: [
            { group: 'main', operation: 'EQUAL', property: 'status', relation: 'AND', value: '1' }
        ],
        sorter: [
            {
                direction: 'DESC',
                property: 'createTime'
            }
        ]
    }
    const { total = 0, rows = [] } = await getEvaluationConfig(params)
    appraisalList.value = rows
    } finally {
        detailLoading.value = false
    }
}
// 获取考核详情
const getAppraisalDetail = async (id: string) => {
    try {
        detailLoading.value = true
        const data = await getEvaluationConfigDetail(id)
        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
        })
        addEditForm.totalScore = data.value.totalScore
    } finally {
        detailLoading.value = false
    }
}
// 获取选择考核详情数据
const changeEvaluation = (value: any) => {
    appraisalList.value.forEach((item) => {
        if (item.id === value) {
            addEditForm.valuationConfigurationName = item.name
            addEditForm.valuationConfigurationCode = item.code
            addEditForm.valuationConfigurationId = item.id
            addEditForm.desc = item.desc
        }
    })
    getAppraisalDetail(value)
}
// 获取所选企业详情
const changeCompany = (value: any) => {
    enterpriseList.value.forEach((item) => {
        if (item.companyCode === value) {
            addEditForm.supplierName = item.companyName
            addEditForm.supplierNumber = item.companyCode
            addEditForm.supplierEnterpriseId = item.orgId
        }
    })
}
// 远程搜索供应商
const remoteSearchSupplier = async (query: string) => {
    if (query) {
        supplierLoading.value = true
        try {
            const params = {
                pageBean: { page: 1, pageSize: -1 },
                querys: [
                    {
                        group: 'main',
                        operation: 'LIKE',
                        property: 'companyName',
                        relation: 'AND',
                        value: query
                    }
                ]
            }
            const { rows = [] } = await dataEnterpriseList(params)
            enterpriseList.value = rows
        } finally {
            supplierLoading.value = false
        }
    } else {
        enterpriseList.value = []
    }
}

// 考核类型变化处理
const handleAssessmentTypeChange = (value: any) => {
    if (value == 1) {
        addEditForm.assessmentMonth =
            addEditForm.assessmentYear + '-' + String(new Date().getMonth() + 1).padStart(2, '0')
    } else if (value == 2) {
        const currentQuarter = Math.floor((new Date().getMonth() + 3) / 3)
        addEditForm.assessmentQuater = addEditForm.assessmentYear + '-' + currentQuarter
    } else if (value == 3) {
        addEditForm.assessmentYear = addEditForm.assessmentYear
    } else {
        addEditForm.assessmentMonth = ''
        addEditForm.assessmentQuater = ''
    }
}
// 提交
const handleSubmit = () => {
    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
    addEditForm.details.forEach((item) => {
        item.performanceEvaluationDetailsId = item.id
        item.performanceEvaluationDetailsName = item.content
        item.performanceEvaluationDetailsCode = item.code
    })

    // 从 assessmentMonth 中提取月份
    if (addEditForm.assessmentMonth) {
        addEditForm.assessmentMonth = parseInt(addEditForm.assessmentMonth.split('-')[1]).toString()
    }

    // 从 assessmentQuater 中提取季度
    if (addEditForm.assessmentQuater) {
        addEditForm.assessmentQuater = addEditForm.assessmentQuater.split('-')[1]
    }

    console.log(addEditForm, 'addEditForm')
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                const value = addEditForm.id
                    ? await dataUpdate({ ...addEditForm })
                    : await dataAdd({ ...addEditForm })
                if (value.state) {
                    ElMessage.success('保存成功')
                    router.push({ name: 'PerformanceEvaluation' })
                }
            } finally {
                btnLoading.value = false // 无论成功或失败，都关闭加载状态
            }
            // 这里可以添加提交逻辑
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

onMounted(() => {
    const storedData = localStorage.getItem('user')
    if (storedData) {
        userDetail.value = JSON.parse(storedData)
    }
    addEditForm.enterpriseCode = userDetail.value.userDetail.org[0].orgCode
    addEditForm.enterpriseId = userDetail.value.userDetail.org[0].orgId
    addEditForm.enterpriseName = userDetail.value.userDetail.org[0].orgName
    addEditForm.initiatorName = userDetail.value.userInfo.username
    addEditForm.initiatorId = userDetail.value.userInfo.userId
    addEditForm.initiatorAccount = userDetail.value.userInfo.account
    getEvaluationConfigData()
    getEnterpriseList()
    getReviewerOptions()
    // 如果是编辑模式，获取详情数据
    if (isEdit.value) {
        // getDetail(editId.value)
    }
})
</script>

<style lang="scss" scoped>
.review-requirements {
    margin-bottom: 10px;
    .review-requirements-title {
        color: var(--theme-text-primary);
        margin-bottom: 5px;
        font-size: 15px;
        font-weight: bold;
    }
    ul {
        list-style: none;
        li {
            color: var(--theme-text-primary);
            line-height: 25px;
            font-size: 15px;
        }
    }
}
.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;
}

.content-area {
    /* 确保容器的高度计算正确 */
    box-sizing: border-box;

    :deep(.el-collapse) {
        /* 通过添加 1px 来补偿 border 导致的 1px 高度差 */
        margin-bottom: 1px;
    }
}
</style>
