<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"
                    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 :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>
                                            <span class="required-asterisk">*</span>
                                            供方基本情况调查内容
                                        </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' ? 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
                                                placeholder="请选择"
                                                v-model="addEditForm.gategoryNames"
                                                :readonly="true"
                                                @click="materialChange()"
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item
                                        :span="2"
                                        v-if="addEditForm.requiredQualification.includes('3')"
                                    >
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            必填资质
                                        </template>
                                        <el-form-item prop="btzzName">
                                            <el-input
                                                placeholder="请选择"
                                                v-model="addEditForm.btzzName"
                                                :readonly="true"
                                                @click="qualificationChange(1)"
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item
                                        :span="2"
                                        v-if="addEditForm.requiredQualification.includes('3')"
                                    >
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            选填资质
                                        </template>
                                        <el-form-item prop="fbtzzName">
                                            <el-input
                                                placeholder="请选择"
                                                v-model="addEditForm.fbtzzName"
                                                :readonly="true"
                                                @click="qualificationChange(2)"
                                            >
                                            </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"
                                                type="textarea"
                                                :autosize="{ minRows: 4, maxRows: 6 }"
                                                placeholder="请输入"
                                                maxlength="200"
                                                show-word-limit
                                            />
                                        </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 type="primary" :loading="btnLoading" @click="handleSubmit">发布</el-button>
            <el-button @click="handleCancel">取消</el-button>
        </div>

        <!-- 物资分类 -->
        <materialDialog
            width="60%"
            height="50vh"
            v-model:isShow="materialIsShowDialog"
            :isShowTree="false"
            :isShowSelect="false"
            :selectedContent="materialSelectedContent"
            @selectedChange="materialSelectedChange"
        ></materialDialog>

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

<script setup lang="ts">
import MermaidFlow from '@/components/MermaidFlow/index.vue'
import { Document } from '@element-plus/icons-vue'
import { countdownEmits, type FormRules } from 'element-plus'
import {
    dataDetail,
    dataAdd,
    dataUpdate
} from '@/api/supplierMonitor/ConfigManagement/AccessQualificationConfig'
import listDialog from '@/views/SupplierMonitor/ConfigManagement/AccessQualificationConfig/listDialog.vue'
import materialDialog from '@/views/SupplierMonitor/ConfigManagement/AccessQualificationConfig/materialDialog.vue'
import { dictionaryEscape, 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'],
    gategoryNames: '',
    gategoryIds: [],
    flowNode: ['1', '2'],
    btzzName: '',
    fbtzzName: ''
})

// 表单验证规则
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'] }],
    fbtzzName: [{ required: true, message: '请选择选填资质', trigger: ['change', 'blur'] }]
})

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.gategoryNames = addEditForm.gategoryNameList
    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(',')
    selectedContent2.value = addEditForm.qualificationMap.unnecessary.map((item: any) => {
        return {
            ...item,
            id: item.qualificationCategoryId
        }
    })
    addEditForm.fbtzzName = addEditForm.qualificationMap.unnecessary
        .map((item: any) => item.qualificationCategoryName)
        .join(',')
}

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

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

const qualificationChange = (type: number) => {
    qualificationType.value = type
    const config = qualificationConfig[type as keyof typeof qualificationConfig]
    selectedContent.value = config ? config.selectedRef.value : []
    console.log(selectedContent.value, 'selectedContent.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 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'
                            })
                        ),
                        unnecessary: qualificationConfig[2].selectedRef.value.map(
                            ({ id: qualificationCategoryId, ...rest }) => ({
                                ...rest,
                                qualificationCategoryId,
                                required: 'unnecessary'
                            })
                        )
                    }
                }
                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>
.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>
