<template>
    <view
        class="progress"
        :style="{
            padding
        }"
    >
        <!-- 顶部提示 -->
        <view v-if="headerTips" class="progress__header__tips c-color-gray c-font-normal">{{ headerTips }}</view>
        <view class="progress__bar">
            <view
                v-for="item in orderProcess.list"
                :key="'progress__' + item.text"
                class="progress__bar__item"
                :class="{'progress__bar__item-act': item.status === 1}"
                :style="{
                    width: itemWidth + '%'
                }"
            >
                <view class="progress__bar__item__text c-font-normal c-gap-bottom-small">
                    {{ item.date }}
                </view>
                <view class="progress__bar__item__center">
                    <view
                        class="progress__bar__item__circle"
                        :class="{'progress__bar__item-act__circle': item.status === 1}"
                    >
                        <c-icon
                            class="icon"
                            name="yixuanzhong-solid"
                            font-size="17px"
                            :color="item.status === 1 ? '#FD503E' : '#E0E0E0'"
                        />
                    </view>
                    <view class="progress__bar__item__line" />
                </view>
                <!-- text多行 数组处理 -->
                <view v-if="Array.isArray(item.text)" class="progress__bar__item__text c-font-normal c-gap-top-small">
                    <view v-for="(item, index) in item.text" :key="index">{{ item }}</view>
                </view>
                <view v-else class="progress__bar__item__text c-font-normal c-gap-top-small">
                    {{ item.text }}
                </view>
            </view>
        </view>
        <view
            v-if="tips"
            class="progress__tips"
            @tap="onProgessTips"
        >
            <view class="progress__cont">
                <view class="progress__tips__text c-span1">
                    <rich-text v-if="tips" :nodes="tips" />
                </view>
                <view v-if="orderProcess.url && hideRightIcon" class="progress__tips__icon c-font-normal c-gap-left">
                    <c-icon name="right" font-size="14px" />
                </view>
                <!-- 如果有按钮，也放在右侧 -->
                <view v-if="orderProcess.btn" class="progress__tips__icon c-font-normal c-gap-left">
                    <c-button
                        :height="28"
                        :font-size="14"
                        :primary-color="btnPrimaryColor[orderProcess.btn.color]"
                        type="primary"
                        border-radius="20px"
                        @tap="onProcessButtonTap(orderProcess.btn)"
                    >
                        {{ orderProcess.btn.text }}
                    </c-button>
                </view>
            </view>
            <!-- 箭头 -->
            <view class="progress__tips__arrow" :style="{left: 'calc(' + arrowLeft + '% - 0.06rem)'}" />
        </view>
    </view>
</template>
<script>
/**
 * @file 订单进度
 * @author mayifan02
 * @categories 业务组件
 * @tags [component]
 */
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import CButton from '@baidu/med-ui/components/Button/Button';
import {navigate} from '@utils/navigate';
import {ubcSend} from '@utils/log';

export default {
    config: {
        navigationStyle: 'custom',
        component: true
    },
    options: {
        addGlobalClass: true
    },
    components: {
        CIcon,
        CButton
    },
    props: {
        /** 订单数据 */
        orderProcess: {
            type: Object,
            default: () => {
                return {};
            }
        },
        /** 圆圈默认状态 */
        circleNormalStyle: {
            type: Object,
            default: () => {
                return {
                    color: '#e0e0e0'
                };
            }
        },
        /** 圆圈激活状态 */
        circleActStyle: {
            type: Object,
            default: () => {
                return {
                    color: '#FD503E'
                };
            }
        },
        /** padding */
        padding: {
            type: String,
            default: '26px 0px 15px'
        },
        /** 提示文本 */
        headerTips: {
            type: String,
            default: ''
        },
        /** requestAsync */
        requestAsync: {
            type: Function,
            default: () => function () {}
        },
        /** 隐藏右侧箭头 */
        hideRightIcon: {
            type: Boolean,
            default: true
        },
        /** 强制显示icon */
        showIcon: {
            type: Boolean,
            default: false
        },
        /** 请求疫苗接种人列表 */
        listVaccPatient: {
            type: Function,
            default: () => function () {}
        },
        /** 请求疫苗接种人详细信息 */
        requestVaccPatientInfo: {
            type: Function,
            default: () => function () {}
        },
        // ubc打点必传字段page
        page: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            arrowLeft: 0,
            itemWidth: '',
            tips: '',
            btnPrimaryColor: {
                red: '#FD503E',
                white: '#fff'
            },
            vaccCountDownTimeSeconds: '',
            vaccCountDownTimeMinutes: '',
            vaccTimeInterval: 0
        };
    },
    created() {
        // 初始化组件数据
        this.initOrderProgress();
    },
    destroyed() {
        this.tips = '';
        clearInterval(this.vaccTimeInterval);
    },
    watch: {
        orderProcess(newVal, oldVal) {
            this.initOrderProgress();
        }
    },
    methods: {
        initOrderProgress() {
            // item宽度
            const len = this.orderProcess.list.length;
            this.itemWidth = 100 / len;
            // 箭头位置
            let statusIndex = len;
            this.orderProcess.list.some((item, index) => {
                if (item.status === 0) {
                    statusIndex = index;
                    return true;
                }
            });
            // 处理高亮
            this.tips = this.highlightFormat(this.orderProcess.tips);
            this.arrowLeft = (statusIndex / len) * 100 - this.itemWidth / 2;
            // 处理疫苗接种人的倒计时
            // remainingTimeProvide 倒计时的时间差
            if (this.orderProcess.remainingTimeProvide) {
                this.vaccCountDownTimeSeconds = this.orderProcess.remainingTimeProvide;
                if (this.vaccCountDownTimeSeconds > 0 && this.orderProcess.tips) {
                    clearInterval(this.vaccTimeInterval);
                    this.vaccCountDownTimeMinutes = Math.floor(this.vaccCountDownTimeSeconds / 60);
                    this.updataVaccCountdownTips(this.orderProcess.tips);
                    this.handleVaccCountdownTime(this.orderProcess.tips);
                } else {
                    this.tips = this.highlightFormat(this.orderProcess.isOutOfStockTips);
                }
            } else if (this.orderProcess.limit && this.orderProcess.paidTime) {
                let currentTimeMills = Date.parse(new Date());
                /* eslint-disable max-len */
                this.vaccCountDownTimeSeconds =
                    this.orderProcess.limit - (currentTimeMills / 1000 - this.orderProcess.paidTime);
                if (this.vaccCountDownTimeSeconds > 0 && this.orderProcess.tips_w) {
                    clearInterval(this.vaccTimeInterval);
                    this.vaccCountDownTimeMinutes = Math.floor(this.vaccCountDownTimeSeconds / 60);
                    this.updataVaccCountdownTips(this.orderProcess.tips_w);
                    this.handleVaccCountdownTime(this.orderProcess.tips_w);
                } else {
                    this.tips = this.highlightFormat(this.orderProcess.tips_d);
                }
            }
        },
        handleVaccCountdownTime(tips) {
            this.vaccTimeInterval = setInterval(() => {
                if (this.vaccCountDownTimeSeconds > 0) {
                    this.vaccCountDownTimeSeconds = this.vaccCountDownTimeSeconds - 1;
                    const currentTimeMinutes = Math.floor(this.vaccCountDownTimeSeconds / 60);
                    if (this.vaccCountDownTimeMinutes !== currentTimeMinutes) {
                        this.vaccCountDownTimeMinutes = currentTimeMinutes;
                        this.updataVaccCountdownTips(tips);
                    }
                } else {
                    clearInterval(this.vaccTimeInterval);
                    this.$set(this, 'tips', this.highlightFormat(this.orderProcess.tips_d));
                }
            }, 1000); // 每秒计算一次，但是按分钟来更新UI
        },
        updataVaccCountdownTips(tips) {
            let hours = Math.floor(this.vaccCountDownTimeMinutes / 60);
            let minutes = this.vaccCountDownTimeMinutes % 60;
            let resultTips = this.highlightFormat(tips.replace('[limit]', hours + '时' + minutes + '分'));
            this.$set(this, 'tips', resultTips);
        },
        onProgessTips() {
            if (this.orderProcess.url) {
                if (this.orderProcess.behavior === 'async') {
                    this.requestAsync(this.orderProcess.url);
                } else if (this.orderProcess.behavior === 'vaccgetpatient') {
                    ubcSend({
                        page: this.page,
                        type: 'clk',
                        value: 'examinebodydetail_get_patient'
                    });
                    this.requestVaccPatientInfo(this.orderProcess.url);
                } else {
                    navigate({
                        url: this.orderProcess.url,
                        extra: {
                            type: 'order-progress-tips'
                        }
                    });
                }
            }
        },
        onProcessButtonTap(btn) {
            // 重构之后，后端无法返回接种人列表弹窗弹起的标识，所以由前端来存储
            if (btn.type === 'listPatient' || btn.type === 'addPatient') {
                this.$emit('showVaccineList');
            }
            if (btn.type === 'listPatient') {
                ubcSend({
                    page: this.page,
                    type: 'clk',
                    value: 'examinebodydetail_add_patient_btn'
                });
                this.listVaccPatient(btn);
            } else if (btn.type === 'addPatient') {
                ubcSend({
                    page: this.page,
                    type: 'clk',
                    value: 'examinebodydetail_add_patient_btn'
                });
                navigate({
                    url: btn.asyncUrl
                });
            } else if (btn.type === 'book') {
                // 体检待预约的时候添加立即预约按钮
                navigate({
                    url: btn.asyncUrl
                });
            } else {
                // navigate({
                //     url : '/pages/vaccine-sub/patientedit/index?type=add',  // only for test !  btn.urlxxx
                // });
            }
        },
        // 匹配高亮文本
        highlightFormat(text = '', color = '#FD503E') {
            return text
                .replace(new RegExp('<em>', 'g'), '<span style="color: ' + color + ';">')
                .replace(new RegExp('</em>', 'g'), '</span>')
                .replace(new RegExp('<b>', 'g'), '<b style="font-weight: bold;">');
        }
    }
};
</script>
<style lang="less" scoped>
.progress {
    border-radius: 10px;
    background: #fff;
    padding: 26px 0px 15px;

    &__header {
        &__tips {
            text-align: center;
            margin-bottom: 13px;
        }
    }

    &__bar {
        color: #858585;
        display: flex;
        justify-content: space-around;

        &__item {
            position: relative;
            text-align: center;

            &__center {
                position: relative;
            }

            &__circle {
                position: relative;
                z-index: 10;
                margin: 0 auto;
                width: 16px;
                height: 16px;
                background: #fff;
                border-radius: 50%;
                color: #fff;
                font-weight: bold;
                text-align: center;
                box-sizing: border-box;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            &__line {
                width: 100%;
                height: 1px;
                background: #e0e0e0;
                position: absolute;
                top: 8px;
                left: 50%;
            }

            &:last-child {
                .progress__bar__item__line {
                    width: 0%;
                }
            }

            &-act {
                color: #fd503e;
            }
        }
    }

    &__cont {
        margin: 0 13px;
        background: #f5f5f5;
        padding: 11px 9px 10px;
        border-radius: 9px;
        display: flex;
        align-items: center;
    }

    &__tips {
        margin-top: 0.07rem;
        position: relative;
        color: #858585;

        &__arrow {
            position: absolute;
            top: -12px;
            border: 6px solid transparent;
            border-bottom-color: #f5f5f5;
        }

        &__text {
            font-family: PingFangSC-Regular;
            font-size: 0.14rem;
            color: #525252;
            letter-spacing: 0;
            line-height: 0.23rem;
            font-weight: 400;
        }
    }
}
</style>
