<template>
  <view class="navbox">
    <view class="status_bar"></view>
    <uni-nav-bar
    title="肝胆会议"
    :left-icon="from?'left':''"
    @clickLeft="goBack"
    color="#8B2316"
    :border="false"
    backgroundColor="#eee"
  >
    <template #right>
      <view class="nav-right" >
        <view class="scan-btn" @click="handleScanCode">
          扫一扫
          <!-- <uni-icons
            type="scan"
            size="24"
            color="#8B2316"
          ></uni-icons> -->
        </view>
        <!-- <uni-icons
          type="scan"
          size="24"
          color="#8B2316"
          @click="handleScanCode"
        ></uni-icons> -->
      </view>
    </template>
  </uni-nav-bar>
  </view>
  <view class="page">
    <!-- 筛选标签栏 -->
    <view class="filter-bar">
      <view
        class="filter-item"
        :class="{ active: monthName }"
        @click="showTimePopup"
      >
        <text>{{ monthName ? monthName : "会议时间" }}</text>
        <up-image
          :src="monthName ? selectOn : select"
          width="26rpx"
          height="26rpx"
        ></up-image>
      </view>
      <view class="filter-divider"></view>
      <view
        class="filter-item"
        @click="showLocationPopup"
        :class="{ active: provinceName }"
      >
        <text>{{ provinceName ? provinceName : "会议地点" }}</text>
        <up-image
          :src="provinceName ? selectOn : select"
          width="26rpx"
          height="26rpx"
        ></up-image>
      </view>
      <view class="filter-divider"></view>
      <view class="filter-item" @click="goLiveReplay">
        <text>会议回放</text>
      </view>
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view
      ref="scrollView"
      class="scroll-content"
      :class="{'active':from}"
      scroll-y="true"
      refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      :refresher-threshold="100"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
      :lower-threshold="100"
      :scroll-top="scrollTop"
      :enable-back-to-top="true"
    >
      <!-- 时间标题 -->

      <!-- 会议列表 -->
      <view class="meeting-list" v-if="meetingList.length > 0">
        <template
          v-for="(group, groupIndex) in groupedMeetings"
          :key="groupIndex"
        >
          <view class="time-header">{{ group.monthYear }}</view>
          <view
            class="meetcell"
            v-for="(item, index) in group.items"
            :key="item.id || index"
           
          >
            <view class="meeting-item">
              <!-- 左侧日期标识 -->
              <view
                class="date-tag"
                :style="{ backgroundColor: formatTagColor(index) }"
              >
                <text class="date-text" :style="{ color: formatTagColor(index) }">{{ formatDay(item.begin_date) }}</text>
              </view>

              <!-- 会议内容 -->
              <view class="meeting-content">
                <view class="meeting-title"   @click="goDetail(item)">{{ item.title }}</view>
                <view
                  class="meeting-poster"
                  @click.stop="playVideo(item)"
                  v-if="item.liveimg && item.status_code!=0"
                >
                  <up-image
                      :src="docUrl + item.liveimg"
                      class="poster-image"
                    mode="aspectFill"
                    :loadingIcon="lazyImg"
                    :errorIcon="lazyImg"
                   :lazy-load="true"
                    width="100%"
                    height="320rpx"
                    :data-item-id="item.id"
                  >
                  <template #error>
                   <image :src="lazyImg" class="poster-image" mode="aspectFill"></image>
	              </template>
                </up-image>
                  <view class="play-btn" v-if="item.status_code==1 || item.status_code==2 || item.status_code==4">
                    <up-image
                      :src="playImg"
                      width="108rpx"
                      height="108rpx"
                    ></up-image>
                  </view>
                  <view
                    class="status-tag"
                    :class="getStatusClass(item.status_code)"
                  >
                    {{ item.status }}
                  </view>
                </view>
                <view class="meeting-info">
                  <view class="info-item">
                    <view class="timebox">
                      <up-image
                        :src="timeImg"
                        width="24rpx"
                        height="24rpx"
                      ></up-image>
                    </view>
                    <text class="info-text">{{
                      formatDate(item.begin_date, "YYYY.MM.DD")
                    }}</text>
                    <text
                      class="info-text"
                      v-if="
                        formatDate(item.end_date, 'YYYY.MM.DD') !=
                        formatDate(item.begin_date, 'YYYY.MM.DD')
                      "
                      >{{ "-" + formatDate(item.end_date, "YYYY.MM.DD") }}</text
                    >
                  </view>
                  <view class="info-item">
                    <uni-icons
                      type="location"
                      size="14"
                      color="#999"
                    ></uni-icons>
                    <text class="info-text">{{ item.location }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </template>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-else-if="!isRefreshing">
        <empty></empty>
      </view>

      <!-- 加载更多提示 -->
      <view class="load-more" v-if="showLoadMore">
        <view class="load-more-content" v-if="isLoadingMore">
          <uni-icons type="spinner-cycle" size="20" color="#999"></uni-icons>
          <text class="load-more-text">加载中...</text>
        </view>
        <view
          class="load-more-content"
          v-else-if="hasMoreData && meetingList.length > 0"
        >
          <text class="load-more-text">上拉加载更多</text>
        </view>
        <view
          class="load-more-content"
          v-else-if="meetingList.length > 0 && !isLoadingMore"
        >
          <text class="load-more-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 时间选择弹窗 -->
    <view class="time-popup" v-if="isTimePopupShow" @click="hideTimePopup">
      <view class="popup-mask"></view>
      <view class="time-popup-content" @click.stop>
        <view class="time-list">
          <view
            class="time-item"
            v-for="(month, index) in monthList"
            :key="index"
            :class="{ active: selectedMonth === month.value }"
            @click="selectMonth(month)"
          >
            <text>{{ month.label }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 地区选择弹窗 -->
    <view
      class="location-popup"
      v-if="isLocationPopupShow"
      @click="hideLocationPopup"
    >
      <view class="popup-mask"></view>
      <view class="popup-content" @click.stop>
        <view class="location-grid">
          <view
            class="location-item"
            v-for="(province, index) in provinceList"
            :key="index"
            :class="{ active: selectedProvince === province.code }"
            @click="selectProvince(province)"
          >
            <text>{{ province.name }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 过往会议提示 -->
    <view class="history-tip" @click="goToMeetHistroy">
       <up-image :src="historyImg" width="161rpx" height="84rpx"></up-image>
    </view>

    <!-- 底部导航栏 -->
    <CustomTabbar v-if="!from"></CustomTabbar>
    <topTip ref="topTipRef" title="相机权限使用说明" content="“肝胆相照”想使用您的相机和访问您的媒体，用于帮助您进行后续的扫码活动"></topTip>
  </view>
</template>

<script setup>
import { ref, nextTick, computed } from "vue";
import { onShow,onReady,onBackPress,onUnload,onLoad} from "@dcloudio/uni-app";
import CustomTabbar from "@/components/tabBar/tabBar.vue";
import api from "@/api/api.js";
import select from "@/static/triangle_normal.png";
import selectOn from "@/static/triangle_green_theme.png";
import playImg from "@/static/bofang.png";
import timeImg from "@/static/play_long.png";
import docUrl from "@/utils/docUrl";
import historyImg from "@/static/meetHis.png";
import dayjs from "dayjs";
import navTo from "@/utils/navTo.js";
import empty from "@/components/empty/empty.vue";
import navBar from "@/components/navBar/navBar.vue";
import { encryptAesEcb, decryptAesEcb } from "@/utils/aesEcb.js";
import { getCameraPermission } from "@/utils/permission.js";
import topTip from "@/components/topTip/topTip.vue";
import lazyImg from "@/static/default_news_iv.png";
import isAndroid from "@/utils/platform.js";
// 弹窗状态
const isTimePopupShow = ref(false);
const isLocationPopupShow = ref(false);
const selectedMonth = ref("");
const monthName = ref("");
const selectedProvince = ref("");
const provinceName = ref("");
import OTHER_HOST from '@/utils/otherHost.js';
// 下拉刷新和上拉加载状态
const isRefreshing = ref(false);
const isLoadingMore = ref(false);
const hasMoreData = ref(true);
const showLoadMore = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const scrollTop = ref(0);
const permissionListener=ref(null);
const topTipRef=ref(null);
const from=ref('');
const goToMeetHistroy = () => {
  navTo({
    url: "/pages_app/meetHistroy/meetHistroy",
  });
};

onUnload (() => {
  permissionListener.value?.stop();
});
 onLoad((options)=>{	
  if(options.from){
    from.value=options.from;
  }
	// #ifdef APP-PLUS
  uni.sendNativeEvent("portraitReport",{
                  msg:{
                event_nickname: "list_page",
                page_type: "会议直播",
            },
            },
            (ret) => {
            console.log(ret);
            });
   permissionListener.value=uni.createRequestPermissionListener();
   console.log('放在onLoad执行');
   console.log(permissionListener.value);
   permissionListener.value.onRequest((res)=>{
	    console.log("onRequest");
	  if(res.includes("android.permission.CAMERA")){
		  topTipRef.value?.open();
	  }
   }).catch((err)=>{
    console.log("onRequest error");
    console.log(err);
   });
   permissionListener.value.onComplete((res)=>{
	  console.log("onComplete");
    console.log(res);
    if(res.includes("android.permission.CAMERA")){
		  topTipRef.value?.close();
	  }
   }).catch((err)=>{
    console.log("onComplete error");
    console.log(err);
   });
   // #endif
})


// 月份数据
// 生成月份列表
const monthList = ref([]);
const generateMonthList = () => {
  const months = [];
  let index = -1;
  const currentDate = new Date();
  const currentMonth = currentDate.getMonth() + 1; // 当前月份 (1-12)
  const currentYear = currentDate.getFullYear();

  // 添加"所有"选项
  months.push({ value: "", label: "所有" });

  // 从当前月份到12月
  for (let month = currentMonth; month <= 12; month++) {
    index++;
    let monthLabel = "";
    if (month === currentMonth) {
      monthLabel = `${month}月`;
    } else if (month === currentMonth + 1) {
      monthLabel = `${month}月`;
    } else {
      monthLabel = `${month}月`;
    }

    months.push({
      value: index,
      label: monthLabel,
      year: currentYear,
      month: month,
    });
  }

  // 从1月到当前月份（不包括当前月份，避免重复）
  for (let month = 1; month < currentMonth; month++) {
    index++;
    months.push({
      value: index,
      label: `${month}月`,
      year: currentYear + 1, // 下一年的月份
      month: month,
    });
  }

  monthList.value = months;
  console.log("生成的月份列表:", monthList.value);
};
const goDetail = (item) => {
  console.log(item);
  // uni.sendNativeEvent('noticeBack', {
  //   msg: 'go'
  // }, ret => {
  //   console.log('ret数据');
  //   console.log(ret);
  // })
  const encoded = encodeURIComponent(item.path);
  let imgPath=encodeURIComponent('https://doc.igandan.com/app/html/img/2016/20160714132557.png');
  uni.navigateTo({
    url: `/pages_app/webview/webview?url=${encoded}&sharetitle=${item.title}&bg=1&type=live_yugao&imgPath=${imgPath}&share=1&title=会议详情&tags=${item.tags}`,
  });
};
const goBack = () => {
  if(from.value){
    uni.navigateBack();
  }
};
 onBackPress(() => {
  if(!from.value){
    try{
			uni.sendNativeEvent('goTabbarPage', {
			msg: 'home'
		},ret => {
			console.log(ret);
		})
		}catch(e){
			console.log(e);
		}
    plus.runtime.quit()
    return true;
  }
})
const sendWebsocketMsg = (code) => {
  let userInfo = uni.getStorageSync("userInfo");
  let str ="liveScanSuccess}"+code+"}"+userInfo.uuid+","+userInfo.realName+","+userInfo.photo;
  let message = encryptAesEcb(str, "deoep09_klodLdAo");
  uni.request({
    url: OTHER_HOST+'/watchlive/sendWebsocketMsg', 
	method: 'POST',
    data: {
		message: message,
    },
    header: {
     'Content-Type':'application/x-www-form-urlencoded'//自定义请求头信息
    },
    success: (res) => {
      console.log(res);
  	if(res.data.code==1){
  		navTo({
  			url: '/pages_app/scanLogin/scanLogin?code='+code
  		});
  	}else{
		uni.showToast({
			title: res.data.message,
			icon: 'none'
		});
	}
    },
  });
  // api.sendWebsocketMsg({
  // 	message:message
  // }).then(res=>{
  // 	console.log(res);
  // 	if(res.code==1){
  // 		navTo({
  // 			url: '/pages_app/scanLogin/scanLogin?code='+code
  // 		});
  // 	}
  // }).catch(err=>{
  // 	console.log(err);
  // });
};
const  handleScanCode = () => {
   if(isAndroid){
     getCameraPermission(scanCode);
   }else{
    console.log('ios执行');
    uni.sendNativeEvent('getScanCodeAuth', {
			msg: 'getScanCodeAuth'
		}, ret => {
      console.log('getScanCodeAuth回调数据');
      console.log(ret);
       if(ret.code==200){
         scanCode()
       }else{
        uni.showToast({
          title: '请在iPhone的"设置-隐私-相机"中允许肝胆相照专家端访问相机',
          icon: 'none'
        });
       }
		})
   }
}
const scanCode = () => {
  uni.scanCode({
    onlyFromCamera: true,
    success: (result) => {
      console.log(result);
      if (result.result) {
        let data = decryptAesEcb(result.result, "deoep09_klodLdAo");
        console.log(data);
        if (data.indexOf("watchvideoFrom") > -1) {
          let code = data.split(":")[1];
          sendWebsocketMsg(code);
        } else {
          uni.showToast({
            title: "您扫描的不是有效的肝胆相照平台二维码",
            icon: "none",
            duration: 2000,
          });
        }
      }
    },
  });
};
// 省份数据
const provinceList = ref([
  { code: "", name: "全国" },
  { code: "北京", name: "北京市" },
  { code: "天津", name: "天津市" },
  { code: "河北", name: "河北省" },
  { code: "山西", name: "山西省" },
  { code: "内蒙古", name: "内蒙古自治区" },
  { code: "辽宁", name: "辽宁省" },
  { code: "吉林", name: "吉林省" },
  { code: "黑龙江", name: "黑龙江省" },
  { code: "上海", name: "上海市" },
  { code: "江苏", name: "江苏省" },
  { code: "浙江", name: "浙江省" },
  { code: "安徽", name: "安徽省" },
  { code: "福建", name: "福建省" },
  { code: "江西", name: "江西省" },
  { code: "山东", name: "山东省" },
  { code: "河南", name: "河南省" },
  { code: "湖北", name: "湖北省" },
  { code: "湖南", name: "湖南省" },
  { code: "广东", name: "广东省" },
  { code: "广西", name: "广西壮族自治区" },
  { code: "海南", name: "海南省" },
  { code: "重庆", name: "重庆市" },
  { code: "四川", name: "四川省" },
  { code: "贵州", name: "贵州省" },
  { code: "云南", name: "云南省" },
  { code: "西藏", name: "西藏自治区" },
  { code: "陕西", name: "陕西省" },
  { code: "甘肃", name: "甘肃省" },
  { code: "青海", name: "青海省" },
  { code: "宁夏", name: "宁夏回族自治区" },
  { code: "新疆", name: "新疆维吾尔自治区" },
  { code: "台湾", name: "台湾省" },
  { code: "香港", name: "香港特别行政区" },
  { code: "澳门", name: "澳门特别行政区" },
]);
const goLiveReplay = () => {
  navTo({
    url: "/pages_app/liveReplay/liveReplay",
  });
};
// 会议列表数据
const meetingList = ref([]);

// 按年月分组的会议列表
const groupedMeetings = computed(() => {
  if (!meetingList.value || meetingList.value.length === 0) {
    return [];
  }

  const groups = {};

  meetingList.value.forEach((item) => {
    const monthYear = formatDate(item.begin_date, "YYYY年MM月");

    if (!groups[monthYear]) {
      groups[monthYear] = {
        monthYear: monthYear,
        items: [],
      };
    }

    groups[monthYear].items.push(item);
    console.log(groups);
  });

  // 转换为数组并按时间排序
  return Object.values(groups).sort((a, b) => {
    // 按年月排序
    const dateA = dayjs(a.items[0].begin_date);
    const dateB = dayjs(b.items[0].begin_date);
    return dateA.isBefore(dateB) ? -1 : 1;
  });
});

// 页面显示时获取会议列表数据
onShow(() => {
   currentPage.value = 1;
   hasMoreData.value = true;
    meetingList.value = [];
   selectedMonth.value = '';
   monthName.value = '';
    selectedProvince.value = '';
    provinceName.value = '';
  generateMonthList();
  getMeetingList(true);
});

const meetingListBySearch = async (isRefresh = false) => {
  if (isRefresh) {
    currentPage.value = 1;
    hasMoreData.value = true;
    meetingList.value = [];
  }

  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    month: selectedMonth.value,
    location: selectedProvince.value,
    status: "",
  };

  try {
    console.log("获取会议列表参数:", params);
    const response = await api.meetingListBySearch(params);
    console.log("会议列表API响应:", response);

    if (response && response.code == 1 && response.data) {
      const { list, totalPage, pageNumber, totalRow } = response.data;

      console.log("解析后的数据:", { list, totalPage, pageNumber, totalRow });

      if (Array.isArray(list) && list.length > 0) {
        // 处理会议数据，根据实际API数据结构映射字段
        const processedItems = list.map((item) => {
          // 解析开始日期，提取日期部分用于显示
          const beginDate = dayjs(item.begin_date);
          const day = beginDate.format("DD");

          // 根据状态确定标签颜色
          const tagColor = getTagColor(item.status);

          // 格式化时间显示
          const timeStr = formatDate(item.begin_date, "YYYY.MM.DD");

          return {
            id: item.id,
            begin_date: day, // 用于左侧日期标识显示
            tagColor: tagColor,
            title: item.title,
            liveimg: item.liveimg,
            poster: item.liveimg, // 使用 liveimg 作为海报
            time: timeStr,
            location: item.location || "线上",
            tags: item.tags || '',
            status: getStatusText(item.status),
            // 保留原始数据用于其他功能
            originalData: item,
            begin_date_timestamp: item.begin_date_timestamp,
            end_date_timestamp: item.end_date_timestamp,
            begin_date: item.begin_date,
            end_date: item.end_date,
            liveurl: item.liveurl,
            spareurl: item.spareurl,
            path: item.path,
            status_code: item.status,
          };
        });

        if (isRefresh) {
          meetingList.value = processedItems;
        } else {
          meetingList.value.push(...processedItems);
        }

        // 更新分页状态
        hasMoreData.value = totalPage > pageNumber;
        showLoadMore.value = totalRow > 0;

        console.log("会议列表更新成功，当前总数:", meetingList.value.length);
        console.log("分页信息:", {
          currentPage: currentPage.value,
          totalPage,
          pageNumber,
          totalRow,
          hasMore: hasMoreData.value,
        });
      } else {
        console.log("API返回的数据为空");
        if (isRefresh) {
          meetingList.value = [];
        }
      }
    } else {
      console.log("API响应格式不正确:", response);
      if (isRefresh) {
        meetingList.value = [];
      }
    }
  } catch (error) {
    console.error("获取会议列表失败:", error);
    if (isRefresh) {
      meetingList.value = [];
    }
    uni.showToast({
      title: "获取会议列表失败",
      icon: "error",
      duration: 2000,
    });
  }
};
// 获取会议列表数据的函数
const getMeetingList = async (isRefresh = false) => {
  if (isRefresh) {
    currentPage.value = 1;
    hasMoreData.value = true;
    meetingList.value = [];
  }

  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    month: selectedMonth.value,
    location: selectedProvince.value,
  };

  try {
    console.log("获取会议列表参数:", params);
    const response = await api.meetingListV2U(params);
    console.log("会议列表API响应:", response);

    if (response && response.code === 200 && response.data) {
      const { list, total, pageNum, pages, isLastPage } = response.data;

      console.log("解析后的数据:", { list, total, pageNum, pages, isLastPage });

      if (Array.isArray(list) && list.length > 0) {
        // 处理会议数据，根据实际API数据结构映射字段
        const processedItems = list.map((item) => {
          // 解析开始日期，提取日期部分用于显示
          const beginDate = dayjs(item.begin_date);
          const day = beginDate.format("DD");

          // 根据状态确定标签颜色
          const tagColor = getTagColor(item.status);

          // 格式化时间显示
          const timeStr = formatDate(item.begin_date, "YYYY.MM.DD");

          return {
            id: item.id,
            begin_date: day, // 用于左侧日期标识显示
            tagColor: tagColor,
            title: item.title,
            liveimg: item.liveimg,
            poster: item.liveimg, // 使用 liveimg 作为海报
            time: timeStr,
            location: item.location || "线上",
            status: getStatusText(item.status),
            // 保留原始数据用于其他功能
            originalData: item,
            begin_date_timestamp: item.begin_date_timestamp,
            end_date_timestamp: item.end_date_timestamp,
            begin_date: item.begin_date,
            end_date: item.end_date,
            liveurl: item.liveurl,
            spareurl: item.spareurl,
            path: item.path,
            tags: item.tags || '',
            status_code: item.status,
          };
        });

        if (isRefresh) {
          meetingList.value = processedItems;
        } else {
          meetingList.value.push(...processedItems);
        }

        // 更新分页状态
        hasMoreData.value = !isLastPage;
        showLoadMore.value = total > 0;

        console.log("会议列表更新成功，当前总数:", meetingList.value.length);
        console.log("分页信息:", {
          currentPage: currentPage.value,
          total,
          pages,
          hasMore: hasMoreData.value,
        });
      } else {
        console.log("API返回的数据为空");
        if (isRefresh) {
          meetingList.value = [];
        }
      }
    } else {
      console.log("API响应格式不正确:", response);
      if (isRefresh) {
        meetingList.value = [];
      }
    }
  } catch (error) {
    console.error("获取会议列表失败:", error);
    if (isRefresh) {
      meetingList.value = [];
    }
    uni.showToast({
      title: "获取会议列表失败",
      icon: "error",
      duration: 2000,
    });
  }
};

// 根据会议状态获取标签颜色
const getTagColor = (status) => {
  const colorMap = {
    1: "#FF4444", // 预告
    2: "#00BCD4", // 直播中
    3: "#9C27B0", // 已结束/回放
    4: "#4CAF50", // 已完成
    5: "#FF9800", // 已取消
  };
  return colorMap[status] || "#FF4444";
};

const formatTagColor = (index) => {
  const colors = ['#f94438', '#ffb93f', '#4ecdc4', '#92d758'];
  return colors[index % colors.length];
};
// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: "预告",
    2: "直播中",
    3: "已结束",
    4: "回放中"
  };
  return statusMap[status] || "预告";
};

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    1: "status-preview",
    2: "status-live",
    3: "status-ended",
    4: "status-completed",
    5: "status-cancelled",
  };
  return classMap[status] || "status-preview";
};

// 使用 dayjs 格式化日期函数，包含年月
const formatDate = (date, format = "YYYY-MM") => {
  if (!date) return "";

  try {
    // 使用 dayjs 解析日期
    const dayjsDate = dayjs(date);

    // 检查日期是否有效
    if (!dayjsDate.isValid()) {
      console.error("无效的日期:", date);
      return "";
    }

    // 根据格式参数返回不同格式
    switch (format) {
      case "YYYY-MM":
        return dayjsDate.format("YYYY-MM");
      case "YYYY-MM-DD":
        return dayjsDate.format("YYYY-MM-DD");
      case "YYYY-MM-DD HH:mm":
        return dayjsDate.format("YYYY-MM-DD HH:mm");
      case "YYYY-MM-DD HH:mm:ss":
        return dayjsDate.format("YYYY-MM-DD HH:mm:ss");
      case "YYYY年MM月":
        return dayjsDate.format("YYYY年MM月");
      case "YYYY年MM月DD日":
        return dayjsDate.format("YYYY年MM月DD日");
      case "MM月":
        return dayjsDate.format("MM月");
      case "MM月DD日":
        return dayjsDate.format("MM月DD日");
      case "YYYY.MM.DD":
        return dayjsDate.format("YYYY.MM.DD");
      case "MM-DD":
        return dayjsDate.format("MM-DD");
      case "MM/DD":
        return dayjsDate.format("MM/DD");
      case "YYYY/MM/DD":
        return dayjsDate.format("YYYY/MM/DD");
      default:
        return dayjsDate.format(format);
    }
  } catch (error) {
    console.error("日期格式化失败:", error);
    return "";
  }
};

// 格式化会议时间
const formatMeetingTime = (timeStr) => {
  if (!timeStr) return "";

  try {
    // 使用 dayjs 格式化时间
    const formattedDate = formatDate(timeStr, "YYYY年MM月");
    return formattedDate || "";
  } catch (error) {
    console.error("时间格式化失败:", error);
    return "";
  }
};
const formatDay = (timeStr) => {
  if (!timeStr) return "";
  return formatDate(timeStr, "DD");
};
// 显示时间选择弹窗
const showTimePopup = () => {
  isTimePopupShow.value = !isTimePopupShow.value;
};

// 隐藏时间选择弹窗
const hideTimePopup = () => {
  isTimePopupShow.value = false;
};

// 选择月份
const selectMonth = (month) => {
  selectedMonth.value = month.value;
  monthName.value = month.label;
  console.log("选择月份:", month.label);
  // 选择月份后重新加载数据
  meetingListBySearch(true);
  hideTimePopup();
};

// 显示地区选择弹窗
const showLocationPopup = () => {
  isLocationPopupShow.value = !isLocationPopupShow.value;
};

// 隐藏地区选择弹窗
const hideLocationPopup = () => {
  isLocationPopupShow.value = false;
};

// 选择省份
const selectProvince = (province) => {
  selectedProvince.value = province.code;
  provinceName.value = province.name;
  console.log("选择省份:", province.name);
  // 选择省份后重新加载数据
  meetingListBySearch(true);
  hideLocationPopup();
};

// 播放视频
const playVideo = (item) => {
  // uni.sendNativeEvent('noticeBack', {
  //   msg: 'go'
  // }, ret => {
  //   console.log('ret数据');
  //   console.log(ret);
  // })
	if(item.status_code==1 || item.status_code==2 || item.status_code==4){
		let zhiboUrl=OTHER_HOST+'/hcp/setInfo';
		let userInfo=uni.getStorageSync('userInfo');
		let str=userInfo.uuid+userInfo.realName+userInfo.photo+item.liveurl;
		let sign=encryptAesEcb(str, "deoep09_klodLdAo");
		let tempUrl=zhiboUrl+'?id='+userInfo.uuid+"&name="+userInfo.realName+"&avatar="+userInfo.photo+"&sign="+sign+'&url='+item.liveurl;
		console.log(tempUrl);
		const encoded = encodeURIComponent(tempUrl);
    let imgPath=encodeURIComponent(docUrl+item.liveimg);
		uni.navigateTo({
			url: `/pages_app/webview/webview?url=${encoded}&sharetitle=${item.title}&bg=1&type=live&imgPath=${imgPath}&share=1&title=会议直播&tags=${item.tags}`,
		});
	}else{
		goDetail(item);
	}
  // 这里可以实现视频播放逻辑
};

// 图片加载失败处理
const onImageError = (e) => {
  const itemId = e.currentTarget.dataset.itemId;
  console.log("图片加载失败，项目ID:", itemId);

  // 找到对应的项目并设置默认图片
  const itemIndex = meetingList.value.findIndex((item) => item.id === itemId);
  if (itemIndex !== -1) {
    // 如果liveimg加载失败，尝试使用poster
    if (
      meetingList.value[itemIndex].liveimg &&
      meetingList.value[itemIndex].liveimg !==
        meetingList.value[itemIndex].poster
    ) {
      console.log("liveimg加载失败，切换到poster");
      meetingList.value[itemIndex].liveimg =
        meetingList.value[itemIndex].poster;
    } else {
      // 如果poster也失败，使用默认图片
      console.log("设置默认图片");
      meetingList.value[itemIndex].poster = "/static/meeting-poster-1.jpg";
    }
  }
};

// 图片加载成功处理
const onImageLoad = (e) => {
  const itemId = e.currentTarget.dataset.itemId;
  console.log(
    "图片加载成功，项目ID:",
    itemId,
    "图片地址:",
    e.currentTarget.src
  );
};

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true;
  currentPage.value = 1;
  hasMoreData.value = true;

  // 调用获取会议列表函数
  if(selectedMonth.value || selectedProvince.value){
    meetingListBySearch(true).finally(() => {
      isRefreshing.value = false;
      uni.showToast({
        title: "刷新成功",
        icon: "none",
        duration: 1500,
      });
    });
  }else{
  getMeetingList(true).finally(() => {
    // 延迟关闭刷新状态，给用户更好的体验
    setTimeout(() => {
      isRefreshing.value = false;
      uni.showToast({
        title: "刷新成功",
        icon: "none",
        duration: 1500,
      });
    }, 500);
  });
};
}
// 上拉加载更多
const onLoadMore = () => {
  console.log("上拉加载更多");
  if (isLoadingMore.value || !hasMoreData.value) return;

  isLoadingMore.value = true;
  currentPage.value++;

  // 调用API获取更多数据
  if(selectedMonth.value || selectedProvince.value){
    meetingListBySearch(false).finally(() => {
      isLoadingMore.value = false;
    });
  }else{
    getMeetingList(false).finally(() => {
      isLoadingMore.value = false;
    });
  }
};
</script>

<style lang="scss" scoped>
// 颜色变量
$primary-color: #d32f2f;
$secondary-color: #8b2316;
$background-color: #f5f5f5;
$white: #ffffff;
$gray-light: #f0f0f0;
$gray: #666;
$gray-dark: #333;
$gray-text: #999;
$border-color: #e0e0e0;
$green-accent: #00d4aa;
$shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
.nav-right {
//   margin-top: 50rpx;
}
.page {
  background-color: $background-color;
  min-height: 100vh;
}
.scan-btn {
  font-size: 30rpx;
  color: #8B2316;
  
}
// 可滚动内容区域
.scroll-content {
  position: fixed;
  top: calc(var(--status-bar-height) + 44px + 88rpx); // 导航栏140rpx + 筛选栏88rpx
  left: 0;
  right: 0;
  bottom:120rpx; // 底部导航栏高度
  width: 100%;
  &.active{
    bottom:10rpx;
  }
}

// 筛选标签栏
.filter-bar {
  position: fixed;
  top: calc(var(--status-bar-height) + 44px);
  width: 100%;
  z-index: 2;
  background-color: $white;
  height: 88rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  border-bottom: 2rpx solid $gray-light;

  .filter-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 20rpx;
    font-size: 28rpx;
    color: $gray;
    text {
      margin-right: 10rpx;
      white-space: nowrap;
      max-width: 160rpx;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    &.active {
      color: #8b2316;
    }
  }

  .filter-divider {
    width: 2rpx;
    height: 32rpx;
    background-color: $border-color;
    margin: 0 10rpx;
  }
}

// 时间选择弹窗
.time-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;

  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .time-popup-content {
    margin-top: calc(var(--status-bar-height) + 44px + 90rpx);;
    position: relative;
    background-color: $white;
    width: 100%;
    height: calc(100vh - calc(var(--status-bar-height) - 44px - 88rpx));

    .time-list {
      padding: 0;
      height: 100%;
      overflow-y: auto;

      .time-item {
        padding: 25rpx 60rpx;
        font-size: 32rpx;
        color: #666;
        border-bottom: 2rpx solid #f0f0f0;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;

        &:hover {
          background-color: #f8f8f8;
        }

        &.active {
          background-color: #f8f8f8;
          color: $primary-color;

          text {
            font-weight: 500;
          }
        }

        &:last-child {
          border-bottom: none;
        }

        text {
          display: block;
          width: 100%;
        }
      }
    }
  }
}

// 地区选择弹窗
.location-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;

  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .popup-content {
    margin-top: calc(var(--status-bar-height) + 44px + 90rpx);;
    position: relative;
    background-color: $white;
    box-sizing: border-box;
    width: 100%;
    height: calc(100vh - calc(var(--status-bar-height) - 44px - 88rpx));
    padding: 40rpx;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .popup-title {
        font-size: 18px;
        font-weight: 500;
        color: $gray-dark;
      }

      .close-btn {
        width: 30px;
        height: 30px;
        background-color: $gray-light;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        color: $gray;
        cursor: pointer;
      }
    }

    .location-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 30rpx;
      
      overflow-y: auto;

      .location-item {
        padding: 16rpx;
        background-color: $background-color;
        border-radius: 16rpx;
        text-align: center;
        font-size: 28rpx;
        color: #999;
        border: 2rpx solid #999;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          background-color: lighten($primary-color, 45%);
        }

        &.active {
          background-color: lighten($primary-color, 40%);
          border-color: $primary-color;
          color: $primary-color;
        }

        text {
          display: block;
          white-space: nowrap;
          overflow: hidden;
          width: 106rpx;
          text-overflow: ellipsis;
          word-break: break-all;
        }
      }
    }
  }
}

// 时间标题
.time-header {
  text-align: center;
  padding: 30rpx 0;
  font-size: 32rpx;
  color: $gray;
  background-color: $background-color;
}

// 会议列表
.meeting-list {
  padding: 0 30rpx;

  .meeting-item {
    display: flex;
    margin-bottom: 30rpx;
    background-color: $white;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: $shadow;

    // 日期标识
    .date-tag {
      width: 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .date-text {
        background: $white;
        position: absolute;
        top: 50%;
        color: red;
        transform: translateY(-50%);
        font-size: 32rpx;
        width: 40rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        left: 35rpx;
        height: 40rpx;
        border-radius: 50%;
      }
    }

    // 会议内容
    .meeting-content {
      flex: 1;
      padding: 30rpx;

      .meeting-title {
        font-size: 32rpx;
        font-weight: 500;
        color: $gray-dark;
        margin-bottom: 20rpx;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2; /* 限制文本为2行 */
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .meeting-poster {
        position: relative;
        height: 320rpx;
        border-radius: 12rpx;
        overflow: hidden;
        margin-bottom: 20rpx;

        .poster-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .play-btn {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 210rpx;
          height: 210rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .status-tag {
          position: absolute;
          top: 16rpx;
          right: 16rpx;
          font-size: 24rpx;
          padding: 4rpx 16rpx;
          border-radius: 20rpx;
          color: $white;
          font-weight: 500;
          border: 2rpx solid #fff;
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);

          &.status-preview {
            background: rgba(0, 0, 0, 0.2);
          }

          &.status-live {
            background: rgba(0, 0, 0, 0.2);
          }

          &.status-ended {
            background: rgba(0, 0, 0, 0.2);
          }

          &.status-completed {
            background: rgba(0, 0, 0, 0.2);
          }

          &.status-cancelled {
            background: rgba(0, 0, 0, 0.2);
          }
        }
      }

      .meeting-info {
        display: flex;
        justify-content: space-between;

        .info-item {
          display: flex;
          align-items: center;
          .timebox {
            margin-top: -19rpx;
          }
          .info-text {
            font-size: 28rpx;
            color: $gray-text;
            margin-left: 8rpx;
          }
        }
      }
    }
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 30rpx;

  .empty-icon {
    margin-bottom: 30rpx;
  }

  .empty-text {
    font-size: 32rpx;
    color: $gray;
    margin-bottom: 16rpx;
  }

  .empty-subtext {
    font-size: 26rpx;
    color: $gray-text;
    text-align: center;
  }
}

// 加载更多提示
.load-more {
  padding: 30rpx;

  .load-more-content {
    display: flex;
    align-items: center;
    justify-content: center;

    .load-more-text {
      font-size: 28rpx;
      color: $gray-text;
      margin-left: 10rpx;
    }
  }
}

// 过往会议提示
.history-tip {
  position: fixed;
  bottom: 200rpx;
  z-index: 9;
  right: 0;
 
  display: flex;
  align-items: center;
  justify-content: center;
  
}

// 底部导航栏
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: $white;
  display: flex;
  border-top: 1px solid $gray-light;

  .nav-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 5px 0;

    .nav-text {
      font-size: 10px;
      color: $gray-text;
      margin-top: 2px;

      &.active {
        color: $primary-color;
      }
    }
  }
}
</style>
