<template>
    <div class="email2" :class="!!error ? 'email2__error' : ''">
        <div class="email-box" ref="emailBox">
            <el-tag
                :key="tag"
                size="mini"
                type="info"
                v-for="tag in activeList"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
            >
                {{ tag }}
            </el-tag>
            <el-input v-model="email" ref="saveTagInput"
                @keyup.enter.native="handleInputConfirm" @keyup.delete.native="handleDeleteConfirm"
                @blur="handleInputConfirm" @input.native="handleInput" @focus="focusInput">
            </el-input>
        </div>
        <div v-if="!!error" class="tip">{{ error }}</div>
    </div>
</template>

<script setup lang="ts">
    // const props = defineProps({
    //     inputType: {
    //         type: String,
    //         required: true
    //     }
    // })

    const emits = defineEmits(['inputFocus'])

    const activeList = defineModel({ type: Array })

    const emailList = ref([])
    const inputVisible = ref(false)
    const email = ref('')
    // 默认点击一次backspace就会从activeList中删除最后一个
    const deleteCount =  ref(1)
    const error = ref('')
    const isPaste = ref(false)
    const emailBox = ref()

    onMounted(() => {
        emailBox.value.onclick = function () {
            this.classList.add('email-box--active')
            const input = this.querySelector('input')
            input.focus()

            input.onblur = () => {
                this.classList.remove('email-box--active')
            }
        }
    })

    const paste = () => {
        isPaste.value = true
        navigator.clipboard.readText().then(text => {
            addMail(text)
        }).catch(err => {
            console.error('读取剪贴板内容失败：', err);
        });
    }

    const addMail = (mail: string) => {
        if(mail) {
            let list: any = mail.split(/,|;|，|；/).map(e => e.trim()).filter(e => e && isEmail(e))
            list = Array.from(new Set(activeList.value.concat(list)))
            activeList.value = list
        }
    }

        const handleClose = (tag) => {
            activeList.value.splice(activeList.value.indexOf(tag), 1)
        }

        const handleInput = (e) => {
            if (isPaste.value) {
                error.value = ''
                email.value = ''
                isPaste.value = false
            } else {
                const s = e.data
                if (s === ',' || s === '，') {
                    handleInputConfirm()
                }
                error.value = ''
            }
        }

        const focusInput = () => {
            emits('inputFocus')
        }

        const handleInputConfirm = () => {
            if (activeList.value.length === 0 && !email.value) {
                // error.value = '请输入邮箱'
                return
            } else {
                email.value && validateEmail()
            }
        }

        const validateEmail = () => {
            const emails = email.value.trim().replace(/(,$)|(，$)/g, '')

            const isExist = (n) => {
                return activeList.value.some(v => v === n)
            }

            if (isEmail(emails)) {
                if (!isExist(emails)) {
                    activeList.value.push(emails)
                    email.value = ''
                    deleteCount.value = 1
                    error.value = ''
                } else {
                    error.value = '邮箱已存在'
                }
            } else {
                error.value = '邮箱格式错误'
            }
        }

        const isEmail = (val) => {
            let regEmail = /^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,}$/
            return regEmail.test(val)
        }

        const handleDeleteConfirm = () => {
            if (!email.value) {
                if (deleteCount.value === 1) {
                    activeList.value.pop()
                } else {
                    deleteCount.value -= 1
                }
            }
        }

        /**
         * @function 验证邮箱是否输入通过，没有error就代表通过
         * */
        const validation = () => {
            handleInputConfirm()
            return !error.value
        }
    // watch: {
    //     activeList(val) {
    //         this.$emit('valueEvent', val)
    //     },
    //     email(newVal, oldVal) {
    //         if (!newVal && oldVal.length === 1) {
    //             // 在email为空后还需点一次backspace才能删除
    //             this.deleteCount = 2
    //         }
    //     }
    // }
    defineExpose({
        paste,
        addMail
    })
</script>

<style scoped lang="scss">
.email-box {
    display: flex;
    /*margin-top: 4px;*/
    flex-wrap: wrap;
    border-radius: 5px;
    box-sizing: border-box;
    align-items: center;
    border: 1px solid #d9d9d9;
    min-height: 32px;
    max-height: 160px;
    overflow-y: auto;
    cursor: text;

    &:hover {
        border-color: #bfbfbf;
    }

    .el-input{
        flex: 1;
    }

    :deep(.el-input__wrapper) {
        border: none !important;
        box-shadow: none;
    }

    .el-tag{
        margin-left: 8px;
    }
}

.email-box--active {
    border-color: #268DFF !important;
}

.email2 {
    width: 100%;
    >.tip {
        line-height: 1.5;
        font-size: 12px;
        color: #fa2a31;
    }

    &.email2__error {
        >.email-box {
            border: 1px solid #fa2a31 !important;
        }
    }
}
</style>