<template>
    <view class="activity-page">
        <van-sticky style="background: #fff">
            <!-- <view class="search-wrap">
                <van-search 
                    shape="round" 
                    :value="searchVal" 
                    placeholder="搜索您想要的商品名" 
                    @change="searchValChange" 
                    @search="onSearch" 
                    @clear="onClearSearch" 
                />
            </view> -->
            <view class="flex tabs-wrap" @click="tabChange">
                <view
                    :class="['tab-item', tabActive === '1' && 'tab-active']"
                    data-type="1"
                    >线上会议</view>
                <view
                    :class="['tab-item', tabActive === '3' && 'tab-active']"
                    data-type="3"
                    >线下沙龙</view>
            </view>
            <view class="flex status-wrap" @click="statusChange">
                <view
                    :class="[
                        'status-item',
                        statusActive === '1' && 'status-active',
                    ]"
                    data-status="1">本周预告
                </view>
                <view
                    :class="[
                        'status-item',
                        statusActive === '2' && 'status-active',
                    ]"
                    data-status="2">进行中
                </view>
                <view
                    :class="[
                        'status-item',
                        statusActive === '3' && 'status-active',
                    ]"
                    data-status="3">已结束
                </view>
            </view>
        </van-sticky>

        <view class="list" v-if="list.length > 0">
            <view
                class="global-list-card item"
                v-for="(item,index) in list"
                :key="item.activityId"
                @click="handleGoDetail(item.activityId)"
            >
                <view class="status-box status-before" v-if="item.activityState===1">未开始</view>
                <view class="status-box status-progress" v-if="item.activityState===2">进行中</view>
                <view class="status-box status-end" v-if="item.activityState===3">已结束</view>
                <view class="flex top">
                    <image class="avatar" :src="item.speakerHeadPic" mode="aspectFill"></image>
                    <view class="content">
                        <view class="flex icon-box">
                            <template v-if="item.firstActivityTypeId===3&&item.city">
                                <image src='../../static/position.png'></image>
                                <text>{{item.city}}</text>
                            </template>
                            <template v-if="item.firstActivityTypeId===1&&item.activityState===3&&item.hasPlayBack">
                                <image src='../../static/hf.png'></image>
                                <text>可回放</text>
                            </template>
                        </view>
                        <view class="van-ellipsis title">{{item.activityTypeName}}</view>
                        <view class="name">主讲：{{item.speaker}}</view>
                        <view class="time">{{ item.startTime | formatActivityTime(item.endTime) }}</view>
                    </view>
                </view>
                <view class="flex bot" v-if="item.activityState===1">
                    <view 
                        :class="!item.hasRemind&&'active'"
                        @click.stop="handleRemind(item,index)"
                    >
                        {{item.hasRemind?'取消提醒':'会议提醒'}}
                    </view>
                    <view 
                        :class="!item.registerState&&'active'" 
                        v-if="item.firstActivityTypeId===3"
                        @click.stop="handleRegister(item,index)"
                    >
                        {{item.registerState?'取消线下报名':'报名线下参会'}}
                    </view>
                </view>
            </view>
        </view>
        <van-empty description="暂无数据" v-else />

        <!-- 弹窗 -->
        <van-popup :show="pupData.show" @close="pupData.show=false" :close-on-click-overlay="false">
            <view class="global-pup">
                <view class="content">
                    <rich-text :nodes="pupData.content"></rich-text>
                </view>
                <view class="flex bot" v-if="pupData.type=='contact'">
                    <view @click="pupData.show=false" style="color:#A9AFB8">取消</view>
                    <view @click="handleCallPhone(pupData.mobile)">拨号</view>
                </view>
                <view class="flex bot" v-else-if="pupData.type=='apply'">
                    <view @click="pupData.show=false" style="color:#A9AFB8">取消</view>
                    <view @click="handleApply">立即申请</view>
                </view>
                <view class="flex bot" v-else>
                    <view @click="pupData.show=false">知道了</view>
                </view>
            </view>
        </van-popup>
    </view>
</template>

<script>
import { 
    apiActivityList,
    apiActivityAddRemind,
    apiActivityCancelRemind, 
    apiActivityRegister,
    apiActivityCancelRegister
} from '@/api/activity'
import {apiApplyPermission} from '@/api/user'
export default {
    watch: {
      'pupData.show':{
          handler(nval){
              if(!nval){
                this.pupData={
                    show:false,
                    content:'',//弹窗html字符串
                    type:'',
                    mobile:"",
                }
              }
          }
      }
    },
    data() {
        return {
            searchVal: '',
            tabActive: '1',
            statusActive: '1',

            page: 1,
            pageSize: 20,
            list: [],
            finished: false,

            pupData:{
                show:false,
                content:'',//弹窗html字符串
                type:'',
                mobile:"",
            }
        }
    },
    onLoad() {
        this.getList()
        this.addEventListenerRemind()
        this.addEventListenerRegister()
    },
    onShow() {
        if(this.$store.state.activity.activityListPageRefresh){
            this.allRefresh()
        }
    },
    onHide(){
        this.pupData.show=false
    },
    onUnload(){
		uni.$off('activityDetailSetRemind')
        uni.$off('activityDetailSetRegister')
	},
    onShareAppMessage(res) {
        return {
            title: '弘则研报',
            path: ''
        }
    },

    onPullDownRefresh() {
        this.refreshPage()
        setTimeout(() => {
            uni.stopPullDownRefresh()
        }, 1500)
    },

    onReachBottom() {
        if (this.finished) return
        this.page++
        this.getList()
    },

    methods: {
        // 切换tabbar页面时 整个刷新
        allRefresh(){
            this.tabActive= '1'
            this.statusActive='1'
            this.pupData={
                show:false,
                content:'',//弹窗html字符串
                type:'',
                mobile:"",
            }
            this.page = 1
            this.list = []
            this.finished = false
            this.getList()
        },

        // 监听详情中设置提醒
        addEventListenerRemind(){
            uni.$on('activityDetailSetRemind',e=>{
                this.list.forEach((item,index) => {
                    if(item.activityId==e.id){
                        this.handleUpateRemindStatus(index)
                    }
                });
            })
        },

        // 监听详情中报名
        addEventListenerRegister(){
            uni.$on('activityDetailSetRegister',e=>{
                this.list.forEach((item,index) => {
                    if(item.activityId==e.id){
                        this.handleUpdateRegister(index)
                    }
                });
            })
        },

        //搜索
        onSearch(){
            this.refreshPage()
            this.getList()
        },

        //清除搜索内容
        onClearSearch(){
            this.searchVal=''
            this.refreshPage()
            this.getList()
        },

        // 同步搜索关键词
        searchValChange(e){
            this.searchVal=e.detail
        },

        // 类型切换
        tabChange(e) {
            const type = e.target.dataset.type
            if (!type||type === this.tabActive) return
            this.tabActive = type
            this.statusActive = '1'
            this.refreshPage()
        },

        // 状态切换
        statusChange(e) {
            const status = e.target.dataset.status
            if (!status||status === this.statusActive) return
            this.statusActive = status
            this.refreshPage()
        },

        // 刷新页面
        refreshPage() {
            this.page = 1
            this.list = []
            this.finished = false
            this.getList()
        },

        handleGoDetail(id) {
            uni.navigateTo({
                url: '/pages-activity/detail?id=' + id
            });
        },

        async getList() {
            const res = await apiActivityList({
                title:this.searchVal,
                active_state: Number(this.statusActive),
                activity_type: Number(this.tabActive),
                page: this.page,
                limit: this.pageSize
            })
            if (res.code === 200) {
                if(res.data){
                  this.list = [...this.list, ...res.data]
                }else{
                  this.finished=true
                }
            }
        },

        handleRemind(e,index){    
            if(e.hasRemind===0){
                this.handleAddRemind(e,index)
            }else{
                this.handleCancelRemind(e,index)
            }
        },

        // 添加提醒
        async handleAddRemind(e,index){
            const res=await apiActivityAddRemind({activity_id:Number(e.activityId)})
            if(res.code===200){
                this.pupData.content=`<h4 style="text-align:center;margin-bottom:5px">设置成功</h4>
                                      <p>请关注【弘则研究】公众号，接收会前15分钟微信提醒，并及时获取活动信息变更通知</p>`
                this.pupData.show=true
                this.handleUpateRemindStatus(index)
            }else if(res.code===4001){
                if(res.data.type=='time'){
                    this.pupData.content=`<p style="margin-top:20px">会议开始前15分钟内无法设置会议提醒</p>`
                    this.pupData.type='time'
                }
                this.pupData.show=true
            }else if(res.code===403){
                if(res.data.type=='contact'){
                    if(!res.data.customer_info.has_apply){
                        if(res.data.customer_info.status=='冻结'||(res.data.customer_info.status=='试用'&&res.data.customer_info.is_suspend==1)){
                            apiApplyPermission({
                                company_name:res.data.customer_info.company_name,
                                real_name:res.data.customer_info.name,
                            }).then(res=>{
                                if(res.code===200){
                                    console.log('主动申请成功');
                                }
                            }) 
                        }
                    }
                    this.pupData.content=`<p>您暂无权限参加此会议，若想参加请联系对口销售--${res.data.name}：${res.data.mobile}</p>`
                    this.pupData.mobile=res.data.mobile

                }else if(res.data.type=='apply'){
                    this.pupData.content=`<p style="margin-top:20px">您暂无权限参加此会议，若想参加可以申请开通哦</p>`
                }
                this.pupData.show=true
                this.pupData={...this.pupData,...res.data}
            }
        },

        //取消提醒
        async handleCancelRemind(e,index){
            const res=await apiActivityCancelRemind({activity_id:Number(e.activityId)})
            if(res.code===200){
                uni.showToast({
                    title:"取消提醒成功",
                    icon:"none"
                })
                this.handleUpateRemindStatus(index)
            }else if(res.code===403){
                uni.showToast({
                    title:res.msg,
                    icon:"none"
                })
            }
        },

        //更新列表中某项的设置提醒状态
        handleUpateRemindStatus(index){
            if(this.list[index].hasRemind===0){
                this.list[index].hasRemind=1
            }else{
                this.list[index].hasRemind=0
            }
        },

        handleRegister(e,index){
            if(e.registerState===0){
                this.handleAddRegister(e,index)
            }else{
                this.handleCancelRegister(e,index)
            }
        },

        // 线下报名
        async handleAddRegister(e,index){
            const res=await apiActivityRegister({activity_id:Number(e.activityId)})
            if(res.code===200){
                this.pupData.content=`<h4 style="text-align:center;margin-bottom:5px">报名成功</h4>
                                      <p>请关注【弘则研究】公众号，接收会前1小时微信提醒，并及时获取活动信息变更通知</p>`
                this.pupData.show=true
                this.handleUpdateRegister(index)
            }else if(res.code===4001){
                if(res.data.type=='time'){
                    this.pupData.content=`<p style="margin-top:20px">活动开始前15分钟内无法设置会议提醒</p>`
                    this.pupData.type='time'
                }else if(res.data.type=='full'){
                    this.pupData.content=`<p style="margin-top:20px">此活动报名人数已满，请留意下期活动</p>`
                    this.pupData.type='full'
                }
                this.pupData.show=true
            }else if(res.code===403){
                if(res.data.type=='contact'){
                    if(!res.data.customer_info.has_apply){
                        if(res.data.customer_info.status=='冻结'||(res.data.customer_info.status=='试用'&&res.data.customer_info.is_suspend==1)){
                            apiApplyPermission({
                                company_name:res.data.customer_info.company_name,
                                real_name:res.data.customer_info.name,
                            }).then(res=>{
                                if(res.code===200){
                                    console.log('主动申请成功');
                                }
                            }) 
                        }
                    }
                    this.pupData.content=`<p>您暂无权限参加此活动，若想参加请联系对口销售--${res.data.name}：${res.data.mobile}</p>`
                    this.pupData.mobile=res.data.mobile
                }else if(res.data.type=='apply'){
                    this.pupData.content=`<p style="margin-top:20px">您暂无权限参加此活动，若想参加可以申请开通哦</p>`
                }
                this.pupData.show=true
                this.pupData={...this.pupData,...res.data}
            }
        },

        //取消线下报名
        async handleCancelRegister(e,index){
            const res=await apiActivityCancelRegister({activity_id:Number(e.activityId)})
            if(res.code===200){
                uni.showToast({
                    title:"取消报名成功",
                    icon:"none"
                })
                this.handleUpdateRegister(index)
            }else if(res.code===403){
                uni.showToast({
                    title:res.msg,
                    icon:"none"
                })
            }
        },

        // 更新报名状态
        handleUpdateRegister(index){
            if(this.list[index].registerState===0){
                this.list[index].registerState=1
            }else{
                this.list[index].registerState=0
            }
        },

        // 点击立即申请
        async handleApply(){
            if(this.pupData.customer_info.has_apply){//已经申请过
                this.pupData.content=`<p style="padding-top:20px">您已提交过申请，请耐心等待</p>`
                this.pupData.type=''
            }else{
                if(!this.pupData.customer_info.status||this.pupData.customer_info.status!='流失'){
                    uni.navigateTo({
                        url:"/pages-applyPermission/applyPermission"
                    })
                }else{//主动调一次申请权限接口 
                    const res=await apiApplyPermission({
                        company_name:this.pupData.customer_info.company_name,
                        real_name:this.pupData.customer_info.name,
                    })
                    if(res.code===200){
                        this.pupData.content=`<p>申请已提交</p><p>请等待销售人员与您联系</p>`
                        this.pupData.type=''
                    }
                }
            }
        },

        // 拨打电话
        handleCallPhone(tel){
            uni.makePhoneCall({
                phoneNumber: tel
            });
        }

    }
}
</script>

<style lang="scss">
.search-wrap {
    padding: 0 8rpx;
    background-color: $global-bg-color;
}
.tabs-wrap {
    background-color: $global-bg-color;
    box-shadow: $global-tab-shadow-color;
    align-items: center;
    text-align: center;
    font-size: $global-font-size-lg;
    color: $global-text-color-grey;
    position: relative;
    z-index: 10;
    .tab-item {
        flex: 1;
        height: 94rpx;
        line-height: 94rpx;
    }
    .tab-active {
        font-weight: bold;
        color: $global-text-color-main;
        border-bottom: 6rpx solid $global-text-color-main;
    }
}
.status-wrap {
    background-color: $global-bg-color;
    padding: 40rpx 34rpx 20rpx 34rpx;
    .status-item {
        font-size: $global-font-size-sm;
        color: #444;
        min-width: 167rpx;
        text-align: center;
        padding: 14rpx;
        border-radius: 40rpx;
        background-color: #f6f6f6;
        margin-right: 40rpx;
    }
    .status-active {
        background: linear-gradient(270deg, #efc896 0%, #d9a35f 100%);
        color: $global-bg-color;
    }
}

.list {
    padding: 34rpx;
    .item {
        position: relative;
        margin-bottom: 30rpx;
        .status-box {
            top: 0;
            right: 0;
            position: absolute;
            width: 132rpx;
            line-height: 44rpx;
            text-align: center;
            font-size: $global-font-size-sm;
            color: $global-text-color-white;
        }
        .status-before {
            background-color: #e3b377;
        }
        .status-progress {
            background-color: #3385ff;
        }
        .status-end {
            background-color: #a2a2a2;
        }
        .top {
            padding-top: 64rpx;
            padding-left: 30rpx;
            padding-right: 30rpx;
            padding-bottom: 42rpx;
            .avatar {
                width: 168rpx;
                height: 168rpx;
                border-radius: 50%;
                margin-right: 30rpx;
                flex-shrink: 0;
                border: 1px solid $global-border-color;
            }
            .title {
                font-size: $global-font-size-lg;
                font-weight: bold;
                width: 400rpx;
                padding-right: 80rpx;
                padding-bottom: 10rpx;
                border-bottom: 1px solid $global-border-color;
            }
            .name {
                color: $global-text-color-grey;
                margin: 20rpx 0;
            }
            .time {
                font-size: $global-font-size-sm;
                color: $global-text-color-999;
            }
        }
        .bot {
            border-top: 1px solid $global-border-color;
            color: $global-text-color-999;
            view {
                line-height: 72rpx;
                flex: 1;
                text-align: center;
                border-right: 1px solid $global-border-color;
            }
            view:last-child {
                border: none;
            }
            .active{
                color: #E3B377;
            }
        }
        .content{
            width: 420rpx;
            position: relative;
            .icon-box{
                align-items: center;
                position: absolute;
                right: 0;
                top: 8rpx;
                font-size: $global-font-size-sm;
                color:$global-text-color-main;
                image{
                    width: 26rpx;
                    height: 26rpx;
                }
            }
        }
    }
}
</style>