<template>
    <view ref="scopedIdRef" :class="dust ? 'dust' : ''">
        <view class="bk-dialogue-title">患者最常问的问题</view>
        <view
            v-for="(dialogue, index) in dialogueData"
            :key="index"
            :class="targetPrefix + (index + 1)"
            class="bk-dialogue"
            @tap="handleParse(dialogue.ttsIndex)"
        >
            <view class="bk-dialogue-question">
                <view class="bk-dialogue-question-icon bk-dialogue-icon">问</view>
                <c-parse
                    v-if="dialogue.question"
                    :nodes="dialogue.question"
                    :class="dialogue.ttsIndex === ttsIndex ? 'bk-dialogue-active' : ''"
                    class="bk-dialogue-question-cont bk-dialogue-cont"
                    base-a-color="#00c8c8"
                    @onTapA="onTapA"
                />
            </view>
            <view class="bk-dialogue-answer">
                <view class="bk-dialogue-answer-icon bk-dialogue-icon">答</view>
                <c-parse
                    v-if="dialogue.answer"
                    :nodes="dialogue.answer"
                    :class="dialogue.ttsIndex === ttsIndex ? 'bk-dialogue-active' : ''"
                    css-prefix="parse-dialogue"
                    class="bk-dialogue-answer-cont bk-dialogue-cont"
                    base-a-color="#00c8c8"
                    @onTapA="onTapA"
                />
            </view>
        </view>
        <view class="c-line-bottom"/>
    </view>
</template>

<script>
/**
 * @file 百度健康医典  问答
 * @author yumingzhi
 * @categories 问答模块
 * @tags [component]
 */

import Parse from '@baidu/med-ui/components/Parse/Parse';
import {navigate} from '@utils/navigate';
import {send} from '@utils/log';
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';

export default {
    config: {
        component: true
    },
    options: {
        addGlobalClass: true
    },
    components: {
        CParse: Parse
    },
    props: {
        /**
         * 问答数据
         */
        dialogueData: {
            type: Array,
            default: () => []
        },
        /**
         * 是否蒙层
         */
        dust: {
            type: Boolean,
            default: false
        },
        /**
         * ttsIndex
         */
        ttsIndex: {
            type: Number,
            default: 0
        },
        /**
         * 锚点标识 
         */
        scrollFlag: {
            type: String,
            default: ''
        }
    },
    data() {
        const {navigationBarHeight, statusBarHeight} = getSystemInfo();
        return {
            titleMap: {},
            targetPrefix: 'dialogue-idx-',
            delayDuration: 1000,
            scrollDuration: 300,
            // h5TopHeight ≈ 页面标题高度+浮动横向导航栏高度 = 44px+53px = 97px
            h5TopHeight: 100,
            // swanTopHeight ≈ 小程序标题高度+小程序状态栏高度+浮动横向导航栏高度
            swanTopHeight: (navigationBarHeight + statusBarHeight + 60)
        };
    },
    created() {
        if (this.dialogueData && this.dialogueData.length > 0) {
            this.dialogueData.forEach((dialogue, index) => {
                let key = this.targetPrefix + (index + 1);
                this.titleMap[key] = dialogue.question;
            });
        }
    },
    mounted() {
        const __this = this;
        __this.$nextTick(() => {
            if (!__this.scrollFlag) {
                return;
            }
            __this.setDialogueTitleTop(__this.delayDuration);
            __this.$api.showLoading({
                title: '正在加载...',
                mask: false,
                success: () => setTimeout(() => __this.$api.hideLoading(), __this.delayDuration),
                fail: err => {}
            });
        });
    },
    methods: {
        fetchHtml(htmlString) {
            const scopedId = '';
            htmlString = htmlString
                .replace(
                    /<([a-z]{1,10}[1-6]{0,1})([\s\S]*?)(\/*?)>/gi,
                    `<$1 class="swan-detail-dialogue-content-$1" ${scopedId} $2>`
                )
                // 资源方换行符提交错误，暂时处理
                .replace(/<\/br>/gi, '<br/>')
                .replace(/>[\s\r\n]+</g, '><');
            htmlString = `<div class="swan-detail-dialogue-content" ${scopedId}>${htmlString}</div>`;
            return htmlString;
        },
        onTapA(e, attrs) {
            if (attrs.from === 'yd' && attrs.href) {
                navigate({url: attrs.href});
            }
            send({
                type: 't',
                action: 'click',
                extra: Object.assign({
                    module: 'highlightA'
                })
            });
        },
        handleParse(e) {
            /**
             * 点击高亮
             */
            this.$emit('handleParse', e);
        },
        // TODO: 校准标题元素的scrollTop值，有时会出现轻微偏差的情况
        // 设置dialogue标题元素的scrollTop值
        setDialogueTitleTop(delay = 0, noCheck) {
            const __set = () => {
                Promise.all([
                    new Promise((resolve, reject) => {
                        this.$api
                            .createSelectorQuery()
                            .selectViewport()
                            .scrollOffset(viewport => resolve(viewport.scrollTop))
                            .exec();
                    }),
                    new Promise((resolve, reject) => {
                        const targetClass = Object.keys(this.titleMap)
                            .find(key => {
                                return this.titleMap[key] && this.titleMap[key].startsWith(this.scrollFlag);
                            });

                        const query = this.$api.createSelectorQuery().select(`.${targetClass}`);
                        query.boundingClientRect(rect => {
                            const top = rect && rect.top || {};
                            resolve(top);
                        })
                            .exec();
                    })
                ]).then(values => {
                    const scrollTop = values[0];
                    let top = values[1];

                    if (top) {
                        if (process.env.MARS_ENV === 'h5') {
                            top = Math.floor(top + scrollTop - this.h5TopHeight);
                            this.scrollDuration = 300;
                        } else {
                            top = Math.floor(top + scrollTop - this.swanTopHeight);
                            this.scrollDuration = 500;
                        }

                        this.$api.pageScrollTo({
                            scrollTop: top,
                            duration: this.scrollDuration
                        });
                    } else {
                        !noCheck && this.setDialogueTitleTop(500, !noCheck);
                    }
                });
            };

            delay ? setTimeout(__set, delay) : __set();
        }
    }
};
</script>
<style lang="less" scoped>
.dust {
    filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: grayscale(100%);
    filter: gray;
}
.bk-dialogue-title {
    width: 100%;
    height: 60px;
    line-height: 60px;
    text-align: center;
    background: rgba(3, 208, 191, 0.1);
    border-radius: 5px;
    margin: 31px 0 24px 0;
    font-size: 20px;
    color: #00c8c8;
    font-family: 'PingFangSC-Regular';
}

.bk-dialogue {
    padding-bottom: 15px;
    font-family: 'PingFangSC-Regular';

    &-icon {
        flex: 0 0 auto;
        width: 19px;
        height: 19px;
        line-height: 19px;
        text-align: center;
        margin-right: 10px;
        margin-top: 5px;
        border-radius: 3px;
        font-size: 13px;
        color: #fff;
    }

    &-cont {
        font-size: 17px;
        color: #333;
        letter-spacing: 0;
        line-height: 31px;
    }

    &-question {
        display: flex;
        align-items: flex-start;
        margin-bottom: 10px;

        &-icon {
            background: #ff7061;
        }

        &-cont {
            font-weight: bold;
        }
    }

    &-answer {
        display: flex;
        align-items: flex-start;

        &-icon {
            background: #00c8c8;
        }

        &-cont {
            font-weight: normal;
        }
    }

    &-active {
        color: #00c8c8;
    }
}
</style>
