<template>
    <view class="brand-operate-day">
        <view class="title-img">
            <c-image
                has-compress
                :src="img"
                width="100%"
                height="100%"
                mode="widthFix"
                :extra="{column: 12}"
                :hack-white-stroke="false"
                :is-round="false"
            />
        </view>
        <view class="task-item-box c-gap-inner-top">
            <login-btn
                :disabled="isLogin"
                :z-index="10"
                @onLoginSuccess="$emit('getPageData')"
                @onTapEnd="onLoginBtnTapEnd"
            >
                <view
                    v-for="taskItem in taskList"
                    :key="taskItem.task || taskItem.id"
                    class="task-item"
                    @tap="
                        onTaskBtn({
                            url: taskItem.url,
                            taskItem,
                        })
                    "
                >
                    <view
                        class="item-left"
                        :class="'item-left-' + imgType"
                        :style="{
                            'background-image': 'url(' + taskItem.icon + ')'
                        } | imgCompress('background-image', {column: 2})"
                    />
                    <view class="item-content">
                        <view class="item-title c-line-clamp1 c-font-normal">{{ taskItem.title }}</view>
                        <view class="item-desc c-font-13 c-line-clamp1">
                            <!--  -->
                            <view
                                v-if="taskItem.gold"
                                class="rich-text c-inline"
                            ><text class="num">+{{ taskItem.gold }}</text></view>
                            <rich-text
                                v-if="taskItem.subTitle"
                                class="c-font-13 c-line-clamp1 c-inline"
                                :nodes="taskItem.subTitle"
                            />

                        </view>
                    </view>
                    <view class="item-right">
                        <view
                            class="item-btn c-font-normal"
                            :class="{
                                'item-btn-animate': btnAnimate && taskItem.btnAnimate,
                            }"
                            :style="{
                                backgroundColor: btnColor[taskItem.task],
                            }"
                        >
                            <template v-if="taskItem.status === 0">
                                <c-icon
                                    name="check"
                                    font-size="14px"
                                    style="color: #fff; font-weight: bold;"
                                />
                            </template>
                            <template v-else>{{ taskItem.btnText }}</template>
                        </view>
                        <rich-text
                            v-if="taskItem.daysText"
                            class="c-font-13"
                            :nodes="taskItem.daysText"
                        />
                    </view>
                </view>
            </login-btn>
        </view>
    </view>
</template>

<script>
/**
 * @file 每日打卡列表
 * @author mayifan02
 * @categories 业务组件
 * @tags [component]
 */
import CImage from '@components/common/image';
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import * as core from '../../../utils/core';
import {send} from '../../../utils/log';
import {navigate} from '../../../utils/navigate';
import LoginBtn from '@commonComponents/login-btn';
import * as login from '../../../utils/login';

export default {
    config: {
        component: true
    },
    options: {
        addGlobalClass: true
    },
    components: {
        CIcon,
        LoginBtn,
        CImage
    },
    created() {
        if (this.taskList && this.taskList.length > 0) {
            this.taskBtnText();
        }
    },
    props: {
        /**
         * 任务列表
         */
        taskList: {
            type: Array,
            required: true
        },
        /**
         * 图片类型
         */
        imgType: {
            type: String,
            default: 'normal'
        },
        /**
         * 屏幕宽度
         */
        screenWidth: {
            type: Number,
            required: true
        },
        /**
         * 顶部图片
         */
        img: {
            type: String,
            required: true
        },
        /**
         * 登陆状态
         */
        isLogin: {
            type: Boolean,
            required: true
        },
        /**
         * 按钮动画
         */
        btnAnimate: {
            type: Boolean,
            default: false
        }
    },
    data() {
        const isSwan = process.env.MARS_ENV === 'swan';
        return {
            isSwan,
            intervalIds: [],
            btnColor: {
                drink: '#37ce89',
                sleepearly: '#997ddf'
            }
        };
    },
    watch: {
        taskList(val) {
            if (val && val.length > 0) {
                this.taskBtnText();
            }
        }
    },
    lifetimes: {
        detached() {
            this.clear();
        }
    },
    pageLifetimes: {
        hide() {
            this.clear();
        }
    },
    methods: {
        onLoginBtnTapEnd() {
            if (!this.isSwan) {
                login.toH5LoginPage({
                    isReplaceUrl: true
                });
            }
        },
        // 处理按钮文本
        taskBtnText() {
            // 开启前先清除
            this.clear();
            this.taskList.forEach(taskItem => {
                if (taskItem.status === 0 || !taskItem.lastTime) { // 已完成, 或不需要倒计时
                    taskItem.btnAnimate = false;
                    return;
                }
                // 转换为毫秒级别的时间戳
                taskItem.lastTime *= 1000;

                if (Date.now() < taskItem.lastTime) { // 倒计时
                    let intervalId = setInterval(() => {
                        this.countDownCallback(taskItem, taskItem.lastTime, intervalId);
                    }, 1000);
                    this.intervalIds.push({
                        intervalId,
                        btnText: taskItem.btnText
                    });
                    this.countDownCallback(taskItem, taskItem.lastTime, intervalId);
                }
            });
        },
        // 倒计时回调函数
        countDownCallback(taskItem, futureDate, intervalId) {
            let timeDiff = futureDate - Date.now();
            taskItem.btnText = core.fmtCountDown(timeDiff / 1000);
            taskItem.btnAnimate = false;
            if (timeDiff < 1000) {
                let intervalObj = this.intervalIds.find(
                    item => item.intervalId === intervalId
                );
                clearTimeout(intervalObj.intervalId);
                taskItem.btnText = intervalObj.btnText;
                taskItem.btnAnimate = true;
            }
        },
        // 清空任务区域定时器
        clear() {
            this.intervalIds.forEach(item => {
                clearTimeout(item.intervalId);
            });
        },
        // 任务按钮点击
        onTaskBtn(args) {
            // 判断是否登陆
            if (!this.isLogin && !args.notLogin) {
                console.log('onTaskBtn');
                login.toH5LoginPage({
                    isReplaceUrl: true
                });
                return;
            }

            // 判断是否已经完成
            if (args.taskItem.btnStatus === 'done') {
                return;
            }

            // 按钮状态打点
            let status = '';
            if (args.taskItem.status === 0) { // 已完成
                status = 'success';
            } else if (Date.now() < args.taskItem.lastTime * 1000) { // 倒计时
                status = 'countDown';
            } else { // 正常状态
                status = 'normal';
            }

            send({
                type: 'b',
                action: 'navigate',
                extra: {
                    action: 'task-btn-click',
                    title: args.taskItem.task || args.taskItem.id,
                    status
                }
            });
            /* eslint-disable */
            this.isSwan && this.$api.reportAnalytics('center_task_btn', {
                center_task_name: args.taskItem.task || args.taskItem.id
            });

            const {id, type} = args.taskItem;
            const taskUrl = args.url;
            if (id === '1') { // 关注, 预留

            } else if (id === '2') { // 分享
                /**
                 * 分享
                 */
                this.$emit('sharePage', 'share', false, id);
            } else if (taskUrl.indexOf('pages/act/daka-center') !== -1) { // 浏览活动页
                /**
                 * 开启本页面的倒计时
                 */
                this.$emit('openActCountDown', id);
            } else if (type === 'browse') { // 浏览频道页
                navigate({
                    url: taskUrl + '&daka_task=' + id + '&daka_time=' + 15,
                    openType: taskUrl.indexOf('pages/gy/medstorehome') >= 0 ? 'relaunch' : 'navigate'
                });
            } else { // 普通跳转
                navigate({url: taskUrl});
            }
        }
    }
};
</script>
<style lang="less" scoped>
    @keyframes breathe {
        0% { transform: scale(.96); }
        25% { transform: scale(1); }
        50% { transform: scale(.96); }
        75% { transform: scale(1); }
        100% { transform: scale(.96); }
    }

    .brand-operate-day {
        margin: 0 10px;
        margin-top: 16px;
        box-shadow: 0px 0px 10px 0px rgba(120, 198, 227, 0.51);
        border-radius: 13px;
        margin-bottom: 14px;
        position: relative;

        .title-img {
            width: 100%;
            border-radius: 13px 13px 0 0;
            display: block;
        }
    }

    .task-item-box {
        border-radius: 13px;
        margin-top: -10px;
        background: #fff;
        padding: 0 7px;
        padding-top: 10px;
    }

    .task-item {
        height: 18.6vw;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #727272;
        position: relative;
        padding: 0 7px;

        .num {
            color: #f77171;
        }

        .item-left {
            background-repeat: no-repeat;
            background-size: 100% auto;
            background-position: left bottom;

            &-normal {
                width: 45px;
                height: 45px;
                margin-right: 10px;
            }

            &-large {
                width: 64px;
                height: 54px;
                margin-right: 4px;
            }
        }

        .item-content {
            flex: 1;
            box-sizing: border-box;
            font-size: 0.13rem;
            overflow: hidden;

            .item-title {
                color: #262626;
                font-size: 0.14rem;
                font-weight: 500;
            }
        }

        .item-right {
            display: flex;
            flex-direction: column;
            align-items: center;

            .item-btn {
                // padding: 0px 13px;
                width: 68px;
                text-align: center;
                border-radius: 12px;
                background-color: #0fb6fb;
                color: #fff;
                font-size: 0.14rem;

                &-animate {
                    animation: breathe 1s infinite;
                }
            }
        }

        &::after {
            content: '';
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 1px;
            background-color: #ebebeb;
            transform: scaleY(0.5);
        }

        &:last-child {
            &::after {
                height: 0;
                display: none;
            }
        }
    }

    .med-rich-text {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        font-size: 13px;
    }

    .rich-text {
        font-size: 13px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
</style>
