<template>
    <view class="c-padding-h">
        <!-- 消息列表 -->
        <view
            v-for="(msg) in allMsgList"
            :id="'stm_' + msg.rand"
            :key="msg.rand"
            use-trackby
        >
            <im-msg
                :is-im-popup="true"
                :msg="msg"
                :ask-stl="{
                    bgColor: '#fff',
                }"
                @applyDrugs="applyDrugs"
            />
        </view>
    </view>
</template>

<script>
/**
* @file 预下单-im
* @author dengqiuju
* @categories 业务组件
* @tags [预下单-im]
*/

import {PRES_AUDIT_STATUS_TYPE} from '@utils/constant';
import {request} from '@utils/request';
import * as core from '@utils/core';
import * as Conf from '@utils/conf';
import ImMsg from '@components/im/im-msg';

// 消息轮询timer
let msgTimer = null;
export default {
    config: {
        component: true
    },
    options: {
        addGlobalClass: true
    },
    components: {
        ImMsg
    },
    props: {
        questionId: {
            type: String,
            default: ''
        },
        preOrderId: {
            type: String,
            default: ''
        },
        wenzhenUrl: {
            type: String,
            default: ''
        },
        msgList: {
            type: Array,
            default() {
                return [];
            }
        }
    },
    data() {
        return {
            // 刷新消息开关
            needCheck: true,
            allMsgList: []
        };
    },
    created() {
        // 有msgList时才会展示组件，所以可直接赋值给allMsgList
        const list = this.msgList && this.msgList.length && this.msgList.slice(0);
        this.allMsgList = this.setTimeRand(list);
        this.pollGetNewMsg();
    },
    methods: {
        /**
         * @description: 格式化时间
         * @param {number} timestamp 时间戳
         * @return {string} 返回指定格式的时间
         */
        getTime(timestamp) {
            return core.formatDate(timestamp, 'yyyy年MM月dd日 hh:mm');
        },

        /**
         * @description: 给数据添加时间标记,增加rand标识
         * @param {Array} msgList 消息数组
         * @return {Array} 添加time和rand字段后的数组
         */
        setTimeRand(msgList) {
            return msgList.map((msg, i) => {
                if (!msg.rand) {
                    msg.rand = core.rand();
                }
                const pre = msgList[i - 1];
                if (msg.timestamp && ((!pre || !pre.timestamp) || msg.timestamp - pre.timestamp >= 5 * 60 * 1000)) {
                    msg.time = this.getTime(msg.timestamp * 1000);
                }
                return msg;
            });
        },

        /**
         * @description: 获取最后一条消息ID
         * @return {string} 返回messageID
         */
        getLastMsgId() {
            const list = this.allMsgList;
            const len = list && list.length;

            for (let i = len - 1; i >= 0; i--) {
                const msg = list[i];

                if (msg.messageID) {
                    return String(msg.messageID);
                }
            }
            return '';
        },

        /**
         * @description: 根据处方状态处理获取新消息开关
         */
        handlePollPresStatus(presStatus) {
            // 处方审核通过/失败及其他异常态时 停止轮询
            const {presPass, presFail, timeout, expired} = PRES_AUDIT_STATUS_TYPE;
            if ([presPass, presFail, timeout, expired].includes(presStatus)) {
                this.needCheck = false;
            } else {
                this.needCheck = true;
            }
            // 不需要检测时清除获取新消息的timer
            if (!this.needCheck) {
                this.clearMsgTimer();
            }
        },
        /**
         * @description: 获取新消息
         */
        getNewMsg() {
            return new Promise((resolve, reject) => {
                const lastMsgId = this.getLastMsgId();
                const now =  parseInt(Date.now() / 1000, 10);
                const options = {
                    question_id: this.questionId,
                    message_id: lastMsgId,
                    timestamp: now,
                    preOrderId: this.preOrderId
                };
                request({
                    // url: 'https://yapi.baidu-int.com/mock/200/med/api/gy/medstorecommonrefresh',
                    url: Conf.apiHost + '/med/api/gy/medstorecommonrefresh?vn=med',
                    data: options,
                    method: 'POST',
                    isNeedLogin: true,
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    }
                }).then(resp => {
                    const {data} = resp;
                    const list = [...this.allMsgList, ...data.msgList];
                    this.allMsgList = this.setTimeRand(list);
                    // emit开方状态
                    const {presStatus, applyUrl} = data;
                    if (presStatus) {
                        this.$emit('presStatusChange', {
                            presStatus,
                            applyUrl
                        });
                        // 处方审核通过/失败时停止获取新消息
                        this.handlePollPresStatus(presStatus);
                    }
                    resolve(data);
                }).catch(() => {});
            });
        },

        /**
         * @description: 处方卡返回的drugs
         */
        applyDrugs(drugs) {
            this.$emit('applyDrugs', drugs);
        },

        /**
         * @description: 轮询获取新消息
         */
        pollGetNewMsg() {
            this.clearMsgTimer();
            if (!this.needCheck) {
                return;
            }
            msgTimer = setInterval(() => {
                this.getNewMsg();
            }, 5000);
        },

        /**
         * @description: 清除timer
         */
        clearMsgTimer() {
            msgTimer && clearInterval(msgTimer);
        }
    },
    lifetimes: {
        detached() {
            this.clearMsgTimer();
        }
    },
    pageLifetimes: {
        show() {
            // 回到页面后先获取一次消息，避免回到页面状态未及时更新
            this.getNewMsg();
            // 回到页面后恢复刷新消息
            this.pollGetNewMsg();
        },
        hide() {
            this.clearMsgTimer();
        }
    }
};
</script>
