<template>
    <super-dialog
        v-model="dialogVisible"
        :title="title"
        custom-class="notification-dialog"
        top="10vh"
        width="60%"
        @closed="closePage"
    >
        <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"
                                                clearable
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in reviewAllocationOptions"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </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.reviewTableData"
                                    border
                                    stripe
                                    @selection-change="handleSelectionChange"
                                >
                                    <el-table-column align="center" type="selection" width="55" />
                                    <el-table-column
                                        align="center"
                                        label="序号"
                                        prop="index"
                                        width="80"
                                    />
                                    <el-table-column
                                        align="center"
                                        label="类别"
                                        prop="category"
                                        width="120"
                                    />
                                    <el-table-column
                                        label="评审内容"
                                        min-width="300"
                                        prop="content"
                                    />
                                    <el-table-column align="center" label="评审人" width="200">
                                        <template #default="{ row }">
                                            <el-cascader
                                                v-model="row.reviewers"
                                                :options="reviewerOptions"
                                                :props="cascaderProps"
                                                clearable
                                                collapse-tags
                                                collapse-tags-tooltip
                                                placeholder="请选择"
                                                style="width: 100%"
                                            />
                                        </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 type="primary" @click="submitObject">确定</el-button>
            <el-button @click="closePage">取消</el-button>
        </div>

        <!-- 批量评审人 -->
        <reviewer-dialog
            ref="rejectDialogRef"
            v-model:isShowAdd="isShowReviewerDialog"
            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'

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

const props = defineProps({
    isShowAdd: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: ''
    },
    info: {
        type: Object,
        default: () => ({})
    }
})

// ==================== 表单相关 ====================
const activeCollapse = ref<string[]>(['review-allocation'])

const reviewAllocationOptions = ref([
    { value: '评价体系1', label: '评价体系1' },
    { value: '评价体系2', label: '评价体系2' },
    { value: '评价体系3', label: '评价体系3' }
])

const detailLoading = ref<Boolean>(false)

const addEditFormRef = ref<any>(null)

const addEditForm = ref<any>({
    reviewAllocation: '',
    reviewTableData: [
        {
            index: 1,
            category: '工厂生产现场',
            content: '工厂是否整洁?是否按5S标准管理现场?(2分)',
            reviewers: []
        },
        { index: 2, category: '', content: '原材料堆放是否合理,标识清晰,(2分)', reviewers: [] },
        {
            index: 3,
            category: '',
            content: '生产设备是否正常运转,维护记录完整,(2分)',
            reviewers: []
        },
        { index: 4, category: '', content: '生产过程是否按工艺要求执行,(2分)', reviewers: [] },
        {
            index: 5,
            category: '管理体系',
            content: '是否有完善的质量管理体系文件,(3分)',
            reviewers: []
        },
        { index: 6, category: '', content: '是否有内审制度并定期执行,(3分)', reviewers: [] },
        { index: 7, category: '', content: '是否有纠正预防措施程序,(3分)', reviewers: [] },
        { index: 8, category: '质量管理', content: '是否有来料检验制度,(2分)', reviewers: [] }
    ]
})

const addEditFormRules = ref<any>({
    reviewAllocation: [{ required: true, message: '请选择评价体系', trigger: 'change' }]
})

function submitObject() {
    addEditFormRef.value?.validate((valid: any, object: any) => {
        if (!valid) {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        } else {
            emit('divideSuccess')
            closePage()
        }
    })
}

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

const reviewerOptions = ref<ReviewerOption[]>([
    {
        value: 'dept1',
        label: '质量部',
        children: [
            { value: 'user1', label: '张三' },
            { value: 'user2', label: '李四' },
            { value: 'user3', label: '王五' }
        ]
    },
    {
        value: 'dept2',
        label: '技术部',
        children: [
            { value: 'user4', label: '赵六' },
            { value: 'user5', label: '钱七' },
            { value: 'user6', label: '孙八' }
        ]
    }
])

const cascaderProps = {
    emitPath: false,
    value: 'value',
    label: 'label',
    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.reviewers = []
    })

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

const handleReviewerSuccess = (reviewers: string) => {
    // 这里可以将评审人信息保存到 selectedRows.value 中
    selectedRows.value.forEach((row) => {
        row.reviewers = reviewers
    })
    ElMessage.success('评审人分配成功')
}

const emit = defineEmits(['update:isShowAdd', 'divideSuccess'])

onMounted(() => {})

const openPage = () => {
    // loadData()
}

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

defineExpose({
    openPage
})

// 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: 10px 0 10px 10px;
}
</style>
