<template>
    <!-- 小型弹窗，用于完成，删除，保存等操作 -->
    <el-dialog class="l-dialog" :class="lDialog" :title="title" :visible.sync="dialogVisible" :showClose="true"
        :closeOnClickModal="false" @close="handleClose" :append-to-body="true">
        <div>
            <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px">
                <el-form-item label="IP类型" prop="ipType">
                    <el-radio
                        v-model="form.ipType"
                        v-for="item in dict.type.sys_white"
                        :key="item.value"
                        :label="item.value"
                        :disabled="isAdd === 'edit'"
                    >{{ item.label }}</el-radio>
                </el-form-item>
                <el-form-item label="单个IP地址" prop="ipAddressDes" v-if="form.ipType === 'single'" :key="'single-'+form.ipType">
                    <el-input class="form-item" v-model="form.ipAddressDes" clearable show-word-limit
                        placeholder="请输入单个IP地址" maxlength="20"></el-input>
                </el-form-item>

                <el-form-item label="IP网段起始地址" prop="ipRangeStartDes" v-if="form.ipType === 'range'" :key="'range-start-'+form.ipType">
                    <el-input class="form-item" v-model="form.ipRangeStartDes" clearable show-word-limit
                        placeholder="请输入IP网段起始地址" maxlength="20"></el-input>
                </el-form-item>

                <el-form-item label="IP网段结束地址" prop="ipRangeEndDes" v-if="form.ipType === 'range'" :key="'range-end-'+form.ipType">
                    <el-input class="form-item" v-model="form.ipRangeEndDes" clearable show-word-limit
                        placeholder="请输入IP网段结束地址" maxlength="20"></el-input>
                </el-form-item>

                <el-form-item label="时间范围">
                    <el-date-picker v-model="form.timeRange" type="datetimerange" range-separator="至"
                        start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss"
                        :default-time="['00:00:00', '23:59:59']" style="width: 100%" align="right" clearable />
                </el-form-item>


            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button class="clear-btn" @click="handleClose" :disabled="disabled">取消</el-button>
            <el-button type="primary" class="search-btn" :disabled="disabled"
                @click="submitForm('ruleForm')">确认</el-button>
        </span>
    </el-dialog>
</template>
<script>
import _ from 'lodash'
import { isIPv4, isIPv4RangeOrder } from '@/utils/validate'
import {
    addWhiteAPI,
    updateWhiteAPI,
} from '@/api/system/white'
export default {
    name: "WhiteForm",
    dicts: ['sys_white'],
    props: ["width", "dataForm", "title", "disabled", "isAdd", "rowData"],
    data() {
        return {
            lDialog: this.width > 500 ? "w700" : "w500",
            dialogVisible: true,
            isDisabled: true,
            form: {},
            loading: null,
            rules: {
                ipAddressDes: [
                    { required: true, message: '单个IP地址不能为空', trigger: 'blur' },
                    { validator: (rule, value, callback) => this.validateIpAddressDes(value, callback), trigger: 'blur' }
                ],
                ipRangeStartDes: [
                    { required: true, message: 'IP网段起始地址不能为空', trigger: 'blur' },
                    { validator: (rule, value, callback) => this.validateIpRangeStartDes(value, callback), trigger: 'blur' }
                ],
                ipRangeEndDes: [
                    { required: true, message: 'IP网段结束地址不能为空', trigger: 'blur' },
                    { validator: (rule, value, callback) => this.validateIpRangeEndDes(value, callback), trigger: 'blur' }
                ],
            },
            errorObj: {
                ipAddressDes: '单个IP地址',
                ipRangeStartDes: 'IP网段起始地址',
                ipRangeEndDes: 'IP网段结束地址',
            },
        };
    },
    created() {
        this.initFormData();
    },
    watch: {
        'form.ipType'(newVal) {
            this.$nextTick(() => {
                if (!this.$refs.ruleForm) return
                if (newVal === 'single') {
                    // 切到单个IP：清空网段字段并清除其校验
                    this.form.ipRangeStartDes = ''
                    this.form.ipRangeEndDes = ''
                    this.form.ipRangeStart = ''
                    this.form.ipRangeEnd = ''
                    // 先整体清空，再针对当前显示字段校验，避免信息串位
                    this.$refs.ruleForm.clearValidate()
                } else {
                    // 切到网段：清空单个IP字段并清除其校验
                    this.form.ipAddressDes = ''
                    this.form.ipAddress = ''
                    this.$refs.ruleForm.clearValidate()
                }
            })
        }
    },
    methods: {
        /** 初始化表单数据 */
        initFormData() {
            if (this.isAdd === 'edit' && this.rowData) {
                // 编辑模式：填充表单数据
                this.form = {
                    id: this.rowData.id,
                    ipAddressDes: this.rowData.ipAddressDes || '',
                    ipAddressDesNew: this.rowData.ipAddressDes || '',
                    ipAddress: this.rowData.ipAddress || '',
                    ipRangeStartDes: this.rowData.ipRangeStartDes || '',
                    ipRangeStartDesNew: this.rowData.ipRangeStartDes || '',
                    ipRangeStart: this.rowData.ipRangeStart || '',
                    ipRangeEndDes: this.rowData.ipRangeEndDes || '',
                    ipRangeEndDesNew: this.rowData.ipRangeEndDes || '',
                    ipRangeEnd: this.rowData.ipRangeEnd || '',
                    ipType: this.rowData.ipAddress ? 'single' : 'range',
                    timeRange: this.rowData.accessStartTime && this.rowData.accessEndTime
                        ? [this.rowData.accessStartTime, this.rowData.accessEndTime]
                        : [],
                };
            } else {
                // 新增模式：重置表单
                this.form = {
                    ipType: 'single',
                    ipAddressDes: '',
                    ipAddressDesNew: '',
                    ipAddress: '',
                    ipRangeStartDes: '',
                    ipRangeStartDesNew: '',
                    ipRangeStart: '',
                    ipRangeEndDes: '',
                    ipRangeEndDesNew: '',
                    ipRangeEnd: '',
                    timeRange: [],
                };
            }
        },
        /*关闭弹窗 */
        handleClose() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
            /* setTimeout(() => {
                this.dialogVisible = true;
            }); */
        },
        /**确认弹窗 */
        sureBtnClick() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
            /* setTimeout(() => {
                this.dialogVisible = true;
            }); */
        },
        /**重置表单*/
        reset() {
            this.form = {
                ipType: 'single',
                ipAddressDes: '',
                ipAddressDesNew: '',
                ipAddress: '',
                ipRangeStartDes: '',
                ipRangeStartDesNew: '',
                ipRangeStart: '',
                ipRangeEndDesNew: '',
                ipRangeEndDes: '',
                ipRangeEnd: '',
                timeRange: [],
            };
            this.resetForm("ruleForm");
        },
        handleReuslt(res) {
            this.$modal.msgSuccess(res.msg);
            this.reset();
            this.$emit('handleQuery');
            this.handleClose();
        },
        // 动态校验：仅在对应类型下必填
        validateIpAddressDes(value, callback) {
            if (this.form.ipType === 'single') {
                const previous = this.form.ipAddressDesNew
                // 若与原值相同则不触发校验错误，直接通过
                if (previous !== undefined && value === previous) return callback()
                if (!value) return callback(new Error('单个IP地址不能为空'))
                if (!isIPv4(value)) return callback(new Error('请输入合法的IPv4地址，如 192.168.1.1'))
            }
            callback()
        },
        validateIpRangeStartDes(value, callback) {
            if (this.form.ipType === 'range') {
                const previous = this.form.ipRangeStartDesNew
                if (previous !== undefined && value === previous) return callback()
                if (!value) return callback(new Error('IP网段起始地址不能为空'))
                if (!isIPv4(value)) return callback(new Error('请输入合法的IPv4地址，如 192.168.1.1'))
                const end = this.form.ipRangeEndDes
                if (end && isIPv4(end) && !isIPv4RangeOrder(value, end)) {
                    return callback(new Error('起始地址不能大于结束地址'))
                }
            }
            callback()
        },
        validateIpRangeEndDes(value, callback) {
            if (this.form.ipType === 'range') {
                const previous = this.form.ipRangeEndDesNew
                if (previous !== undefined && value === previous) return callback()
                if (!value) return callback(new Error('IP网段结束地址不能为空'))
                if (!isIPv4(value)) return callback(new Error('请输入合法的IPv4地址，如 192.168.1.100'))
                const start = this.form.ipRangeStartDes
                if (start && isIPv4(start) && !isIPv4RangeOrder(start, value)) {
                    return callback(new Error('结束地址不能小于起始地址'))
                }
            }
            callback()
        },
        /**验证 */
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    // 显示遮罩层
                    this.loading = this.$loading({
                        lock: true,
                        text: "数据提交中，请稍候...",
                        background: 'rgba(0,0,0,0.5)',
                        target: this.$el.querySelector('.el-dialog') || document.body
                    })
                    let params = _.cloneDeep(this.form);
                    // 映射时间范围到后端需要的字段（可按需调整字段名）
                    if (Array.isArray(params.timeRange) && params.timeRange.length === 2) {
                        params.startTime = params.timeRange[0]
                        params.endTime = params.timeRange[1]
                    } else {
                        params.startTime = ''
                        params.endTime = ''
                    }
                    // 新增时：将描述字段映射到提交字段
                    if (this.isAdd === 'add') {
                        if (params.ipType === 'single') {
                            params.ipAddress = (params.ipAddressDes || '').trim()
                            params.ipRangeStart = ''
                            params.ipRangeEnd = ''
                        } else {
                            params.ipRangeStart = (params.ipRangeStartDes || '').trim()
                            params.ipRangeEnd = (params.ipRangeEndDes || '').trim()
                            params.ipAddress = ''
                        }
                    } else {
                        // 编辑时：根据 ipType 判断更新哪些字段
                        if (params.ipType === 'single') {
                            if (params.ipAddressDesNew !== params.ipAddressDes) {
                                params.ipAddress = (params.ipAddressDes || '').trim()
                            }
                        } else if (params.ipType === 'range') {
                            if (params.ipRangeStartDesNew !== params.ipRangeStartDes) {
                                params.ipRangeStart = (params.ipRangeStartDes || '').trim()
                            }
                            if (params.ipRangeEndDesNew !== params.ipRangeEndDes) {
                                params.ipRangeEnd = (params.ipRangeEndDes || '').trim()
                            }
                        }
                    }
                    if (this.isAdd === 'add') {
                        addWhiteAPI(params).then(res => {
                            this.loading.close();
                            if (res.code === 200) {
                                this.handleReuslt(res);
                            } else {
                                this.$modal.msgError(res.msg);
                            }
                        }).catch(error => {
                            this.loading.close();
                            this.$modal.msgError(this.errorMsg(error));
                        });
                    } else {
                        updateWhiteAPI(params).then(res => {
                            this.loading.close();
                            if (res.code === 200) {
                                this.handleReuslt(res);
                            } else {
                                this.$modal.msgError(res.msg);
                            }
                        }).catch(error => {
                            this.loading.close();
                            this.$modal.msgError(this.errorMsg(error));
                        });
                    }
                }
            });
        },
        errorMsg(error) {
            const errorMessage = error.message;
            const errorArr = errorMessage.split('：');
            const errorObjData = errorArr.length > 1 ? JSON.parse(errorArr[1]) : '';
            if(errorObjData){
                return this.errorObj[errorObjData.paramName] + errorArr[0] + ':' + errorObjData.originalValue;
            }else{
                return errorMessage;
            }
            
        }
    }
};
</script>
<style lang="scss" scoped>
.w700 ::v-deep .el-dialog {
    width: 700px;
}

.w500 ::v-deep .el-dialog {
    width: 500px;
}

.w500 ::v-deep .el-dialog__header,
.w700 ::v-deep .el-dialog__header {
    // background: #eeeeee;

    .el-dialog__title {
        font-size: 16px;
    }
}

.yxq .el-range-separator {
    margin-right: 7px !important;
}

.el-date-editor--daterange.el-input__inner {
    width: 260px;
}

.form-item {
    width: 100%;
}

.select-style {
    display: flex;
    justify-content: space-between;
}
</style>