<template>
    <view
        class="msg-container-wrapper"
        :style="{
            'flex-direction': align === 'left'
                ? 'row'
                : 'row-reverse',
        }"
    >

        <!-- 头像 -->
        <view class="msg-container-avatar">
            <c-image
                has-compress
                :src="avatar"
                width="0.4rem"
                height="0.4rem"
                class="avatar-image"
                :hack-white-stroke="false"
                :extra="{column: 2}"
                @tap="jumpAvatar(avatarLink)"
            />
        </view>
        <view class="msg-container-main" :class="name ? 'msg-container-name' : ''">
            <view v-if="name" class="msg-name c-color-gray c-font-small">{{ name }}</view>
            <view
                v-if="tips && tips.length"
                class="c-font-small c-color-gray c-gap-inner-left c-gap-inner-right msg-tip-style"
                :style="{
                    'text-align': align || 'right',
                }"
            >
                <text
                    v-for="(o, i) in tips"
                    :key="i"
                    :class="i === 0 ? '' : 'c-gap-left-small'"
                >{{ o }}</text>
            </view>
            <view class="msg-main-content">
                <view
                    v-if="sendState === 'loading'"
                    class="msg-send-loading"
                />
                <!-- 图标若使用flex来居中，部分im组件有兼容性问题 -->
                <c-icon
                    v-if="(sideIcon && sideIcon.name)
                        || (sendState && (sendState === 'fail' || sendState === 'imgFail'))"
                    class="msg-side-icon"
                    :name="sideIcon && sideIcon.name || 'exclamation-circle-solid'"
                    :color="sideIcon && sideIcon.color || '#FF6F61'"
                    :font-size="sideIcon && sideIcon.size || '20px'"
                    @tap.stop="$emit('askReset', $event)"
                />
                <view
                    class="msg-main-wrapper"
                    :style="{
                        'background-color': bgColor,
                        'color': textColor,
                        'display': blockStyle,
                    }"
                >
                    <!-- 长按悬浮tooltip -->
                    <c-tooltip
                        :show="msg.allowConvert && toolTipFlag"
                        :top="toolTipRect.top"
                        :left="toolTipRect.left"
                        :show-mask="false"
                        padding="12px 15px"
                        :triangle-left="27"
                        triangle="down"
                        :border-radius="8"
                        bg-color="#303030"
                    >
                        <view class="tooltip-cnt" @tap="transTxt">
                            <image
                                class="tooltip-cnt-image"
                                src="https://med-fe.cdn.bcebos.com/wz/transtxt.png"
                                mode="widthFix"
                            />
                        </view>
                    </c-tooltip>
                    <!-- 气泡主体 -->
                    <view
                        class="msg-main"
                        :style="msgMainSty"
                    >
                        <slot></slot>
                    </view>

                    <!-- 图片上传遮罩 -->
                    <view
                        v-if="sendState && (sendState === 'imgLoading' || sendState === 'imgFail')"
                        class="img-mask"
                    >
                        <view
                            v-if="sendState === 'imgLoading'"
                            class="img-loading-wrap"
                        >
                            <view class="img-loading"/>
                            <c-icon
                                name="baidu-logo"
                                class="img-icon"
                            />
                        </view>
                    </view>

                    <!-- 气泡三角 -->
                    <view
                        v-if="triangle"
                        :class="['msg-main-triangle-' + align, 'msg-main-triangle']"
                    >
                        <svg
                            width="6px"
                            height="14px"
                            viewBox="0 0 17 36"
                            version="1.1"
                            xmlns="http://www.w3.org/2000/svg"
                            xmlns:xlink="http://www.w3.org/1999/xlink"
                        >
                            <g
                                stroke="none"
                                stroke-width="1"
                                fill="none"
                                fill-rule="evenodd"
                            >
                                <!-- eslint-disable -->
                                <path
                                    d="M0.00063936275,0 L0.000639362751,36 C0.27534144,34.6293937 1.40988235,32.7489653 3.40426209,30.3587147 C5.03674492,28.4021951 8.36954397,25.2870124 13.4026592,21.0131668 L13.4026515,21.0131577 C15.0865864,19.5832524 15.2925182,17.0589862 13.8626129,15.3750512 C13.7314622,15.220601 13.5887655,15.0763392 13.435755,14.9435117 C8.61789649,10.7611563 5.27406552,7.61873521 3.40426209,5.51624828 C1.10365163,2.92934351 -0.0308892789,1.09059409 0.00063936275,0 Z"
                                    :fill="arrowBgColor || bgColor"
                                />
                            </g>
                        </svg>
                        <!-- <svg
                            width="6px"
                            height="14px"
                            viewBox="0 0 17 36"
                            version="1.1"
                            xmlns="http://www.w3.org/2000/svg"
                            xmlns:xlink="http://www.w3.org/1999/xlink"
                        >
                            <g
                                stroke="none"
                                stroke-width="1"
                                fill="none"
                                fill-rule="evenodd"
                            >
                                <path
                                    d="M1.00000281,4.54747351e-13 L14.5510401,4.54747351e-13 L16.9941077,4.54747351e-13 L16.9941077,35.989802 L14.9853737,35.989802 C14.2960081,29.6683812 13.593267,25.1086295 12.8771502,22.3105469 C10.9728009,14.8696843 6.78158864,8.00535836 0.303513424,1.71756921 L0.303511954,1.71757072 C-0.0927902466,1.33290944 -0.102227081,0.699813458 0.282434196,0.303511257 C0.470754992,0.109491348 0.729617069,4.5479702e-13 1.00000281,4.54747351e-13 Z"
                                    :fill="bgColor"
                                    transform="translate(8.497054, 17.994901) scale(-1, 1) translate(-8.497054, -17.994901)"
                                />
                            </g>
                        </svg> -->
                    </view>
                    <!-- 发送状态 -->
                    <!-- <view
                        v-if="showSendStatus"
                        :class="['msg-main-send-' + align, 'msg-main-send']"
                    >
                        <image
                            v-if="sendState === 'loading'"
                            :src="'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=2669382790,1249805892&fm=179&app=35&f=GIF?w=100&h=50&s=FF8838624B8367744EFDF0CA0000E0B1'"
                            class="loading"
                        />
                        <image
                            v-else-if="sendState === 'error'"
                            :src="'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=2669382790,1249805892&fm=179&app=35&f=GIF?w=100&h=50&s=FF8838624B8367744EFDF0CA0000E0B1'"
                            class="loading"
                        />
                        <c-icon
                            v-else
                            class="msg-side-icon"
                            :name="sideIcon.name"
                            :color="sideIcon.color || '#FF6F61'"
                            :font-size="sideIcon.size || '20px'"
                        />
                    </view> -->
                    <!-- 已读未读 -->
                    <view
                        v-if="showReadStatus
                            && (sendState !== 'loading')
                            && (sendState !== 'fail')"
                        class="msg-readState"
                        :class="['msg-main-read-' + align, 'msg-main-read', readStatus ? 'c-color-gray' : 'msg-main-readed']"
                    >{{readStatus ? '已读' : '未读'}}</view>
                </view>
                <view class="msg-side-icon-right" :style="{'display': (msg.allowConvert && readState === 1) ? 'show' : 'none'}">
                    <view class="msg-readState-point"></view>
                    <view
                        @tap="transTxt"
                        class="c-inline-block c-font-tiny c-trans-txt"
                        :style="{'visibility': (msg.showReadStateTxt || showReadStateTxt) ? 'visible' : 'hidden'}"
                        >转文字</view>
                </view>
                <view
                    v-if="convertTxtFlag"
                    class="msg-container-space-flex"
                />
            </view>
            <!-- 语音转文字部分 -->
            <view
                class="msg-append"
                v-if="msg.allowConvert && convertTxtFlag"
            >
                <view class="msg-append-content">
                    <image
                        v-if="loadImg"
                        :src="'https://med-fe.cdn.bcebos.com/wz/loading.gif'"
                        class="msg-append-loading"
                        mode="aspectFit"
                    />
                    {{ convertTxt }}
                </view>
                <view>
                    <view class="msg-append-split"></view>
                    <view class="msg-append-statement">注:文字为机器自动识别转换，仅供参考</view>
                </view>
            </view>
            <!-- 修改回答 -->
            <view
                v-if="align === 'right' && askReset && modify"
                class="msg-reset c-gap-inner-right-middle c-font-small"
                :style="{
                    color: modify.color ? modify.color : bgColor
                }"
                @tap="$emit('askReset', $event)"
            >
                {{modify.text || '修改信息'}}
            </view>
        </view>
        <view
            :class="isFlex ? 'msg-container-space-flex' : 'msg-container-space'"
            @tap.stop
        />
        <view v-if="showMask" class="tool-mask" @touchstart.stop="onMaskTap">
    </view>
</view>
</template>
<script>
/**
 * @file 对话组件
 * @author chenshuo04
 */
import {navigate} from '../../utils/navigate';
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import CTooltip from '@baidu/med-ui/components/Tooltip/Tooltip';
import CImage from '@components/common/image';
import {request} from '../../utils/request';

let TouchTimer = null;

export default {
    config: {
        component: true
    },
    components: {
        CIcon,
        CTooltip,
        CImage
    },
    props: {
        // 说话人弹窗信息
        popupInfo: {
            type: Object,
            default() {
                return {};
            }
        },
        tips: {
            'type': Array,
            default() {
                return [];
            }
        },
        avatar: {
            'type': String,
            'default': ''
        },
        avatarLink: {
            'type': String,
            'default': ''
        },
        align: {
            'type': String,
            'default': 'right'
        },
        // 箭头背景色
        arrowBgColor: {
            'type': String,
            'default': ''
        },
        // 背景色
        bgColor: {
            'type': String,
            'default': '#fff'
        },
        // 文字颜色
        textColor: {
            'type': String,
            'default': '#000'
        },
        // 消息主体是否随其中内容可伸缩，默认为否
        isFlex: {
            'type': Boolean,
            'default': false
        },
        // 是否有气泡三角
        triangle: {
            'type': Boolean,
            'default': true
        },
        // 消息主体样式
        msgMainSty: {
            type: Object,
            default() {
                return {};
            }
        },
        // 是否支持修改
        askReset: {
            type: Boolean,
            default() {
                return false;
            }
        },
        // 消息主体 display
        blockStyle: {
            'type': String,
            'default': 'block'
        },
        // 对话气泡旁边的icon图标
        sideIcon: {
            type: Object,
            default() {
                return {};
            }
        },
        // 是否显示已读未读状态
        showReadStatus: {
            type: Boolean,
            default() {
                return false;
            }
        },
        // 是否显示消息发送状态
        showSendStatus: {
            type: Boolean,
            default() {
                return false;
            }
        },
        // 消息已读未读状态
        readStatus: {
            type: Number,
            default() {
                return 0;
            }
        },
        // 发送状态,消息发送状态loading、fail、done
        sendState: {
            'type': String,
            'default': 'done'
        },
        // 聊天对方名称
        name: {
            'type': String,
            'default': ''
        },
        // 未读标记
        readStateIcon: {
            type: Number,
            default() {
                return 0;
            }
        },
        // 未读文字
        showReadStateTxt: {
            type: Boolean,
            default() {
                return false;
            }
        },
        // 消息体
        msg: {
            type: Object,
            default() {
                return {};
            }
        },
        modify: {
            type: Object,
            default() {
                return {
                    text: '修改信息',
                };
            },
        }
    },
    data() {
        return {
            toolTipRect: {
                top: -55,
                left: 50
            },
            toolTipFlag: false,
            isSwan: process.env.MARS_ENV === 'swan',
            showMask: false,
            convertTxtFlag: false,
            convertTxt: '',
            loadImg: false,
            readState: 1
        };
    },
    watch: {
        readStateIcon(val) {
            this.readState = val;
        }
    },
    created() {
        this.readState = this.readStateIcon;
    },
    methods: {
        jumpAvatar(url) {
            // 头像跳转
            if (url) {
                navigate({
                    url
                });
            } else if (this.popupInfo.name) {
                this.$emit('popup');
            }
        },
        onLongPress(e) {
            clearInterval(TouchTimer);
            if (this.msg.content[0].type === 'audio' && this.convertTxtFlag !== true) {
                this.showToolTip();
            }
        },
        transTxt() {
            this.closeToolTip();
            this.showLoadImg();
            this.readState = 0;
            // 标记为已读
            // 触发寻找下一个未读消息
            this.$emit('nextAudio');
            // 调用后端接口，改变状态
            this.convertTxtFlag = true;
            this.updateState();
            request({
                url: this.msg.transTextUrl,
                method: 'GET'
            }).then(res => {
                this.hiddenLoadImg();
                if (!res.data.text || res.data.text === '') {
                    this.convertTxtFlag = false;
                    this.$api.showToast({
                        icon: 'none',
                        title: '未识别到语音'
                    });
                }
                else {
                    this.convertTxt = res.data.text;
                }
            }).catch(error => {
                this.hiddenLoadImg();
                this.convertTxtFlag = false;
                this.$api.showToast({
                    icon: 'none',
                    title: '转换失败，请重试'
                });
            });
        },
        updateState() {
            this.msg.updateStateUrl && request({
                url: this.msg.updateStateUrl,
                method: 'GET'
            });
        },
        showLoadImg() {
            this.loadImg = true;
        },
        hiddenLoadImg() {
            this.loadImg = false;
        },
        clearTimer() {
            clearInterval(TouchTimer);
        },
        showToolTip() {
            if (this.convertTxtFlag) {
                return;
            }
            this.toolTipFlag = true;
            this.openMask();
        },
        closeToolTip() {
            this.toolTipFlag = false;
            this.closeMask();
        },
        onMaskTap() {
            this.closeToolTip();
        },
        openMask() {
            this.showMask = true;
        },
        closeMask() {
            this.showMask = false;
        }
    }
};
</script>
<style scoped>
.msg-container-wrapper {
    display: flex;
    margin-bottom: 17px;
}

.avatar-image {
    display: block;
    border-radius: 50%;
    width: 40px;
    height: 40px;
}

.msg-container-avatar {
    flex: 0 0 40px;
}

.msg-container-space {
    flex: 0 0 40px;
}

.msg-container-space-flex {
    flex: 1000 0 40px;
}

.msg-container-main {
    flex: auto;
    max-width: 75%;
    /* 修改 max-width 需要将健康建议卡(im-health-advice)的宽度一并修改  */
    max-width: calc(100% - 80px);
}

.msg-container-name {
    margin-top: -0.04rem;
}

.msg-tip-style {
    line-height: 1.2;
    margin-bottom: 5px;
}

.msg-main-content {
    position: relative;
}

.msg-main-wrapper {
    flex: auto;
    position: relative;
    margin: 0 10px;
    min-height: 40px;
    border-radius: 8px;
}

.msg-main {
    overflow: hidden;
    font-size: 17px;
    line-height: 21px;
    border-radius: 9px;
    padding: .1rem .12rem;
}

.msg-main-triangle {
    position: absolute;
    top: 11px;
}

.msg-main-triangle-left {
    left: -5px;
    /* transform: rotateY(180deg);  */
    transform: rotateY(180deg);
    -ms-transform: rotateY(180deg); 	/* IE 9 */
    -moz-transform: rotateY(180deg); 	/* Firefox */
    -webkit-transform: rotateY(180deg); /* Safari 和 Chrome */
    -o-transform: rotateY(180deg);
}

.msg-main-triangle-right {
    right: -5px;
}

.msg-main-read {
    position: absolute;
    bottom: 0;
}

.msg-main-readed {
    color: #fd503e;
}

.msg-main-read-left {
    right: -35px;
}

.msg-main-read-right {
    left: -35px;
}

.msg-main-send {
    position: absolute;
    top: 50%;
    margin-top: -10px;
}

.msg-main-send-left {
    right: -25px;
}

.msg-main-send-right {
    left: -25px;
}

.msg-reset {
    text-align: right;
    position: relative;
    top: 5px;
}

.msg-side-icon {
    position: absolute;
    top: 50%;
    margin-top: -10px;
    left: -15px;
}

.msg-side-icon-right {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 50%;
    margin-top: -12px;
    right: -60px;
}

.tooltip-cnt {
    display: flex;
}

.tooltip-cnt-image {
    width: 40px;
    height: 35px;
}

.c-trans-txt {
    border-radius: 9px;
    background: #e5e5e5;
    padding: 3px 6px;
    color: #999;
    font-size: 12px;
    line-height: 12px;
    margin-left: 8px;
}

.msg-readState-point {
    border: 3px solid #f33;
    border-radius: 50%;
}
@keyframes rabbit {
    0% {
        background-position: 0 0;
    }

    100% {
        background-position: -200px 0;
    }
}

.msg-send-loading {
    background-image: url('https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=2060780410,2483130661&fm=179&app=35&f=PNG?w=600&h=90');
    background-size: cover;
    height: 30px;
    width: 30px;
    -webkit-animation: rabbit 400ms steps(8) infinite;
    animation: rabbit 400ms steps(8) infinite;
    margin: auto;
    position: absolute;
    top: 50%;
    margin-top: -15px;
    left: -20px;
}
@keyframes m-loading-rotation {
    from {
        -webkit-transform: rotate(1deg);
    }

    to {
        -webkit-transform: rotate(360deg);
    }
}

.img-mask {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    border-radius: 8px;
    background-color: rgba(0, 0, 0, .6);
}

.img-loading-wrap {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -.27rem;
    margin-left: -.27rem;
}

.img-loading {
    position: absolute;
    display: block;
    width: .5rem;
    height: .5rem;
    margin: auto;
    border: .02rem solid #f3f3f3;
    box-sizing: content-box;
    border-top-color: rgba(0, 0, 0, 0);
    border-radius: 50%;
    transform-origin: 50% 50%;
    transform: rotate(90deg);
    animation: m-loading-rotation 1s ease 0s infinite normal;
}

.img-icon {
    position: relative;
    display: block;
    width: .54rem;
    height: .54rem;
    margin: auto;
    font-size: .3rem;
    line-height: .5rem;
    color: #f3f3f3;
    text-align: center;
}

.msg-name {
    margin: 0 12px 3px 12px;
}

.msg-readState {
    margin-bottom: -0.03rem;
}

.msg-append {
    display: block;
    overflow: hidden;
    font-size: 17px;
    line-height: 21px;
    border-radius: 9px;
    margin: 5px 10px;
    background: #fff;
}

.msg-append-content {
    min-height: 17px;
    line-height: 21px;
    padding: .1rem .12rem;
    display: flex;
    align-items: center;
}

.msg-append-statement {
    font-size: 12px;
    color: #858585;
    padding: .08rem .12rem;
    line-height: 12px;
}

.msg-append-split {
    display: block;
    width: 100%;
    height: 1px;
    background: #e0e0e0;
    -webkit-transform: scaleY(0.33);
    transform: scaleY(0.33);
}

.tool-mask {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0);
    z-index: 921;
}

.msg-append-loading {
    width: 21px;
    height: 3px;
}

</style>
