<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <el-form
                    ref="addEditFormRef"
                    :model="addEditForm"
                    :rules="addEditFormRules"
                    label-position="left"
                    label-suffix="："
                    size="large"
                >
                    <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 :span="2">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            供方基本情况调查表名称
                                        </template>
                                        <el-form-item prop="name">
                                            <el-input
                                                v-model="addEditForm.name"
                                                placeholder="请输入"
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label>
                                            <div style="display: flex; align-items: center">
                                                <span class="required-asterisk">*</span>
                                                供方基本情况调查内容
                                                <el-popover
                                                    :width="200"
                                                    placement="right"
                                                    trigger="hover"
                                                >
                                                    <template #reference>
                                                        <el-icon
                                                            :size="16"
                                                            style="
                                                                margin-left: 2px;
                                                                cursor: pointer;
                                                            "
                                                        >
                                                            <QuestionFilled color="#f90" />
                                                        </el-icon>
                                                    </template>
                                                    <div>供应商填写的基本情况调查表</div>
                                                    <el-divider style="margin: 6px 0"></el-divider>
                                                    <div
                                                        style="color: #409eff; cursor: pointer"
                                                        @click="previewBasicInfo()"
                                                    >
                                                        预览>>
                                                    </div>
                                                </el-popover>
                                            </div>
                                        </template>
                                        <el-form-item prop="requiredQualification">
                                            <el-checkbox-group
                                                v-model="addEditForm.requiredQualification"
                                            >
                                                <el-checkbox
                                                    v-for="item in getDictionaryByCode(
                                                        'gfjbqkdcnrbm'
                                                    )"
                                                    :key="item.value"
                                                    :disabled="
                                                        item.value === '1' || item.value === '2'
                                                            ? true
                                                            : false
                                                    "
                                                    :label="item.name"
                                                    :value="item.value"
                                                ></el-checkbox>
                                            </el-checkbox-group>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            物资分类
                                        </template>
                                        <el-form-item prop="gategoryNames">
                                            <el-input
                                                v-model="addEditForm.gategoryNames"
                                                :readonly="true"
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 6 }"
                                                placeholder="请选择"
                                                @click="materialChange()"
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item
                                        v-if="addEditForm.requiredQualification.includes('4')"
                                        :span="2"
                                    >
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            准入资质
                                        </template>
                                        <el-form-item prop="btzzName">
                                            <el-input
                                                v-model="addEditForm.btzzName"
                                                :readonly="true"
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 6 }"
                                                placeholder="请选择"
                                                @click="qualificationChange(1)"
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label> 备注</template>
                                        <el-form-item prop="desc">
                                            <el-input
                                                v-model="addEditForm.desc"
                                                :autosize="{ minRows: 4, maxRows: 6 }"
                                                maxlength="200"
                                                placeholder="请输入"
                                                show-word-limit
                                                type="textarea"
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            启用/禁用
                                        </template>
                                        <el-form-item prop="status">
                                            <el-switch
                                                v-model="addEditForm.status"
                                                active-text="启用"
                                                active-value="1"
                                                inactive-text="禁用"
                                                inactive-value="0"
                                                inline-prompt
                                                style="
                                                    --el-switch-on-color: #13ce66;
                                                    --el-switch-off-color: #ff4949;
                                                "
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </el-collapse-item>
                        <el-collapse-item name="flow-node-config">
                            <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> 流程节点选择</template>
                                        <el-form-item prop="flowNode">
                                            <el-checkbox-group v-model="addEditForm.flowNode">
                                                <el-checkbox
                                                    v-for="item in flowNodeList"
                                                    :key="item.id"
                                                    :label="item.name"
                                                    :value="item.id"
                                                ></el-checkbox>
                                            </el-checkbox-group>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label> 流程预览</template>
                                        <div class="flow-preview">
                                            <MermaidFlow :flowNodes="addEditForm.flowNode" />
                                        </div>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </el-form>
            </div>
        </div>

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

        <!-- 物资分类 -->
        <materialsDialog
            ref="dialogRef"
            v-model:isShowAdd="materialIsShowDialog"
            :selectedContent="materialSelectedContent"
            title="物资分类"
            @submit="materialSelectedChange"
        ></materialsDialog>

        <!-- 资质分类 -->
        <listDialog
            v-model:isShow="isShowDialog"
            :isShowSelect="false"
            :isShowTree="false"
            :selectedContent="selectedContent"
            height="50vh"
            width="60%"
            @selectedChange="selectedChange"
        ></listDialog>

        <!-- 预览弹窗 -->
        <previewInfo
            ref="dialogRef"
            v-model:isShowAdd="previewDialog"
            :selectedContent="addEditForm.requiredQualification"
            title="基本情况调查表"
        ></previewInfo>
    </div>
</template>

<script lang="ts" setup>
import MermaidFlow from '@/components/MermaidFlow/index.vue'
import { Document } from '@element-plus/icons-vue'
import { type FormRules } from 'element-plus'
import {
    dataAdd,
    dataDetail,
    dataUpdate
} from '@/api/supplierMonitor/ConfigManagement/AccessQualificationConfig'
import listDialog from '@/views/SupplierMonitor/QualificationAudit/AccessQualificationConfig/listDialog.vue'
import materialsDialog from '@/views/SupplierMonitor/QualificationAudit/AccessQualificationConfig/materialsDialog.vue'
import previewInfo from '@/views/SupplierMonitor/QualificationAudit/AccessQualificationConfig/previewInfo.vue'
import { getDictionaryByCode } from '@/utils/dictionary'

interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

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

// 表单相关
const addEditFormRef = ref()
const detailLoading = ref(false)
const btnLoading = ref(false)
const activeCollapse = ref(['basic-info', 'flow-node-config'])

// 编辑相关
const isShowDialog = ref(false)
const materialIsShowDialog = ref(false)

// 表单数据
const flowNodeList = ref([
    { id: '1', name: '现场评审' },
    { id: '2', name: '样品试用' }
])

const addEditForm = reactive<AddEditForm>({
    requiredQualification: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'],
    gategoryNames: '',
    gategoryIds: [],
    flowNode: ['1', '2'],
    btzzName: '',
    status: '1'
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入供方基本情况调查表名称', trigger: 'blur' }],
    requiredQualification: [
        { required: true, message: '请选择供方基本情况调查内容', trigger: 'change' }
    ],
    gategoryNames: [{ required: true, message: '请选择物资分类', trigger: ['change', 'blur'] }],
    btzzName: [{ required: true, message: '请选择必填资质', trigger: ['change', 'blur'] }],
    status: [{ required: true, message: '请选择启用/禁用', trigger: 'change' }]
})

const getDetail = async (id: string) => {
    // 获取详情逻辑
    const { ...rest } = (await dataDetail(id)) as AddEditForm
    Object.assign(addEditForm, {
        ...rest
    })
    materialSelectedContent.value = addEditForm.gategoryIds.map((item, index) => ({
        id: item.id || item, // 自动处理对象和原始值
        catName: addEditForm.gategoryNameList[index] || ''
    }))
    addEditForm.flowNode = getKeysFromValue(addEditForm.process.code)
    addEditForm.requiredQualification = addEditForm.basic.code.split(',')
    selectedContent1.value = addEditForm.qualificationMap.required.map((item: any) => {
        return {
            ...item,
            id: item.qualificationCategoryId
        }
    })
    addEditForm.btzzName = addEditForm.qualificationMap.required
        .map((item: any) => item.qualificationCategoryName)
        .join(',')
}

//弹窗
const qualificationType = ref()
const selectedContent = ref([])
const selectedContent1 = ref([])
const materialSelectedContent = ref([])

const qualificationConfig = {
    1: { formKey: 'btzz', selectedRef: selectedContent1 }
}

const qualificationChange = (type: number) => {
    qualificationType.value = type
    const config = qualificationConfig[type as keyof typeof qualificationConfig]
    selectedContent.value = config ? config.selectedRef.value : []
    isShowDialog.value = true
}

const selectedChange = (data: any) => {
    const config = qualificationConfig[qualificationType.value as keyof typeof qualificationConfig]
    config.selectedRef.value = data
    if (data.length > 0) {
        addEditForm[config.formKey + 'Name'] = data
            .map((item: any) => item.qualificationCategoryName)
            .join(',')
    } else {
        addEditForm[config.formKey + 'Name'] = ''
    }
}

const materialChange = () => {
    materialIsShowDialog.value = true
}

const materialSelectedChange = (data: any) => {
    materialSelectedContent.value = data
    if (data.length > 0) {
        addEditForm.gategoryIds = data.map((item: any) => item.id)
        addEditForm.gategoryNames = data.map((item: any) => item.catName).join(',')
    } else {
        addEditForm.gategoryIds = []
        addEditForm.gategoryNames = ''
    }
}

// 预览
const previewDialog = ref(false)
const previewBasicInfo = () => {
    previewDialog.value = true
}

// 取消
const handleCancel = () => {
    router.push({ name: 'AccessQualificationConfig' })
}

// 提交
const getKeysFromValue = (valueString: any) => {
    const nodeConfig = {
        '1': '3,4,5',
        '2': '6'
    }

    const values = valueString.split(',')

    return Object.entries(nodeConfig).reduce((acc, [key, configValue]) => {
        const configValues = configValue.split(',')
        if (configValues.some((val) => values.includes(val))) {
            acc.push(key)
        }
        return acc
    }, [])
}

const getFlowNodeValue = (flowNode: any) => {
    const nodeConfig = {
        '1': '3,4,5',
        '2': '6'
    }

    const values = flowNode.map((node) => nodeConfig[node]).filter(Boolean)

    return values.join(',')
}

const handleSubmit = () => {
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                let params = {
                    ...addEditForm,
                    basic: {
                        code: addEditForm.requiredQualification.join(','),
                        name: addEditForm.name
                    },
                    name: addEditForm.name,
                    desc: addEditForm.desc,
                    gategoryIds: addEditForm.gategoryIds,
                    gategoryNames: addEditForm.gategoryNames,
                    process: {
                        code: getFlowNodeValue(addEditForm.flowNode)
                    },
                    qualificationMap: {
                        required: qualificationConfig[1].selectedRef.value.map(
                            ({ id: qualificationCategoryId, ...rest }) => ({
                                ...rest,
                                qualificationCategoryId,
                                required: 'required'
                            })
                        )
                    }
                }
                const { state } = addEditForm.id ? await dataUpdate(params) : await dataAdd(params)
                if (state) {
                    ElMessage.success('发布成功')
                    handleCancel()
                }
            } finally {
                btnLoading.value = false
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

onMounted(() => {
    // 如果是编辑模式，获取详情数据
    if (route.query.id && typeof route.query.id === 'string') {
        getDetail(route.query.id)
    }
})
</script>

<style lang="scss" scoped>
:deep(.el-divider) {
    margin: 12px 0 !important;
}

.flow-preview {
    min-height: 400px;
    width: 100%;
    background: #fafafa;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
    overflow: hidden;
}

.section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
    color: #333;
}

.required-asterisk {
    color: #f56c6c;
    margin-right: 4px;
}
</style>
