<template>
    <div>
        <div class="flex flex-mean" style="background-color: #FFFFFF; height: 150px;">
            <!-- <van-search class=".flex flex-1" v-model="searchValue" left-icon="" shape="round" placeholder="请输入搜索关键词" />
            <van-button round type="info" class="custom-button font-size13 m-top10 m-right12" @click="onSearch()">查询</van-button> -->
            <!-- <van-image src="../../assets/images/servicePhone/" /> -->
            <img src="../../assets/images/peoSuggestion/1.png" style="width: 100%; height:300px ;" />
        </div>
        <div class='container' style="position: relative;top: -35px;">
            <div class="flex flex-x flex-end">
                <img src="../../assets/images/peoSuggestion/special.png" style="width: 180px;"> 
                <img src="../../assets/images/peoSuggestion/daily.png"  style="width: 180px;">
            </div>
        </div>
        <div class='container' style="position: relative;top: -40px;">
            <div class="card">
                <div class="title">
                    <div class="flex flex-center2">
                        <img style="height:20px;" src="@/assets/images/home/biaoqian.png" alt="">
                        <span class="m-left5" style=" color: black;   font-family:pingfang-bold;
      font-size: 20px;">最新专题 </span>
                    </div>
                    <span @click="$router.push('/activity')">更多</span>
                 
                </div>
                <div class="activity_content flex m-top10" v-for="(item, index) in eventList" :key="index"
                    @click="$router.push({ path: `/discusionDetail`, query: { eventId: item.eventId } })">
                    <div class="flex flex-y flex1 flex-end" style="overflow: hidden;">
                        <span class="van-multi-ellipsis--l2">
                            {{ item.title }}
                        </span>
                        <div class="flex flex-end flex-end gray m-top10 font-size13">
                            <div class="flex flex-center">
                                <span>{{ item.total }} 人参与 </span>
                            </div>
                            <div class="flex flex-x">
                                <div class="flex flex-center">
                                    <span> {{ item.data }}</span>
                                </div>
                               
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class='container' style="position: relative;top: -50px;">
            <div class="card">
                <div class="title">
                    <div class="flex flex-center2">
                        <img style="height:20px;" src="@/assets/images/home/biaoqian.png" alt="">
                        <span class="m-left5" style=" color: black;   font-family:pingfang-bold;
      font-size: 20px;">金点子 </span>
                    </div>
                    <span @click="$router.push('/activity')">更多</span>
                 
                </div>
                <van-tabs v-model="tagActive" style="width: 100%;" @change="handelChangeTags" :title-style="titleStyle" title-class="custom-title-class">
                        <van-tab v-for="item in tagList" :key="item.id" :title="item.tagName">
                   
                        </van-tab>
                    </van-tabs>
                <div class="activity_content flex m-top10" v-for="(item, index) in eventList" :key="index"
                    @click="$router.push({ path: `/discusionDetail`, query: { eventId: item.eventId } })">
                    <div class="flex flex-y flex1 flex-end" style="overflow: hidden;">
                        <span class="van-multi-ellipsis--l2">
                            {{ item.title }}
                        </span>
                        <div class="flex flex-end flex-end gray m-top10 font-size13">
                            <div class="flex flex-center">
                                <span>{{ item.total }} 人参与 </span>
                            </div>
                            <div class="flex flex-x">
                                <div class="flex flex-center">
                                    <span> {{ item.data }}</span>
                                </div>
                               
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>

        <Android @send-number="handleNumber" />
    </div>

</template>

<script>
import { activitySignIn,activityApply,addActivityRecord,cancelSignUp1, detail, 
    communityActivityApplicationRecordDelete,getById,activityApplySave} from "@/api/activity"
import Share from "@/components/Share"
import registerDialog from '@/components/registerDialog';
import { setConfig } from '@/utils/jweixin'
import { Toast, Dialog } from 'vant'

export default {
    data() {
        return {
            titleStyle: {
        color: "#007FF1", // 自定义字体颜色
        fontSize: "16px", // 自定义字体大小
      },
            tagList:[{
                id:"1",
                tagName:"标签1"
            },
            {
                id:"2",
                tagName:"标签1"
            },
            {
                id:"3",
                tagName:"标签1"
            }],
            eventList:[{
                title:"70岁以上高龄老人补贴发放定在1月1日",
                total:1,
                data:"2000-00-00 13:00:00"
            },
            {
                title:"70岁以上高龄老人补贴发放定在1月1日",
                total:1,
                data:"2000-00-00 13:00:00"
            }],
            applyedTimeType:false,
            ActName:"",
            info: null,
            signInList: [],
            applyType: false,
            activityId: null,
            realTimeList: [],
            projectList: [],
            realTimeList:[],
            signInList:[],
            applyList:[],
            activityList: [],
            signUp: [
                { name: "", mobile: "", remark: "" },
            ],
            info: {},
            isPast: false,
            showShare: false,
            showRegister: false,
            phone:""
        };
    },
    created() {

    },
   async mounted() {

        setConfig(['updateAppMessageShareData', 'onMenuShareAppMessage', 'updateTimelineShareData'])
        if (this.$route.query.id) {
            this.activityId= this.$route.query.id
           await this.detail(this.$route.query.id)
           if(this.$route.query.flag === 'share'){
           await this.getById(this.$route.query.id)
           }
           await this.share()
           this.activityApplyList()
           this.activitySignIn(1)
           this.activitySignIn(0)
        }
    },
    methods: {
        toSign(e) {
            console.log(e.currentTarget.dataset, "e.currentTarget.dataset ");
            this.$router.push({ path: `/sing`, query: { id: this.activityId,type:e.currentTarget.dataset.type } });
            // wx.navigateTo({
            //     url: `/subpages/activity/pages/sign/sign?activityId=${this.data.activityId}&type=${e.currentTarget.dataset.type}&latitude=${e.currentTarget.dataset.latitude}&longitude=${e.currentTarget.dataset.longitude}`,
            // })
        },
        //取消报名
      cancelSignUp() {
        Dialog.confirm({
  title: '标题',
  message: '弹窗内容',
})
  .then(() => {
        console.log("用户点击了确认");
        
        cancelSignUp1(this.activityId).then(res => {
          console.log(res, "取消报名返回结果");
          if (res.code === 0) {
            this.applyType = true; // 更新报名状态
            this.$toast.success("取消报名成功"); // 提示成功信息
          } else {
            this.$toast.fail(res.message || "取消报名失败");
          }
        })
  })
  .catch(() => {
       console.log("取消");
  });
    //         Dialog.confirm({
    //             title: '提示',
    //             message: '确定取消报名吗？',
    //         })
    // .then(() => {  
    //   // 用户点击了确认
    //   console.log("用户点击了确认");
    //   cancelSignUp1(this.data.activityId)
    //     .then(res => {
    //       console.log(res, "取消报名返回结果");
    //       if (res.code === 0) {
    //         this.applyType = true; // 更新报名状态
    //         this.$toast.success("取消报名成功"); // 提示成功信息
    //       } else {
    //         this.$toast.fail(res.message || "取消报名失败");
    //       }
    //     })
    //     .catch(error => {
    //       console.error("取消报名接口调用失败", error);
    //       this.$toast.fail("网络错误，请稍后重试");
    //     })
    //     .finally(() => {
    //       // 隐藏 loading 状态
    //     });
    // })
    // .catch(() => {
    //   // 用户点击了取消
    //   console.log("用户点击了取消");
    // });
        },
        //报名
        toApply() {
            console.log("dsklfjklsf");
            Dialog.confirm({
                    title: '提示',
                    message: '您确定要报名吗？',
                })
                    .then(() => {
                        activityApplySave(this.activityId).then(res => {
                            console.log(res,"sdflkjlsfjd");
                            Dialog.alert({
                                // title: '吧',
                                message: '报名成功',
                            })
                            // wx.showToast({
                            //     title: '报名成功',
                            //     duration: 2000,
                            //     success: () => {
                            //         setTimeout(() => {
                            //             wx.navigateBack()
                            //         }, 2000)
                            //     }
                            // })
                        }).catch(err => {
                            console.log(err);
                        })
                    })
                    .catch(() => {
                        // on cancel
                    });
                        
        },
        share() {
           let than = this
            if (wx.updateAppMessageShareData) {
                wx.ready(function () {
                    wx.updateAppMessageShareData({
                        title: than.info.activityName || '活动详情',
                        desc: '',
                        link: `https://epmet-preview.elinkservice.cn/epmet-wx-pa/#/activityDetail?id=${than.$route.query.id}&appId=${than.$store.state.app.appId}&flag=share`,
                        imgUrl: than.info.coverPic || 'https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet/test/20240710/617f7fb327064d89892823b81b11cd70.png',
                        success: function () {}
                    })
                    wx.updateTimelineShareData({ 
                        title: than.info.activityName,
                        desc: '',
                        link: `https://epmet-preview.elinkservice.cn/epmet-wx-pa/#/activityDetail?id=${than.$route.query.id}&appId=${than.$store.state.app.appId}`,
                        imgUrl: than.info.coverPic || 'https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet/test/20240710/617f7fb327064d89892823b81b11cd70.png',
                        success: function () {}
                    })
                });
            } else {
                wx.onMenuShareAppMessage({
                    title: than.info.activityName,
                    desc: '',
                    link: `https://epmet-preview.elinkservice.cn/epmet-wx-pa/#/activityDetail?id=${than.$route.query.id}&appId=${than.$store.state.app.appId}`,
                    imgUrl: than.info.coverPic || 'https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet/test/20240710/617f7fb327064d89892823b81b11cd70.png',
                    success: function () {}
                })
            }
        },
        //获取打卡信息
        activitySignIn(whether) {
            let parm = {
                pageNo: 1,
                pageSize: 100,
                activityId: this.activityId,
                whether: whether
            }
            activitySignIn(parm).then(res => {
                if (res.code === 0) {
                    if (whether === 1) {
                            this.signInList=res.data.list
                
                    } else {
                            this.realTimeList=res.data.list
    

                    }
                }
            }).catch(err => {

            })
        },
        //获取报名志愿者
        activityApplyList() {
            let parm = {
                pageNo: 1,
                pageSize: 100,
                activityId: this.activityId
            }
            activityApply(parm).then(res => {
                if (res.code === 0) {
  
                       this.applyList=res.data.list
             
                }
            }).catch(err => {

            })
        },        
        handleNumber(value){
            console.log(value,"wl kgnsl, ");
            this.phone=value
        },
        checkIfPast() {
            const currentTimestamp = Date.now();
            const specifiedTimestamp = new Date(this.info.cutOffTime.replace(/-/g, '/')).getTime();
            this.isPast = specifiedTimestamp < currentTimestamp;
        },
        //获取信息
        async detail(id, delId) {
            const handleResponse = (res) => {
                if (res.code === 0) {
                this.info = res.data;
                this.info.signInTime=res.data.signInTime.slice(0, 16), 
                this.info.signOutTime=res.data.signOutTime.slice(0, 16),
                console.log(this.info,"wl info");
                // this.applyType = res.data.applyed === 0 ? true : false,
                this.applyedTimeType = this.isCurrentTimeBefore(res.data.deadline),
                console.log(this.applyedTimeType,"sdfkjdskfl");
                
                this.signOutTimeType = this.isCurrentTimeBetween(res.data.signInTime, res.data.signOutTime)
                // this.info.participants = res.data.participants;
                // this.info.currentParticipants = res.data.currentParticipants;
                // if (res.data.recordList && res.data.recordList.length > 0) {
                //     this.signUp = res.data.recordList;
                // }
                // if (res.data.cutOffTime) {
                //     this.checkIfPast();
                // }
                }
            };
            // if (delId) {
            //     this.signUp = this.signUp.filter(item => item.id != delId);
            // }
            let res = await detail(id);
            handleResponse(res);
        },
        async getById(id) {
            const handleResponse = (res) => {
                if (res.code === 0) {
                this.info = res.data;
                this.info.participants = res.data.participants;
                this.info.currentParticipants = res.data.currentParticipants;
                if (res.data.recordList && res.data.recordList.length > 0) {
                    this.signUp = res.data.recordList;
                }
                if (res.data.cutOffTime) {
                    this.checkIfPast();
                }
                }
            };
            if (delId) {
                this.signUp = this.signUp.filter(item => item.id != delId);
            }
            
            let res = await getById(id);
            handleResponse(res);
        },
        handelAddResi() {
            this.signUp.push({ name: "", mobile: "", remark: "", })
        },
        isCurrentTimeBetween(startTime, endTime) {
    const current = new Date().getTime();
    const startTimestamp = new Date(startTime).getTime();
    const endTimestamp = new Date(endTime).getTime();
    return current >= startTimestamp && current <= endTimestamp;
  },
        isCurrentTimeBefore(targetTime) {
            const current = new Date().getTime();
            const targetTimestamp = new Date(targetTime).getTime();
            return current < targetTimestamp;
        },
        handelDelResi(item, index) {
            if (item.id) {
                let than = this
                communityActivityApplicationRecordDelete([item.id]).then(res => {
                    if (res.code === 0) {
                        than.detail(this.$route.query.id, item.id);
                    }
                }).catch(err => {
                    console.log(err);
                })
            } else {
                this.signUp.splice(index, 1)
            }
        },
        async save() {
            if (this.$store.state.app.userInfo.mobile) {
                this.signUp.forEach((item) => {
                    item.activityId = this.info.id;
                    item.applicationId = this.$store.state.app.userInfo.id;
                    item.customerId = this.$store.state.app.userInfo.customerId;
                })
                if(this.signUp.findIndex(item=>!item.name) != -1){
                    this.$toast('人员姓名不能为空')
                    return 
                }
                if(this.signUp.findIndex(item=>!item.mobile) != -1){
                    this.$toast('联系电话不能为空')
                    return 
                }
                let parm = {
                    formDTOList: this.signUp
                }
                let res = await addActivityRecord(parm)
                if (res.code === 0) {
                    this.$toast.success(res.data)
                    this.signUp = [{ name: "", mobile: "", remark: "" }]
                    this.detail(this.$route.query.id)
                }
            } else {
                this.showRegister = true;
            }

        },
    },
    components: { Share, registerDialog },
    computed: {
        disabledRecord() {
            return (item) => {
                if (!item.cutOffTime || item.online != 1) return true
                let flag = new Date(item.cutOffTime.replace(/-/g, '/')).getTime() < Date.now() || item.currentParticipants >= item.participants  || item.currentParticipants >= item.participants;
                return flag || false
            }
        },
    },
    watch: {},
}
</script>

<style lang='less' scoped>
.phone{
    height: 50px;
    bottom:8vh;
}
:deep img{
    max-width: 100%;
}
:deep(.p0>.van-cell) {
    padding: 0;
}

:deep(.van-cell) {
    padding: 16px 8px;
}

:deep(.van-cell__title) {
    color: #666666;
    display: flex;

    &>span {
        flex: 1;
    }
}

:deep(.van-cell__value) {
    text-align: left;
}

:deep(.van-cell--required) {
    &::before {
        left: -5px;
    }
}
.activity_content{
    padding-bottom: 15px;
    box-sizing: border-box;
    width: 100%;
    border-bottom: 1px solid #EAEAEA;
    margin-top: 14px;
    .img{
        width: 231px;
        height: 33px;
    }
    &:last-child{
        border-bottom: none;
    }
}
/* 基础标签样式 */
::v-deep .custom-title-class {
  border: 1px solid #007FF1;    /* 设置边框颜色 */
  border-radius: 16px;          /* 圆角边框 */
  padding: 4px 12px;            /* 内边距 */
  background-color: transparent; /* 默认背景透明 */
  color: #007FF1;               /* 默认文字颜色 */
  font-size: 14px;
}

/* 激活状态的标签样式 */
::v-deep .van-tab--active .custom-title-class {
  background-color: #e6f2ff;    /* 激活背景色 */
  color: #007FF1;               /* 激活文字颜色 */
  font-weight: bold;            /* 加粗字体 */
}
</style>
