<template>
    <div class="layer" v-drag="layer.show">
        <el-dialog v-model="layer.show" :title="layer.title" :width="layer.width" :top="layer.top" center
            :before-close="close">
            <el-scrollbar :height="layer.height">
                <div v-if="!layer.disabled" style="display: flex; justify-content: flex-end;">
                    <el-button style="margin-right: 50px;" v-if="configFormList.configList.length === 0"
                        class="button-item" type="primary" @click="addItem">
                        添加
                    </el-button>
                </div>
                <div style="display: flex; align-items: center;margin: 20px 0px;">
                    配置名称：
                    <el-input style="width: 400px; margin-left: 10px;" v-model="configFormList.templateName"
                        placeholder="请输入配置名称" clearable />
                </div>
                <div style="display: flex; align-items: center;margin: 20px 0px;">
                    配置编号：
                    <el-input style="width: 400px; margin-left: 10px;" v-model="configFormList.templateCode"
                        placeholder="请输入配置编号" clearable />
                </div>
                <div style="display: flex; align-items: start;margin: 20px 0px;">
                    配置内容：
                    <el-card style="width: 400px;margin-left: 10px;" shadow="always">
                        <div>
                            <div v-for="(text, index) in conditionTexts" :key="text + index"
                                style="display: flex;margin-bottom: 5px;">
                                <span>{{ text }}</span>
                            </div>
                            <div v-if="conditionTexts.length === 0" style="color: #999;">暂无内容</div>
                        </div>
                    </el-card>
                </div>
                <div style="display: flex; align-items: center;margin: 20px 0px;">
                    条件范围：
                    <el-radio-group style="margin-left: 15px" v-model="configFormList.allSatisfy">
                       <el-radio label="1" >全部满足</el-radio>
                       <el-radio label="2" >满足一条即可</el-radio>
                    </el-radio-group>
                </div>
                <div style="display: flex; align-items: center;margin: 20px 0px;">
                    业务节点：
                    <el-select :disabled="layer.disabled" v-model="configFormList.effectNode"
                        placeholder="请选择" filterable   @change="handleEffectNode(configFormList.effectNode)">
                            <el-option v-for=" item in getOptions('effect_node')" :key="item.label"
                               :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </div>
                <h3 style="margin-top: 20px;">配置列表</h3>

                <div class="flex mt-2" v-for="(item, index) in configFormList.configList" :key="`${item}_${index}`">
                    <div style="display: flex;width: 100%;align-items: center;">
                        <div class="title" style="width: 60px;">配置项{{ index + 1 }}</div>
                        <el-select :disabled="layer.disabled" v-model="item.fieldName"
                            :ref="el => { if (el) configInputRefs[index] = el }" style="width: 180px;margin: 0 10px;"
                            placeholder="请选择" filterable :class="{ 'is-error': item.error_fieldName }"
                            @change="clearFieldError(index, 'fieldName')">
                            <el-option v-for="(typeCode,typeIndex) in  configOptions" :key="`${typeCode.fieldName}_${typeIndex}`"
                                :label="typeCode.fieldDesc" :value="typeCode.fieldName"></el-option>
                        </el-select>


                        <el-select :disabled="layer.disabled" v-model="item.configType"
                            :class="{ 'is-error': item.error_configType }"
                            @change="handleTypeOne(index,item.configType)" style="width: 140px;margin: 0 10px;"
                            placeholder="请选择" filterable>
                            <el-option label="输入框" value="1"></el-option>
                            <el-option label="选择框" value="2"></el-option>
                            <el-option label="日期" value="3"></el-option>
                        </el-select>

                        <el-select :disabled="layer.disabled" v-model="item.multy"
                            @change="handleTypeTwo(index,item.configType,item.multy)"
                            style="width: 140px;margin: 0 10px;" placeholder="请选择" filterable>
                            <template v-if="item.configType === '2' || item.configType === '3'">
                                <el-option v-for="option in getOptions('multy').slice(0,2)" :key="option.label"
                                    :label="option.label" :value="option.value"></el-option>
                            </template>
                            <el-option v-else v-for="option in getOptions('multy')" :key="option.label" :label="option.label"
                                :value="option.value"></el-option>
                        </el-select>


                        <!-- 输入框 -->
                        <template v-if="item.configType === '1'">
                            <!-- 比较 -->
                            <el-input v-if="item.multy === 1" style="width: 240px;" v-model="item.configVal"
                                placeholder="如: 100-500" :class="{ 'is-error': item.error_configVal }"
                                @input="clearFieldError(index, 'configVal')">
                                <template #prepend>
                                    <span>区间</span>
                                </template>
                                <template #append>
                                    <span>值</span>
                                </template>
                            </el-input>


                            <el-input v-else style="width: 240px;margin: 0 10px;" v-model="item.configVal"
                                placeholder="请输入" clearable :class="{ 'is-error': item.error_configVal }"
                                @input="clearFieldError(index, 'configVal')" />

                        </template>

                        <!-- 选择框 -->
                        <template v-else-if="item.configType === '2'">
                            <el-select :multiple="item.multy === 1" v-model="item.configVal" placeholder="请选择"
                                style="width: 240px" :class="{ 'is-error': item.error_configVal }"
                                @input="clearFieldError(index, 'configVal')">
                                <el-option v-for="option in getOptions(camelToSnake(item.fieldName))"
                                    :key="option.label" :label="option.label" :value="option.value"></el-option>
                            </el-select>
                        </template>

                        <!-- 日期 -->
                        <template v-else-if="item.configType === '3'">
                            <div style="max-width: 240px !important;">
                                <el-date-picker v-if="item.multy === 2" v-model="item.configVal" type="date"
                                    placeholder="请选择" :class="{ 'is-error': item.error_configVal }"
                                    @input="clearFieldError(index, 'configVal')" />

                                <el-date-picker v-else v-model="item.configVal" type="daterange"
                                    start-placeholder="开始日期" end-placeholder="结束日期"
                                    :class="{ 'is-error': item.error_configVal }"
                                    @input="clearFieldError(index, 'configVal')" />
                            </div>
                        </template>
                    
                    </div>
                    <template v-if="!layer.disabled">
                        <el-button v-if="configFormList.configList.length === index + 1" class="button-item"
                            type="primary" @click="addItem">
                            添加
                        </el-button>
                        <el-button class="button-item" type="danger" @click="removeItem(index)">删除</el-button>
                    </template>
                </div>
            </el-scrollbar>
            <template #footer v-if="layer.showButton">
                <div>
                    <el-button type="primary" @click="confirm">确认</el-button>
                    <el-button class="default-but" @click="close">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
    import { onBeforeMount, ref, nextTick, reactive, onMounted, watch, computed, watchEffect } from "vue";
    import { useGetDictList } from '@/hooks/useGetDictList.js'
    import drag from '@/directive/drag/index'
    import { camelToSnake } from '@/utils/index.js'
    import { ElMessage } from 'element-plus'
    import { riskTemplateView, riskGetByNode } from '@/api/riskModule.js'

    const props = defineProps({
        layer: {
            type: Object,
            default: () => ({
                show: false,
                title: '',
                showButton: false,
                width: 880,
                top: '8vh',
                height: '70vh',
                optionsData: [], //选择项1数据
                disabled: false, //禁用选择框
                templateId: '', //编辑模板ID
            }),
            required: true
        }
    })

    const emit = defineEmits(['confirm', 'close'])

    const confirm = () => {
        if (configFormList.value.templateName === '') {
            ElMessage.error('请输入模板名称')
            return
        }
        if (configFormList.value.templateCode === '') {
            ElMessage.error('请输入模板编号')
            return
        }

        configFormList.value.templateContent = conditionTexts.value.join('\n')

        setTimeout(() => {
            console.log('风控配置提交数据：', configFormList.value)

            const errorMsg = validateConfigList(configFormList.value.configList);
            if (!errorMsg) return;

            // 调用提交接口
            emit('confirm', configFormList.value, props.layer.disabled)
            close()
        })
    }

    const close = () => {
        props.layer.show = false
        emit('close')
        // 重置数据
        configFormList.value = {
            appId: null,
            channelId: null,
            createTime: null,
            createUserId: null,
            enabled: null,
            allSatisfy: null,
            templateCode: '', //风控配置模板编号
            templateContent: '', //风控配置模板内容
            templateId: '',//风控配置模板ID
            templateName: '', //风控配置模板名称
            updateTime: null,
            updateUserId: null,
            configList: [{
                configId: null,
                configType: null,
                configVal: null,
                dictList: null,
                fieldDesc: null,
                fieldName: null,
                multy: null,
            }]
        }
    }

    function scrollToError(index) {
        // 获取组件 DOM 元素
        const el = configInputRefs.value[index]?.$el;

        if (el && el.scrollIntoView) {
            el.scrollIntoView({ behavior: 'smooth', block: 'center' });
            el.focus?.(); // 如果是输入框也尝试聚焦
        }
    }

    function markFieldError(index, key) {
        configFormList.value.configList[index][`error_${key}`] = true;
    }

    function clearFieldError(index, key) {
        configFormList.value.configList[index][`error_${key}`] = false;
    }

    function validateConfigList(list) {
        for (let i = 0; i < list.length; i++) {
            const item = list[i];

            if (!item.fieldName) {
                markFieldError(i, 'fieldName');
                scrollToError(i);
                ElMessage.error(`第 ${i + 1} 条配置的「字段名」不能为空`);
                return false;
            }

            if (!item.configType && item.configType !== '0') {
                markFieldError(i, 'configType');
                scrollToError(i);
                ElMessage.error(`第 ${i + 1} 条配置的「配置类型」不能为空`);
                return false;
            }

            if (!item.multy && item.multy !== 0) {
                markFieldError(i, 'multy');
                scrollToError(i);
                ElMessage.error(`第 ${i + 1} 条配置的「配置方式」不能为空`);
                return false;
            }

            if (
                item.configVal === undefined ||
                item.configVal === null ||
                item.configVal === ''
            ) {
                markFieldError(i, 'configVal');
                scrollToError(i);
                ElMessage.error(`第 ${i + 1} 条配置的「配置值」不能为空`);
                return false;
            }
        }

        return true;
    }

    const { loadDictData, getOptions, getDictionaryName } = useGetDictList();

    // 配置数据
    const configFormList = ref({
        appId: null,
        channelId: null,
        createTime: null,
        createUserId: null,
        enabled: null,
        allSatisfy: null,
        effectNode: null,
        templateCode: '', //风控配置模板编号
        templateContent: '', //风控配置模板内容
        templateId: '',//风控配置模板ID
        templateName: '', //风控配置模板名称
        updateTime: null,
        updateUserId: null,
        configList: [{
            configId: null,
            configType: null,
            configVal: null,
            dictList: null,
            fieldDesc: null,
            fieldName: null,
            multy: null,
        }]
    })

    const configInputRefs = ref([]);

    // 添加配置
    const addItem = () => {
        let config = {
            configId: null,
            configType: null,
            configVal: null,
            dictList: null,
            fieldDesc: null,
            fieldName: null,
            multy: null,
        }
        configFormList.value.configList.push(config)

        nextTick(() => {
            const lastIndex = configFormList.value.configList.length - 1;
            const inputEl = configInputRefs.value[lastIndex];
            if (inputEl && inputEl.focus) {
                inputEl.focus?.();
                // 延时 scrollIntoView，避免未完全渲染时滚动失败
                setTimeout(() => {
                    if (inputEl.$el?.scrollIntoView) {
                        inputEl.$el.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }
                }, 50);
            }
        });
    }

    // 删除配置
    const removeItem = (index) => {
        configFormList.value.configList.splice(index, 1)
        configInputRefs.value.splice(index, 1)  //清空已删除项的 ref
    }

    // 输入类型检测
    const handleTypeOne = (index, configType) => {
        console.log('选择1变化:', 'index', index, 'configType', configType)
        // configType：1-输入框 2-选择框 3-日期
        // multy：1-多选 2-单选 3-大于> 4-小于<

        configFormList.value.configList[index][`error_configType`] = false;

        if (configType === '1') {
            configFormList.value.configList[index].multy = 2
            configFormList.value.configList[index].configVal = ''
        } else if (configType === '2' || configType === '3') {
            configFormList.value.configList[index].multy = 2
            configFormList.value.configList[index].configVal = ''
        }
        console.log('1-handleTypeOne-configVal', configFormList.value.configList[index].configVal)
    }

    // 输入类型检测
    const handleTypeTwo = (index, configType, multy) => {
        console.log('选择2变化:', 'index', index, 'configType', configType, 'multy', multy)
        // configType：1-输入框 2-选择框 3-日期
        // multy：1-多选 2-单选 3-大于> 4-小于<

        if (configType === '3' && multy === 1 || configType === '2' && multy === 1) {
            configFormList.value.configList[index].configVal = []
        } else {
            configFormList.value.configList[index].configVal = ''
        }
        console.log('2-handleTypeTwo-configVal', configFormList.value.configList[index].configVal)
    }

    // 配置项1列表options
    const configOptions = ref([])
    // 业务节点
    const handleEffectNode = async(val) =>{
        let res = await riskGetByNode({effectNode: val})
        configOptions.value = res.data
        // 切换时重置配置列表
        let config = {
            configId: null,
            configType: null,
            configVal: null,
            dictList: null,
            fieldDesc: null,
            fieldName: null,
            multy: null,
        }
        configFormList.value.configList = []
        configFormList.value.configList.push(config)
    }


    // #region 配置内容逻辑

    // 获取配置名称
    const getFieldDesc = (fieldName) => {
        const item =  configOptions.value.find(i => i.fieldName === fieldName);
        return item ? item.fieldDesc : '';
    };

    // element plus 时间组件转化为 2025-05-01
    function formatDateToYMD(dateStr) {
        if (dateStr) {
            const date = new Date(dateStr);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        } else {
            return
        }
    }

    // 核心：生成每条文本描述
    const conditionTexts = computed(() => {
        return configFormList.value.configList.map(item => {
            const fieldDesc = getFieldDesc(item.fieldName)
            let valueText = ''

            // 选择框
            if (item.configType === '2') {
                const typeCode = camelToSnake(item.fieldName)
                if (item.multy === 2) {
                    // 单选
                    valueText = getDictionaryName(typeCode, item.configVal)
                } else if (item.multy === 1) {
                    // 多选
                    // valueText = item.configVal.map((v) => getDictionaryName(typeCode, v)).join('、')
                    valueText = Array.isArray(item.configVal)
                        ? item.configVal.map(v => getDictionaryName(typeCode, v)).join('、')
                        : String(item.configVal || '')
                            .split(',')
                            .map(v => getDictionaryName(typeCode, v))
                            .join('、')
                }
            }

            // 日期
            else if (item.configType === '3') {
                if (item.multy === 2) {
                    valueText = formatDateToYMD(item.configVal)
                } else if (item.multy === 1) {
                    if (item.configVal[0] || item.configVal[1]) {
                        valueText = `${formatDateToYMD(item.configVal[0])}到${formatDateToYMD(item.configVal[1])}`
                    } else {
                        return ''
                    }
                }
            }

            // 输入框
            else {
                if (item.multy === 1) {
                    if (item.configVal) {
                        const [min, max] = item.configVal.split('-').map(Number)
                        valueText = `${min}到${max}`
                    } else {
                        return ''
                    }
                } else {
                    valueText = item.configVal
                }
            }
            if (fieldDesc && valueText && valueText.length > 0) {
                // getOptions('multy')[item.multy - 1].label
                // item.fieldDesc = `${fieldDesc}为${getOptions('multy')[item.multy - 1].label}${valueText}`
                // return `${fieldDesc}为${getOptions('multy')[item.multy - 1].label}${valueText}`

               /*  let multyList = ['','','>','<']
                item.fieldDesc = `${fieldDesc}为${multyList[item.multy - 1]}${valueText}`
                return `${fieldDesc}为${multyList[item.multy - 1]}${valueText}` */
                let result = fillOrAppend(fieldDesc,[valueText],item.multy)
                item.fieldDesc = result
                return result
            } else {
                return ''
            }
        })
    })

    /**
     * 生成配置内容
     * @param { string } template 配置文字
     * @param  values 配置值
     * @param  multy 比较值
     */
    function fillOrAppend(template, values, multy) {
        let hasPlaceholder = template.includes('?');
        let multyList = ['','','>','<']
        if (hasPlaceholder) {
            let i = 0;
            return template.replace(/\?/g, () => values ?? '?');
        } else {
            return `${template}为${multyList[multy - 1]}${values}`;
        }
    }

    // #endregion

    const gettemplateData = async (templateId) => {
        configFormList.value.configList = []
        let res = await riskTemplateView({ templateId })
        if (res.code == 200) {
            res = res.data
            configFormList.value = res
            configFormList.value.allSatisfy = String(res.allSatisfy)
            res.configList.forEach((item, index) => {
                // configType：1-输入框 2-选择框 3-日期
                // multy：1-多选 2-单选 3-大于> 4-小于<

                if (item.configType === 2) {
                    if (item.multy === 2) {
                        item.configVal = Number(item.configVal)
                    } else {
                        item.configVal = item.configVal.split(',').map(Number)
                    }
                } else if (item.configType === 3 && item.multy === 1) {
                    item.configVal = item.configVal.split(',');
                }

                configFormList.value.configList[index].configType = String(item.configType)
                configFormList.value.configList[index].multy = item.multy
                configFormList.value.configList[index].configVal = item.configVal
            })

            console.log('编辑时回显数据：', configFormList.value)
        }
    }

    // 使用 watch 自动修正 ref 列表长度
    watch(() => configFormList.value.configList.length, (newLength) => {
        configInputRefs.value.length = newLength;
    });
  
    // 编辑时获取回显数据
    watch(() => props.layer.show, async(val) => {
        configOptions.value = [] //重置选项列表
        if (val && props.layer.disabled && props.layer.templateId) {
            console.log('templateId', props.layer.templateId)
            await gettemplateData(props.layer.templateId)
            let res = await riskGetByNode({effectNode: configFormList.value.effectNode})
            configOptions.value = res.data
        }
    })

    onMounted(async () => {
        await loadDictData()
    })
</script>

<script>
    // 单独导出指令以便模板使用
    export default {
        directives: { drag }
    }
</script>

<style lang="scss" scoped>
    :deep(.el-dialog--center) {
        min-width: 55vw;
    }

    :deep(.el-dialog__body) {
        max-height: 60vh;
        overflow: auto;
    }

    :deep() {

        .el-select.is-error .el-input__wrapper,
        .el-input.is-error .el-input__wrapper,
        .el-date-editor.is-error {
            border-color: red !important;
            box-shadow: 0 0 0 1px red !important;
        }
    }
    :deep() {
        .default-but,
        .el-dialog,
        .el-card,
        .el-dialog__title,
        .el-input__wrapper,
        .el-textarea__inner{
            background-color: var(--system-page-background) !important;
            color: var(--system-page-color) !important;
            border-color: var(--system-page-border-color) !important;
        }
    }
</style>