<template>
    <super-dialog
        v-model="dialogVisible"
        :title="title"
        custom-class="notification-dialog"
        top="10vh"
        width="60%"
        @closed="closePage"
        @open="openPage"
    >
        <div
            v-loading="detailLoading"
            class="table-container"
            element-loading-background="rgba(10 ,38 ,61, 0.9)"
        >
            <el-form
                ref="addEditFormRef"
                :model="addEditForm"
                :rules="addEditFormRules"
                label-position="left"
                label-suffix="："
                size="large"
            >
                <el-collapse v-model="activeCollapse">
                    <div id="review-allocation" class="content-section">
                        <el-collapse-item name="review-allocation">
                            <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 :span="2">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            评价体系
                                        </template>
                                        <el-form-item prop="reviewAllocation">
                                            <el-select
                                                v-model="addEditForm.reviewAllocation"
                                                placeholder="请选择"
                                                @change="changeLocation"
                                            >
                                                <el-option
                                                    v-for="item in reviewAllocationOptions"
                                                    :key="item.id"
                                                    :label="item.name"
                                                    :value="item.id"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-descriptions-item>
                                </el-descriptions>

                                <div class="review-actions">
                                    <el-button type="primary" @click="assignReviewers"
                                        >分配评分人
                                    </el-button>
                                    <el-button @click="clearReviewers">清空评分人</el-button>
                                </div>

                                <el-table
                                    ref="reviewTableRef"
                                    :data="addEditForm.reviewRatingDetails2Map"
                                    :default-expand-all="true"
                                    :tree-props="{
                                        children: 'children',
                                        hasChildren: 'hasChildren',
                                        expandColumnKey: 'classificationName'
                                    }"
                                    row-key="id"
                                    @selection-change="handleSelectionChange"
                                >
                                    <el-table-column align="center" type="selection" width="55" />
                                    <el-table-column label="序号" width="80">
                                        <template #default="{ $index }">
                                            {{ $index + 1 }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        align="center"
                                        label="类别"
                                        prop="classificationName"
                                        width="120"
                                    >
                                        <template #default="{ row }">
                                            <div v-if="row.isParent">
                                                {{ row.classificationName }}
                                            </div>
                                            <div v-else></div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="评审内容" min-width="200" prop="name" />
                                    <el-table-column align="center" label="评分人" width="150">
                                        <template #default="{ row }">
                                            <el-select
                                                v-model="row.panelList"
                                                clearable
                                                multiple
                                                placeholder="请选择"
                                                @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>
                    </div>
                </el-collapse>
            </el-form>
        </div>
        <div slot="footer" style="display: flex; justify-content: center; width: 100%">
            <el-button :loading="loadingBtn" type="primary" @click="submitObject">确定</el-button>
            <el-button @click="closePage">取消</el-button>
        </div>

        <!-- 批量评分人 -->
        <reviewer-dialog
            ref="rejectDialogRef"
            v-model:isShowAdd="isShowReviewerDialog"
            :selectedRows="selectedRows"
            title="评分人分配"
            @divideSuccess="handleReviewerSuccess"
        ></reviewer-dialog>
    </super-dialog>
</template>

<script lang="ts" setup>
import SuperDialog from '@/components/Dialog/index.vue'
import reviewerDialog from '@/views/SupplierMonitor/QualificationAudit/BasicInformationAudit/reviewerDialog.vue'
import {
    audit,
    getReviewConfiguration
} from '@/api/supplierMonitor/QualificationAudit/BasicInformationAudit'
import { dataSubmitOtherInfo } from '@/api/supplierMonitor/QualificationAudit/SupplyInfo'
import { useRoute } from 'vue-router'
import { getOrgUserList } from '@/api/system/user'

import { computed, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'

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

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

const props = defineProps({
    isShowAdd: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: ''
    },
    formDataValue: {
        type: Object,
        default: () => ({})
    }
})
const loadingBtn = ref(false)
// ==================== 表单相关 ====================
const activeCollapse = ref<string[]>(['review-allocation'])

const reviewAllocationOptions = ref([])

const detailLoading = ref<Boolean>(false)

const addEditFormRef = ref<any>(null)

const addEditForm = ref<any>({
    reviewAllocation: '',
    reviewRatingDetails2Map: []
})

const addEditFormRules = ref<any>({
    reviewAllocation: [{ required: true, message: '请选择评价体系', trigger: 'change' }]
})
const getInforList = async () => {
    const row = await getReviewConfiguration(route.query.id)
    reviewAllocationOptions.value = row
}
// 提交
const resultList = (data) => {
    // 处理 panelList 转换：将数组格式转换成对象数组格式
    const processPanelList = (item: any) => {
        if (item.panelList && Array.isArray(item.panelList)) {
            item.panelList = (item.panelList || [])
                .map((panelItem: any) => {
                    let correspondingObj = reviewerOptions.value.find(
                        (obj: any) => obj.userId === panelItem
                    )
                    if (correspondingObj) {
                        return {
                            ratingId: panelItem,
                            ratingName: correspondingObj.fullname,
                            ratingAccount: correspondingObj.account
                        }
                    }
                    if (panelItem && typeof panelItem === 'object') {
                        const { id, ...rest } = panelItem
                        return rest
                    }
                    return panelItem
                })
                .filter(Boolean)
        }
    }

    let list = data.reduce((acc, { children, id, ...parent }) => {
        // 处理父项的 panelList
        processPanelList(parent)

        const key = parent.classificationName
        acc[key] = acc[key] || []
        acc[key].push(parent)

        if (children) {
            // 处理子项的 panelList
            const processedChildren = children.map(({ id, ...child }) => {
                processPanelList(child)
                return child
            })
            acc[key].push(...processedChildren)
        }

        return acc
    }, {})
    return list
}

function submitObject() {
    addEditFormRef.value?.validate(async (valid: any, object: any) => {
        if (!valid) {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        } else {
            try {
                loadingBtn.value = true
                let params = {
                    moduleCode: 12,
                    ...props.formDataValue,
                    reviewRatingDetails2Map: resultList(addEditForm.value.reviewRatingDetails2Map)
                }
                const { state } = await dataSubmitOtherInfo(params)
                if (state) {
                    const subData = await audit({
                        supplierEnterpriseId: props.formDataValue.id,
                        status: 2,
                        approvalResult: 1
                    })

                    if (subData.state) {
                        ElMessage.success('审核成功')
                        closePage()
                        router.push({ name: 'BasicInformationAudit' })
                    }
                }
            } finally {
                loadingBtn.value = false
            }
        }
    })
}

// ==================== 评审分配相关 ====================
const reviewTableRef = ref()
const selectedRows = ref<any[]>([])
const isShowReviewerDialog = ref<boolean>(false)

const reviewerOptions = ref<ReviewerOption[]>([])

// 改变评价体系
const changeLocation = (val) => {
    addEditForm.value.reviewRatingDetails2Map = Object.entries(
        reviewAllocationOptions.value.filter((item, i) => {
            return val == item.id
        })[0].detailsMap
    ).map(([key, items]) => {
        const parent = items[0]
        const children = items.slice(1).map((child) => ({
            ...child,
            isParent: false
        }))

        return {
            ...parent,
            isParent: true,
            children: children
        }
    })
}
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
}

const assignReviewers = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要分配评分人的项目')
        return
    }
    isShowReviewerDialog.value = true
}

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

    // 清空选中行的评分人
    selectedRows.value.forEach((row) => {
        row.panelList = []
    })

    ElMessage.success(`已清空${selectedRows.value.length}个项目的评分人`)
}

const handleReviewerSuccess = (reviewers: object) => {
    selectedRows.value.forEach((row) => {
        row.panelList = reviewers.ratingId
    })
    ElMessage.success('评分人分配成功')
}

const emit = defineEmits(['update:isShowAdd', 'divideSuccess'])
const userDetail = ref({})
// 获取评分人
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 changeRatingName = (row: ScoreItem) => {
    // reviewerOptions.value.forEach((item: any) => {
    //     if (item.userId === row.ratingId) {
    //         row.ratingName = item.fullname
    //         row.ratingAccount = item.account
    //         row.ratingId = item.userId
    //     }
    // })
}
onMounted(() => {
    const storedData = localStorage.getItem('user')
    if (storedData) {
        userDetail.value = JSON.parse(storedData)
    }
    getReviewerOptions()
})

const openPage = () => {
    getInforList()
}

const closePage = () => {
    addEditForm.value.reviewAllocation = ''
    addEditForm.value.reviewRatingDetails2Map = []
    addEditFormRef.value?.resetFields()
    dialogVisible.value = false
}

// 3. 使用 computed 定义双向绑定
const dialogVisible = computed({
    get() {
        return props.isShowAdd
    },
    set(val) {
        emit('update:isShowAdd', false)
    }
})
</script>

<style lang="scss" scoped>
.table-container {
    max-height: 65vh;
    overflow-y: auto;
    padding-bottom: 1px;
    margin-bottom: 20px;
}

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

// 隐藏树形表格的缩进
:deep(.el-table__indent) {
    display: none !important;
}
</style>
