
<template>
    <el-form-item :label="item.label+'：'" v-for="(item,index) in standbyList" :prop="'standbyList.' + index" :rules="[{ required:index==0?true:false, validator: index==0?validateEmail:validateEmail2, trigger: 'blur' }]">
        <el-input @input="removeSpace($event,index)" v-model="item.value" :placeholder="'请输入'+item.label" />
        <el-icon style='margin-left: 10px;color:#1874ff;cursor: pointer;' @click="addItem(index)" v-if="index<1"><Plus /></el-icon>
        <el-icon style='margin-left: 10px;color:#1874ff;cursor: pointer;' @click="delItem(index)" v-if="index!=0"><Minus /></el-icon>
    </el-form-item>
</template>

<script setup lang="ts">
const valueRequire = defineModel();
const valueOne = defineModel('valueOne');
const valueTwo = defineModel('valueTwo');
const valueThree = defineModel('valueThree');

const props = defineProps({
    text: { // 表单文字
        type: String,
        default: true
    },
})
const standbyList = defineModel<any>('standbyList')


watch(standbyList, (newValue, oldValue) => {
    console.log('newValue',newValue)
    setArray()
});

const validateEmail =  (rule: any, value: any, callback: any) => {
    const reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    if (!value.value) return callback(new Error('电子邮箱不能为空'))
    if (!reg.test(value.value)) {
        callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }
}

const validateEmail2 =  (rule: any, value: any, callback: any) => {
    // const reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    // if (value.value!=''&&!reg.test(value.value)) {
    //     callback(new Error('请输入正确的邮箱格式'))
    // } else {
    //     callback()
    // }
    callback()
}

const removeSpace = (value: string,index?:number) => {
    let showValue = value.replace(/\s+/g, '')
    standbyList.value[index].value= showValue
    setArray()
}
const setArray = ()=>{
    let arr = standbyList.value.filter(function(element) {
        return element.value !== undefined && element.value !== null && element.value !== '';
    });
    valueRequire.value = arr.length>0?arr[0].value:''
    valueOne.value = arr.length>1?arr[1].value:''
    valueTwo.value = arr.length>2?arr[2].value:''
    valueThree.value = arr.length>3?arr[3].value:''
}
const addItem = (index:number)=>{
    if(standbyList.value.length<4){ // 不超过三个
        standbyList.value.push({label:'联系人备用邮箱',value:''})
    }else{
        ElMessage.warning('备用邮箱最多可添加三个');
    }

}
const delItem = (index:number)=>{
    standbyList.value.splice(index, 1);
    setArray()
}
</script>

<style lang="scss" scoped>

</style>
