<template>
    <div class="mail_input">
        <!-- 已有数据展示 -->
        <div class="mail_input_item" v-for="(i, idx) in showList" :key="i.email">
            <div class="item_input" v-if="i.status && i.status === 'write'">
                <span class="item_input_hidden" :id="'item_input_hidden_' + idx">{{ formatLabel(i.content) }}</span>
                <el-input ref="inputRef" v-model="i.content" :id="'item_input_' + idx" @keyup.enter="itemEnter(i)"
                    @blur="itemBlur(i, idx)" @input="itemChange(idx)" />
            </div>
            <div class="item_err" v-else-if="i.status && i.status === 'err'" @dblclick="editMail(i, idx)">
                <!-- <span v-html="formatLabel(i.content)"></span> -->
                <el-tag
                    size="mini"
                    type="danger"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(idx)"
                >
                    {{ i.content }}
                    <el-tooltip effect="light" content="邮箱格式错误" placement="top">
                        <!-- <fes-icon style="color: #EC4847;padding: 0 4px;" type="jinggao"/> -->
                        <el-icon color=" #EC4847">
                            <Warning />
                        </el-icon>
                    </el-tooltip>
                </el-tag>
                
            </div>
            <div class="item" v-else @dblclick="editMail(i, idx)">
                <!-- <span>{{ i.name }}</span>
                <span>
                    <{{ i.email }}>
                </span> -->
                <el-tag
                    size="mini"
                    type="info"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(idx)"
                >
                    {{ i.email }}
                </el-tag>
            </div>
        </div>
        <!-- 新加输入框 -->
        <div class="mail_input_addBox" v-if="isEdit">
            <span class="item_input_hidden" id="item_input_hidden_add">{{ addValue }}</span>
            <el-input ref="inputAddRef" id="item_input_add" v-model="addValue" @input="itemChange('add')"
                @keyup.enter="addEnter" @blur="addBlur" @keydown="delItem($event)" @focus="focusInput"></el-input>
        </div>
    </div>
</template>
<script lang="ts" setup>
    import { Warning } from '@element-plus/icons-vue'

    const emits = defineEmits(['inputFocus'])
    const props = defineProps({
        isEdit: {
            type: Boolean,
            default: () => true
        },
        noChangeMailList: {
            type: Array,
            default: () => []
        },
        changeMailList: {
            type: Array,
            default: () => []
        }
    })

    /** 处理 < 和 > 字符 */
    const formatLabel = (str) => {
        return str.replace(/</g, '<').replace(/>/g, '>')
    }
    /** 根据输入信息获取邮箱信息 */
    const getEmailData = (value,isChange=true) => {
        // debugger
        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,}))$/
        let data = null
    
        // 如果数据为空则邮件无信息，做删除处理
        if (value && value !== '' && value.trim() !== '') {
        const inputData = value.trim()
        let name = null
        let email = null
    
        if (!reg.test(inputData)) {
            // 如果有 < 且有 > 则处理数据，根据结果再判断是否满足邮件格式
            const stNum = inputData.split('<').length - 1
            const etNum = inputData.split('>').length - 1
            const stIndex = inputData.indexOf('<')
            const etIndex = inputData.indexOf('>')
            // < 或者 > 只存在一个且 < 的位置小于 > 的位置
            if (stNum === 1 && etNum === 1 && stIndex < etIndex) {
            const inputName = inputData.substr(0, stIndex)
            const inputEmail = inputData.substr(stIndex + 1).replaceAll('>', '')
            if (reg.test(inputEmail)) {
                name = inputName
                email = inputEmail
            }
            } else {
            email = inputData
            }
        } else {
            email = inputData
            name = email.split('@')[0]
        }
        if (name === '' && email !== '') name = email.split('@')[0]
        data = {
            content: name && email ? `${email}` : inputData,
            name: name ? name.trim() : null,
            email: email ? email.trim() : null,
            status: name && email ? 'normal' : 'err',
            isChange
        }
        }
        return data
    }
    /** 根据接口数据返回邮件用户列表 */
    const getEmailUserList = (list,isChange=true) => {
        const result = [];
        (list || []).forEach(item => {
            result.push(getEmailData(item,isChange))
        })
        return result
    }

    const emails = defineModel({ type: Array })
    const list = ref([
        ...getEmailUserList(emails.value)
    ])
    const showList = computed(() => {
        return [].concat(getEmailUserList(props.noChangeMailList, false), list.value)
    })
    const addValue = ref('')
        // 邮箱双击切换输入框
    const editMail = (i, idx) => {
        if (!i.isChange) return
        i.status = 'write'
        console.log(this)
        nextTick(() => {
            const id = 'item_input_' + idx
            const el = window.document.getElementById(id)
            el.focus()
            setInputStyle(idx)
        })
    }
    // 双击切换至input的样式
    const setInputStyle = (idx) => {
        const id = 'item_input_hidden_' + idx
        const inputId = 'item_input_' + idx
        const el = window.document.getElementById(id)
        const inputEl = window.document.getElementById(inputId)
        const width = el.clientWidth
        let w = '100px'
        if (width > 76) {
            w = (width + 24) + 'px'
        }
        inputEl.style.width = w
    }
    // 双击切换至input的change事件
    const itemChange = (idx) => {
        nextTick(() => {
            setInputStyle(idx)
        })
    }
    // 处理邮箱格式
    const creatItem = (i, idx) => {
        const item = getEmailData(i.content)
        if (item) {
            let filList = showList.value.filter((i, index) => idx != index)
            if (filList.some(it => it.email === item.email)) {
                list.value.splice(idx - props.noChangeMailList.length, 1)
                return
            }
            i.name = item.name
            i.email = item.email
            i.status = item.status
            i.content = item.content

        } else {
            list.value.splice(idx - props.noChangeMailList.length, 1)
            console.log('cjy', list.value)
        }
        emails.value = list.value.map(i => i.content)
        // this.$emit('getMailList',this.showList)
    }
    // 双击切换至input的enter事件
    const inputRef = ref()
    const itemEnter = (i) => {
        // this.creatItem(i,idx)

        inputRef.value[0].blur()
    }
    // 双击切换至input的失焦事件
    const itemBlur = (i, idx) => {
        creatItem(i, idx)
    }
    // 新增输入框enter事件
    const inputAddRef = ref()
    const addEnter = () => {
        inputAddRef.value.blur()
    }
    // 新增输入框blur事件
    const addBlur = () => {
        const data = getEmailData(addValue.value)
        if (data && data.email) {
            if (!showList.value.some(i => i.email === data.email)) list.value.push(data)
            console.log(showList.value.filter(i => i.status === 'normal'))
            // this.$emit('getMailList',this.showList)
        }
        addValue.value = ''
        emails.value = list.value.map(i => i.content)
    }
    // 删除邮箱
    const delItem = (e) => {
        var evt = window.event || e
        if (evt.keyCode === 8) {
            if (addValue.value === '') {
                list.value.pop()
            }
        }
        emails.value = list.value.map(i => i.content)
    }
    const handleClose = (index) => {
        list.value.splice(index, 1)
        emails.value = list.value.map(i => i.content)
    }
    const addMail = (mail) => {
        if(mail) {
            mail = mail.split(',')
        }
        let data = getEmailUserList(mail)
        list.value.push(...data)
        emails.value = list.value.map(i => i.content)
    }
    const focusInput = () => {
        emits('inputFocus')
    }

    defineExpose({
        addMail
    })
</script>
<style lang="scss" scoped>
.mail_input {
    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;
    width: 100%;
    .mail_input_addBox {
        flex: 1;
    }

    :deep(.el-input__inner) {
        background: transparent;
        border: 0;
    }

    .mail_input_item {

        .item_input {
            margin-left: 8px;
            .el-input {
                height: 24px;
            }
            .item_input_hidden {
                white-space: nowrap;
                position: absolute;
                left: 0;
                top: 0;
                opacity: 0;
                z-index: 1;
                max-width: 200px;
                overflow: hidden;
            }
        }

        .item, .item_err {
            // color: rgba(126, 128, 130, 100);
            // height: 20px;
            // border-radius: 12px;
            // background-color: rgba(235, 244, 255, 1);
            // border: 1px solid rgba(178, 211, 253, 1);
            // padding: 0 12px;
            // display: flex;
            // align-items: center;

            // & span:first-child {
            //     margin-right: 4px;
            //     color: #202428;
            // }
            margin-left: 8px;
        }
        .item_err {
            :deep(.el-tag__content) {
                display: flex;
                align-items: center;
                .el-tooltip__trigger{
                    margin-left: 4px;
                }
            }
        }
    }

    .mail_input_addBox {
        .item_input_hidden {
            white-space: nowrap;
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            z-index: 1;
            max-width: 200px;
            overflow: hidden;
        }

        :deep(.el-input) {
            .el-input__wrapper {
                box-shadow: none;

                &.is-focus {
                    box-shadow: none;
                }

                &:hover {
                    box-shadow: none;
                }
            }
        }

    }
}
</style>
