<template>
    <view
        :style="{
            visibility,
            zIndex,
        }"
        class="dialog"
    >
        <view
            class="dialog-inner"
        >
            <!-- mask -->
            <view
                :style="{
                    opacity,
                }"
                class="mask"
                @tap="handleMaskTap"
                @touchmove.prevent
            />
            <!-- content -->
            <view class="wrap">
                <view
                    class="top-img"
                    :style="{
                        backgroundImage: 'url(' + topImg + ')',
                        width: '85vw',
                        height: '40vw',
                    }"
                />
                <view
                    v-if="cards.length"
                    class="content"
                    :style="{backgroundImage: bgColor}"
                >
                    <view class="list">
                        <view
                            v-for="(itm, idx) in cards"
                            :key="idx"
                            class="list-item"
                        >
                            <view class="c-gap-right-large flex-left">
                                <image class="list-item-img" :src="itm.icon"/>
                            </view>
                            <view class="flex-center">
                                <view class="list-item-name">{{ itm.title }}</view>
                                <view class="list-item-text">{{ itm.text }}</view>
                            </view>
                            <view class="flex-right">
                                <view v-if="itm.price" class="list-item-money">
                                    <text class="list-item-money-label">￥</text>
                                    <text class="list-item-money-value">{{ itm.price }}</text>
                                </view>
                                <login-btn
                                    :z-index="9"
                                    @onTapStart="onTapStart(itm)"
                                    @onLoginSuccess="jumpToPage(itm)"
                                >
                                    <view
                                        v-if="itm.btnText"
                                        class="list-item-btn"
                                        :style="{background: btnBgColor}"
                                    >
                                        {{ itm.btnText }}
                                    </view>
                                </login-btn>
                            </view>
                        </view>
                    </view>
                </view>
                <!-- close -->
                <view class="icon-wrap">
                    <c-icon
                        class="icon-close"
                        font-size="28px"
                        name="close-circle"
                        @tap="onClose"
                    />
                </view>
            </view>
        </view>
    </view>
</template>

<script>
/**
 * @file 运营弹窗
 * @author zhangqian51
 * @categories 业务组件
 * @tags [component]
 */

/* global getCurrentPages */
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import LoginBtn from './login-btn';

import * as login from '../../utils/login';
import {navigate, navToBdBoxH5} from '../../utils/navigate';
import {request} from '../../utils/request';
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';
import * as Log from '../../utils/log';
import * as conf from '../../utils/conf';
export default {
    config: {
        component: true
    },
    components: {
        CIcon,
        LoginBtn
    },
    props: {
        /**
         * 显示层级
         */
        zIndex: {
            type: Number,
            default: 921
        },
        /* 数据 */
        propData: {
            type: Object,
            default: () => {}
        },
        /* 颜色 */
        btnBgColor: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            // 浮层的宽度
            width: 0,
            // 最大高度
            maxHeight: 'auto',
            // 内容最大高度
            contentMaxHeight: 'auto',
            // 透明度
            opacity: 0,
            // 最外层隐藏或显示
            visibility: 'hidden',
            // 浮层的缩放
            scale: 1.17,
            // 接口数据
            data: {},
            // 头图
            topImg: '',
            // 背景色
            bgColor: '',
            // 活动列表
            cards: [],
            // 用户是否登录
            isLogin: 0,
            // 是否显示弹框
            show: false
        };
    },
    created() {
        this.calculateWidthHeight();
    },
    mounted() {
        if (this.propData) {
            const {head = {}, content = {}} = this.propData;
            this.topImg = head.img;
            this.cards = content.cards;
            Object.assign(this, {
                show: true,
                isLogin: 1,
                bgColor: content.bgColor,
                topImg: head.img,
                cards: content.cards || []
            });
        }
        else {
            this.initData();
        }
    },
    watch: {
        show(newVal, oldVal) {
            if (newVal) {
                this.visibility = 'visible';
                this.opacity = 1;
                this.scale = 1;
            }
            else {
                this.opacity = 0;
                setTimeout(() => {
                    this.visibility = 'hidden';
                    this.scale = 1.17;
                }, 300);
            }
        }
    },
    methods: {

        /**
         * 计算宽高
         */
        calculateWidthHeight() {
            let systemInfo = getSystemInfo();
            this.screenWidth = systemInfo.screenWidth;
            this.screenHeight = systemInfo.screenHeight;
            this.width = parseInt(this.screenWidth * .8, 10);
            this.maxHeight = parseInt(this.screenHeight * .55, 10);
            // 48 px 是底部按钮栏的高度
            this.contentMaxHeight = this.maxHeight - this.gapTop - 48;
        },

        handleMaskTap() {

            /**
             * 蒙层点击
             *
             * @event masktap
             */
            // this.$emit('masktap');

            /**
             * 关闭事件
             *
             * @event close
             */
            // this.$emit('close');
        },
        // 将当天0点和23点59分存入缓存中
        setTodayTime() {
            let startTime = new Date(new Date().toLocaleDateString()).getTime(); // 当天0点
            let endTime = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1; // 当天23:59
            this.$api.setStorage({
                key: 'todayTime',
                data: {
                    startTime: startTime,
                    endTime: endTime
                }
            });
        },
        initData() {
            request({
                url: conf.operateApihost + '/api/topic/topicpop?vn=med&topic=healthmonth',
                isNeedLogin: false,
                isFirstScreen: false
            }).then(res => {
                const data = res.data || {};
                if (data && Object.getOwnPropertyNames(data).length > 1) {
                    this.topImg = data.head && data.head.img || '';
                    this.bgColor = data.content && data.content.bgColor || '';
                    this.cards = data.content && data.content.cards || [];
                    this.isLogin = data.userInfo && data.userInfo.is_login || 0;
                    this.cards && this.cards.length && this.cards.map(item => {
                        if (item.reqUrl) {
                            request({
                                url: conf.apiHost + item.reqUrl,
                                isNeedLogin: true,
                                isFirstScreen: false
                            })
                                .then()
                                .catch(err => console.log(err));
                        }
                    });
                    const show = data.userInfo && data.userInfo.show;
                    const todayTime = this.$api.getStorageSync('todayTime') || false;
                    // show === 1 表示用户未领券可显示   todayTime 判断此用户当天没有弹过此框
                    const nowTime = new Date().getTime();
                    if (show === 1 && (!todayTime || nowTime > todayTime.endTime)) {
                        this.show = true;
                        this.setTodayTime();
                    }
                }
            });
        },
        onClose() {
            this.show = false;
            Log.send({
                type: 'b',
                action: 'click',
                extra: {
                    type: 'pop_close'
                }
            });
        },
        onTapStart(item) {
            if (process.env.MARS_ENV === 'h5') {
                if (this.isLogin !== 1) {
                    const todayTime = this.$api.getStorageSync('todayTime') || false;
                    todayTime && this.$api.removeStorageSync('todayTime');
                    login.toH5LoginPage({isReplaceUrl: true});
                }
                else {
                    this.jumpToPage(item);
                }
            }
        },
        jumpToPage(item) {
            this.show = false;
            if (item.tcUrl) {
                navToBdBoxH5(item.tcUrl);
            } else {
                navigate({
                    url: item.url
                });
            }
            Log.send({
                type: 'b',
                action: 'click',
                extra: {
                    type: item.ser
                }
            });
        }
    }
};
</script>

<style lang="less" scoped>
.dialog {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}
.dialog-inner {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.mask {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.4);
    transition: opacity .16s cubic-bezier(0, 0, .3, 1);
}
.wrap {
    // width: calc(100% - 55px);
    width: 85vw;
    border-radius: 11px;
    z-index: 1;
    .top-img {
        background-size: auto 100%;
        background-position: center;
        background-repeat: no-repeat;
        position: relative;
        border-top-left-radius: 11px;
        border-top-right-radius: 11px;
    }
    .content {
        padding: 14px 10px 10px 10px;
        border-bottom-left-radius: 11px;
        border-bottom-right-radius: 11px;
    }
    .list {
        max-height: 334px;
        overflow-y: scroll;
        border-radius: 8px;

    }
    .icon-wrap {
        position: relative;
        margin-top: 17px;
    }
    .icon-close {
        color: #fff;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
    }
}
.list-item {
    display: flex;
    padding: 10px;
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 10px;
    .flex-left, .flex-right {
        flex-shrink: 0;
    }
    .flex-center {
        width: calc(100% - 133px);
    }
    .flex-right {
        align-self: center;
        text-align: center;
    }
    &-img {
        width: 62px;
        height: 62px;
        border-radius: 6px;
    }
    &-name {
        font-family: PingFangSC-Medium;
        font-size: 17px;
        color: #333333;
        letter-spacing: 0;
        line-height: 21px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    &-text {
        font-family: PingFangSC-Regular;
        font-size: 12px;
        color: #999999;
        letter-spacing: 0;
        line-height: 17px;
        margin-top: 7px;
        max-height: 34px;
        overflow: hidden;
    }
    &-money {
        &-label {
            font-family: PingFangSC-Semibold;
            font-size: 12px;
            color: #ff6050;
            letter-spacing: 0;
            line-height: 17px;
        }
        &-value {
            font-family: DINCondensed-Bold;
            font-size: 30px;
            color: #ff6050;
            letter-spacing: 0;
            line-height: 36px;
        }
    }
    &-btn {
        background-image: linear-gradient(129deg, #6FD5F2 0%, #30CBF1 100%);
        border-radius: 15px;
        font-family: PingFangSC-Medium;
        font-size: 12px;
        color: #FFFFFF;
        letter-spacing: 0;
        padding: 1px 10px;
    }
}
</style>
