<template>
  <view class="container">
    <!-- <view class="empty" v-if="communityList.length == 0">
      <image src="https://static.hshuishang.com/property-img-file/com_newEmpty.png" alt="" />
      <text>当前账户未绑定任何项目房源信息</text>
      <button class="emptyBtn" @click="addCommunity">新增房产绑定</button>
    </view> -->

    <view v-if="communityList.length == 0">
      <view class="searchBox" :style="{ height: localHeight + 'px', paddingTop: top + 'px' }">
        <view class="searchBox_add">
          <view class="emptyCommunity" @click="addCommunity">
            {{ communityVal }}
          </view>
        </view>
      </view>

      <view class="swiperBox_no1">
        <swiper @animationfinish="swipers" autoplay circular>
          <image src="https://static.hshuishang.com/community_no_image1.png" mode="aspectFill"
            class="swiperBox_no_img" @click="addCommunity" />
        </swiper>

        <view class="dot">
          <view :class="['dotItem', currentIdx == index ? 'active' : '']" v-for="(item, index) in bannerList"
            :key="index">
          </view>
        </view>
      </view>

      <view class="swiperBox_no2">
        <swiper @animationfinish="swipers" autoplay circular>
          <image src="https://static.hshuishang.com/community_no_image2.png" mode="aspectFill"
            class="swiperBox_no_img" @click="addCommunity" />
        </swiper>
      </view>

      <view class="funcList">
        <u-grid :col="5" :border="false">
          <u-grid-item v-for="(item, index) in noValFunctionList" @click="addCommunity" :key="index">
            <image class="grid_Pic" :src="item.nav_icon" mode=""></image>
            <text class="grid_Text">{{ item.nav_name }}</text>
          </u-grid-item>
        </u-grid>
      </view>

      <view class="tabs" v-if="defaultCategoryList.length > 0">
        <view v-for="(item, index) in defaultCategoryList" :key="index"
          :class="['tabItem', selectedTab === index ? 'active2' : '']" @click="selectTab(index, item)">
          {{ item.category_name }}
        </view>
      </view>

      <view class="newsList" v-if="defaultCategoryList.length > 0">
        <view class="newsItem" v-for="item in defaultInfoList" @click="defaultDetail(item)" :key="item.id">
          <view class="newsItem_left">
            <view class="newsItem_left_tit">{{ item.title }}</view>
            <view class="newsItem_left_sub">{{ item.author }}</view>
          </view>
          <view class="newsItem_right">
            <image :src="item.pic" mode="aspectFill" />
          </view>
        </view>
      </view>

    </view>
    <view v-else>
      <view class="searchBox" :style="{ height: localHeight + 'px', paddingTop: top + 'px' }">
        <view class="searchBox_add">
          <view class="emptyCommunity" @click="addCommunity">
            {{ communityVal }}
          </view>
        </view>
      </view>

      <view class="swiperBox1" v-if="bannerList.length > 0">
        <swiper @animationfinish="swipers" autoplay circular>
          <swiper-item v-for="(item, index) in bannerList" :key="index" @click="headerServerClick(item)">
            <image :src="item.ad_picture" mode="aspectFill" />
          </swiper-item>
        </swiper>

        <view class="dot">
          <view :class="['dotItem', currentIdx == index ? 'active' : '']" v-for="(item, index) in bannerList"
            :key="index">
          </view>
        </view>
      </view>

      <view class="swiperBox_no1" v-else>
        <swiper @animationfinish="swipers" autoplay circular>
          <image src="https://static.hshuishang.com/community_no_image1.png" mode="aspectFill"
            class="swiperBox_no_img" />
        </swiper>

        <view class="dot">
          <view :class="['dotItem', currentIdx == index ? 'active' : '']" v-for="(item, index) in bannerList"
            :key="index">
          </view>
        </view>
      </view>

      <view class="swiperBox2" v-if="streamerList.length > 0">
        <swiper @animationfinish="swipers" autoplay circular>
          <swiper-item v-for="(item, index) in streamerList" :key="index" @click="headerServerClick(item)">
            <image :src="item.ad_picture" mode="aspectFill" class="swiperBox2_img" />
          </swiper-item>
        </swiper>
      </view>

      <view class="swiperBox_no2" v-else>
        <swiper @animationfinish="swipers" autoplay circular>
          <image src="https://static.hshuishang.com/community_no_image2.png" mode="aspectFill"
            class="swiperBox_no_img" />
        </swiper>
      </view>

      <view class="funcList">
        <u-grid :col="rowNum" :border="false">
          <u-grid-item v-for="(item, index) in functionList" @click="jump(item.mini_program_url)" :key="index">
            <image class="grid_Pic" :src="item.nav_icon" mode=""></image>
            <text class="grid_Text">{{ item.nav_name }}</text>
          </u-grid-item>
        </u-grid>
      </view>

      <view v-for="(item, index) in tileList" :key="index" :class="['ads', index == 0 ? 'ads_first' : '']"
        @click="headerServerClick(item)">
        <image :src="item.ad_picture" mode="aspectFill" />
      </view>

      <view class="tabs" v-if="categoryList.length > 0">
        <view v-for="(item, index) in categoryList" :key="index"
          :class="['tabItem', selectedTab === index ? 'active2' : '']" @click="selectTab(index, item)">
          {{ item.category_name }}
        </view>
      </view>

      <view class="tabs" v-else>
        <view v-for="(item, index) in defaultCategoryList" :key="index"
          :class="['tabItem', selectedTab === index ? 'active2' : '']" @click="selectTab(index, item)">
          {{ item.category_name }}
        </view>
      </view>

      <view class="newsList" v-if="categoryList.length > 0">
        <view class="newsItem" v-for="item in infoList" @click="detail(item)" :key="item.id">
          <view class="newsItem_left">
            <view class="newsItem_left_tit">{{ item.title }}</view>
            <view class="newsItem_left_sub">{{ item.author }}</view>
          </view>
          <view class="newsItem_right">
            <image :src="item.list_image" mode="aspectFill" />
          </view>
        </view>
      </view>

      <view class="newsList" v-else>
        <view class="newsItem" v-for="item in defaultInfoList" @click="defaultDetail(item)" :key="item.id">
          <view class="newsItem_left">
            <view class="newsItem_left_tit">{{ item.title }}</view>
            <view class="newsItem_left_sub">{{ item.author }}</view>
          </view>
          <view class="newsItem_right">
            <image :src="item.pic" mode="aspectFill" />
          </view>
        </view>
      </view>

      <view class="tips">{{ loadMoreText }}</view>

      <view class="bigAds" v-if="ads1Show">
        <view class="bigAdsCon">
          <view class="bigAdsCon_img">
            <swiper @animationfinish="swipers" autoplay circular>
              <swiper-item v-for="(item, index) in largePopList" :key="index" @click="headerServerClick(item)">
                <image :src="item.ad_picture" mode="aspectFill" />
              </swiper-item>
            </swiper>
          </view>
          <view class="close" @click="closeAds">
            <image src="https://static.hshuishang.com/property-img-file/com_close.png">
            </image>
          </view>
        </view>
      </view>

      <view class="bigAds" v-if="ads2Show">
        <view class="bigAdsCon2">
          <view class="bigAdsCon2_img">
            <swiper :current="currentSwiperIndex" @change="onSwiperChange" @animationfinish="swipers" autoplay circular>
              <swiper-item v-for="(item, index) in popList" :key="index">
                <image :src="item.ad_picture" mode="aspectFill" />
              </swiper-item>
            </swiper>
          </view>
          <view class="AdsBtnList">
            <view class="AdsBtnItem1" @click="closeAds2">取消</view>
            <view class="AdsBtnItem2" @click="onDetailClick">了解详情</view>
          </view>
        </view>
      </view>
    </view>
    <nav-footer :current="3" />
  </view>
</template>

<script>
import {
  request,
  picUrl,
  uniqueByField,
  menuButtonInfo,
  NavgateTo,
} from "../../../utils";

import { apiArr } from "../../../api/v2Community";
import { apiArr as apiArr2 } from "../../../api/community";

// 引入数据文件
import dataJson from './data.json';

export default {
  data() {
    return {
      communityVal: "添加我的房产",
      picUrl,
      top: "",
      localHeight: "",
      queryPage: {
        page_num: 1,
        page_size: 10,
      },
      communityList: [],
      flag: false,

      defaultFunctionList: [],
      functionList: [],
      noValFunctionList: [
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction1.png',
          nav_name: "物业介绍",
        },
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction2.png',
          nav_name: "物业缴费",
        },
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction3.png',
          nav_name: "岁银",
        },
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction1.png',
          nav_name: "物业报修",
        },
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction4.png',
          nav_name: "便民电话",
        },
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction5.png',
          nav_name: "人脸门禁",
        },
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction6.png',
          nav_name: "手机开门",
        },
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction7.png',
          nav_name: "物业活动",
        },
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction8.png',
          nav_name: "访客邀请",
        },
        {
          nav_icon: 'https://static.hshuishang.com/noValFunction10.png',
          nav_name: "场地预约",
        },
      ],

      ads1Show: false,
      ads2Show: false,

      bannerList: [], //轮播图广告
      currentIdx: 0,
      streamerList: [], //横幅广告
      tileList: [], //平铺广告
      largePopList: [], //巨幅弹屏广告
      popList: [], //弹屏广告
      categoryList: [],
      infoList: [],
      selectedTab: 0,
      currentAdIndex: 0,

      rowNum: 0,
      colNum: 0,

      page_size: 10,
      page_num: 1,
      flag: false,
      loadMoreText: "",

      isShowBill: false,

      houseVal: "",

      // 从JSON文件中获取默认数据
      defaultCategoryList: dataJson.defaultCategoryList,
      defaultInfoList: dataJson.defaultInfoList,
      // 用于存储原始的defaultInfoList数据
      originalDefaultInfoList: null
    };
  },
  async onLoad(options) {
    if (options.item) {
      this.checkComm(JSON.parse(options.item));
    }
  },

  onHide() {
    uni.removeStorageSync("is_me");
  },
  onUnload() {
    uni.removeStorageSync("is_me");
  },

  async onShow() {
    const meun = menuButtonInfo();
    this.top = meun.top;
    // this.top = meun.height + meun.top;
    this.localHeight = meun.height;
    this.defaultFunctionList = [
      {
        create_time: "",
        id: 4,
        is_published: 1,
        jump_target: 1,
        mini_program_url: "/packages/community/repairList/index",
        nav_icon: "https://static.hshuishang.com/noValFunction1.png",
        nav_name: "报事报修",
        other_appid: "",
        other_path: "",
        sort: 5,
        update_time: "",
        visible_communities: ""
      },
      {
        create_time: "",
        id: 5,
        is_published: 1,
        jump_target: 1,
        mini_program_url: "/packages/community/propertyPayment/index",
        nav_icon: "https://static.hshuishang.com/noValFunction2.png",
        nav_name: "物业缴费",
        other_appid: "",
        other_path: "",
        sort: 4,
        update_time: "",
        visible_communities: "",
      },
      {
        create_time: "",
        id: 7,
        is_published: 1,
        jump_target: 1,
        mini_program_url: "/packages/community/providentFund/index",
        nav_icon: "https://static.hshuishang.com/noValFunction3.png",
        nav_name: "岁银",
        other_appid: "",
        other_path: "",
        sort: 2,
        update_time: "",
        visible_communities: ""
      }

    ]
    const isMe = uni.getStorageSync("is_me");
    // 当is_me不存在或为true时执行，存在且为false时不执行
    if (isMe === true || isMe === undefined || isMe === null || isMe === '') {
      await this.getCommunityList();
    }
    this.getfunctionNum();
    this.getAdvertising();
    this.getCategoryList();

    // 初始化默认数据，确保在没有绑定社区时选中第一个分类
    setTimeout(() => {
      if (this.categoryList.length === 0 && this.defaultCategoryList.length > 0) {
        this.selectedTab = 0;
        if (!this.originalDefaultInfoList) {
          this.originalDefaultInfoList = JSON.parse(JSON.stringify(dataJson.defaultInfoList));
        }
        // 默认选中第一个分类并展示对应数据
        this.defaultInfoList = this.originalDefaultInfoList.filter(info => info.id === this.defaultCategoryList[0].id);
      }
    }, 100);
  },

  //上拉刷新
  onPullDownRefresh() {
    this.communityVal = uni.getStorageSync("changeCommData").name;
    this.bannerList = [];
    this.currentIdx = 0;
    this.streamerList = []; //横幅广告
    this.tileList = []; //平铺广告
    this.largePopList = []; //巨幅弹屏广告
    this.popList = []; //弹屏广告
    this.categoryList = [];
    this.infoList = [];
    this.selectedTab = 0;
    this.currentAdIndex = 0;
    this.getfunctionNum();
    this.getAdvertising();
    this.getCategoryList();
    uni.stopPullDownRefresh();
  },
  //下拉加载
  onReachBottom() {
    if (this.flag) {
      this.page_num++;
      const currentItem = this.categoryList[this.selectedTab];
      if (currentItem) {
        this.selectTab(this.selectedTab, currentItem);
      }
    }
  },

  methods: {
    // desc() {
    // 	NavgateTo("../communityDetail/index")
    // },
    checkComm(item) {
      if (uni.getStorageSync("is_me")) {
        uni.setStorageSync("changeCommData", { name: item.name, id: item.community_id })
      } else {
        this.communityList = []
        this.communityVal = item.name;
      }
    },
    async getCommunityList() {
      await request(apiArr2.commInfo, "POST", {
        user_id: uni.getStorageSync("userId"),
        longitude: uni.getStorageSync("location").lng,
        latitude: uni.getStorageSync("location").lat,
        page_num: this.page_num,
        page_size: this.page_size,
      }).then((res) => {
        if (res.rows.length == 0) {
          uni.removeStorageSync("changeCommData");
          return;
        }

        const targetItem = res.rows.find((item) => {
          return item.community_id == uni.getStorageSync("changeCommData").id;
        });

        if (targetItem) {
          //是否跳转物业缴费
          this.isShowBill = targetItem.bill_front_end_display == 1;
          //小区是否隐藏
          if (targetItem.front_end_display == 1) {
            uni.removeStorageSync("changeCommData");
          }
        } else {
          uni.removeStorageSync("changeCommData");
        }

        res.rows = res.rows.filter((item) => {
          return item.front_end_display != 1;
        });
        if (!uni.getStorageSync("changeCommData")) {
          uni.setStorageSync("changeCommData", { name: res.rows[0].name, id: res.rows[0].community_id })
        }
        this.communityList = res.rows;
      });
      if (this.communityList.length == 0) {
        this.communityVal = "添加我的房产";
      } else {
        this.communityVal = uni.getStorageSync("changeCommData").name;
      }
    },
    apply() {
      NavgateTo("../applyOwer/index");
    },
    closeAds() {
      this.ads1Show = false;
      // 记录用户已关闭过弹窗1
      uni.setStorageSync('ads1Showed', true);
    },
    closeAds2() {
      this.ads2Show = false;
      // 记录用户已关闭过弹窗2
      uni.setStorageSync('ads2Showed', true);
    },
    jump(e) {
      if (!e) {
        this.NotOpen();
        return;
      }
      if (
        e == "/packages/community/propertyPayment/index" &&
        !this.isShowBill
      ) {
        uni.showToast({
          title: "请配置账单",
          icon: "none",
        });
        return;
      }
      NavgateTo(e);
    },

    addCommunity() {
      NavgateTo("/packages/community/myCommunity/index");
    },

    swipers(event) {
      // 获取当前轮播图索引
      this.currentIdx = event.detail.current;
    },

    async getfunctionNum() {
      this.functionList = this.defaultFunctionList;
      const res = await request(
        apiArr.commInfo,
        "POST",
        {},
        {
          slice: false,
        }
      );
      this.rowNum = res.nav_row_num_comm;
      this.colNum = res.nav_row_total_comm;
      return await this.getfunctionList();
    },

    async getfunctionList() {
      if (!uni.getStorageSync("changeCommData")) {
        return;
      }
      const res = await request(apiArr.navPage, "POST", {
        community_id: Number(uni.getStorageSync("changeCommData").id),
        page_num: 1,
        page_size: 50,
      });
      console.log(res, "xx");

      // 获取 rowNum 和 colNum 的乘积
      const totalItems = this.rowNum * this.colNum - 3;
      // 截取前 totalItems 个元素
      const newItems = res.rows.slice(0, totalItems).map((item) => {
        return {
          ...item,
          nav_icon: picUrl + item.nav_icon,
        };
      });

      // 根据nav_name判断是否已存在，不存在则添加
      newItems.forEach(newItem => {
        const exists = this.functionList.some(existingItem =>
          existingItem.nav_name === newItem.nav_name
        );
        if (!exists) {
          this.functionList.push(newItem);
        }
      });
    },

    async getAdvertising() {
      if (!uni.getStorageSync("changeCommData")) {
        return;
      }
      const res = await request(apiArr.advPage, "POST", {
        community_id: Number(uni.getStorageSync("changeCommData").id),
        ad_position: 1,
        page_num: 1,
        page_size: 50,
      });
      this.bannerList = res.rows.map((item) => {
        return {
          ...item,
          ad_picture: picUrl + item.ad_picture,
        };
      });

      const res2 = await request(apiArr.advPage, "POST", {
        community_id: Number(uni.getStorageSync("changeCommData").id),
        ad_position: 2,
        page_num: 1,
        page_size: 50,
      });
      this.streamerList = res2.rows.map((item) => {
        return {
          ...item,
          ad_picture: picUrl + item.ad_picture,
        };
      });

      const res3 = await request(apiArr.advPage, "POST", {
        community_id: Number(uni.getStorageSync("changeCommData").id),
        ad_position: 3,
        page_num: 1,
        page_size: 50,
      });
      this.tileList = res3.rows.map((item) => {
        return {
          ...item,
          ad_picture: picUrl + item.ad_picture,
        };
      });

      const res4 = await request(apiArr.advPage, "POST", {
        community_id: Number(uni.getStorageSync("changeCommData").id),
        ad_position: 4,
        page_num: 1,
        page_size: 50,
      });
      this.largePopList = res4.rows.map((item) => {
        return {
          ...item,
          ad_picture: picUrl + item.ad_picture,
        };
      });
      // 检查用户是否已关闭过弹窗1，只有当没有关闭过且有广告数据时才显示
      const ads1Showed = uni.getStorageSync('ads1Showed');
      this.ads1Show = !ads1Showed && res4.rows.length !== 0 ? true : false;

      const res5 = await request(apiArr.advPage, "POST", {
        community_id: Number(uni.getStorageSync("changeCommData").id),
        ad_position: 5,
        page_num: 1,
        page_size: 50,
      });
      this.popList = res5.rows.map((item) => {
        return {
          ...item,
          ad_picture: picUrl + item.ad_picture,
        };
      });
      // 检查用户是否已关闭过弹窗2，只有当没有关闭过且有广告数据时才显示
      const ads2Showed = uni.getStorageSync('ads2Showed');
      this.ads2Show = !ads2Showed && res5.rows.length !== 0 ? true : false;
    },

    headerServerClick(e) {
      console.log("当前点击内容", e);
      if (!e.target_page) {
        this.NotOpen();
        return;
      }
      if (e.target_page) {
        // #ifdef APP-PLUS
        uni.navigateTo({
          url:
            "/pages/webview/webview?url=" + encodeURIComponent(e.target_page),
        });
        // #endif

        // #ifdef H5
        window.open(e.target_page, "_blank");
        // #endif

        // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU
        if (e.appid) {
          uni.navigateToMiniProgram({
            appId: e.appid,
            path: e.target_page,
            //需要传递给目标小程序的数据
            extraData: {
              data1: "test",
            },
            success(res) {
              console.log("打开成功", res);
            },
          });
        } else {
          // 确保路径是绝对路径
          let targetPage = e.target_page;
          if (!targetPage.startsWith("/")) {
            targetPage = "/" + targetPage;
          }
          NavgateTo(targetPage);
          // NavgateTo('/packages/localLife/index/index')
        }
        // 小程序中可能需要用户手动复制链接或使用web-view
        // uni.showModal({
        // 	title: '提示',
        // 	content: '即将打开外部链接，请复制后在浏览器中打开: ' + e.target_page,
        // 	confirmText: '复制链接',
        // 	success(res) {
        // 		if (res.confirm) {
        // 			uni.setClipboardData({
        // 				data: e.target_page,
        // 				success() {
        // 					uni.showToast({
        // 						title: '复制成功',
        // 						icon: 'success'
        // 					});
        // 				}
        // 			});
        // 		}
        // 	}
        // });
        // #endif
      }
    },
    onSwiperChange(e) {
      this.currentAdIndex = e.detail.current;
    },
    onDetailClick() {
      // 获取当前显示的广告项
      const currentAd = this.popList[this.currentAdIndex];
      if (currentAd) {
        this.headerServerClick(currentAd);
      } else if (this.popList.length > 0) {
        // 如果当前索引无效，默认使用第一项
        this.headerServerClick(this.popList[0]);
      }
    },

    NotOpen() {
      uni.showModal({
        title: "提示",
        content: "此功能暂未开通！",
        showCancel: false,
        complete: (res) => {
          if (res.cancel) {
          }
        },
      });
    },

    async getCategoryList() {
      if (!uni.getStorageSync("changeCommData")) {
        return;
      }
      const res = await request(apiArr.categoryPage, "POST", {
        community_id: Number(uni.getStorageSync("changeCommData").id),
        category_code: "",
        category_name: "",
        page_num: 1,
        page_size: 30,
      });
      this.categoryList = res.rows;
      this.selectTab(0, res.rows[0]);
    },

    async selectTab(index, item) {
      // 检查是否使用的是默认数据（没有绑定社区时）
      if (this.categoryList.length === 0) {
        this.selectedTab = index;
        if (!this.originalDefaultInfoList) {
          this.originalDefaultInfoList = JSON.parse(JSON.stringify(dataJson.defaultInfoList));
        }

        // 根据选中的分类ID筛选数据
        this.defaultInfoList = this.originalDefaultInfoList.filter(info => info?.id === item?.id);
        return;
      }

      // 原有逻辑（有绑定社区时）
      const isTabChange = this.selectedTab !== index;
      if (isTabChange) {
        this.page_num = 1;
        this.infoList = [];
      }
      this.selectedTab = index;

      // 如果不是切换tab，且已经没有更多数据，且已有数据，则不发送请求
      if (!isTabChange && !this.flag && this.infoList.length > 0) {
        return;
      }

      const res = await request(apiArr.infoPage, "POST", {
        community_id: Number(uni.getStorageSync("changeCommData").id),
        announcement_category_id: item?.id,
        title: "",
        category_name: "",
        page_num: this.page_num,
        page_size: this.page_size,
      });

      // 处理数据
      const newData = res.rows.map((item) => ({
        ...item,
        list_image: picUrl + item.list_image,
      }));

      // 判断是否还有更多数据
      const hasMore = res.rows.length === this.page_size;
      // 限制最多3页
      this.flag = hasMore;

      // 检查数据是否重复
      const isDataDuplicate =
        !isTabChange &&
        this.infoList.length > 0 &&
        newData.length > 0 &&
        this.infoList[this.infoList.length - 1].id === newData[0].id;

      // 更新数据
      if (isTabChange) {
        this.infoList = newData;
      } else if (!isDataDuplicate) {
        this.infoList = this.infoList.concat(newData);
      }

      // 更新提示文本
      if (this.infoList.length > 10 && !hasMore) {
        uni.showToast({
          title: "没有更多了",
          icon: "none",
        });
      } else {
        // this.loadMoreText = `下拉加载后续10条`;
      }
    },

    detail(e) {
      console.log(e);
      NavgateTo("../noticeDesc/index?id=" + e.id);
    },

    defaultDetail(e) {
      console.log(e);
      NavgateTo("../defaultNotice/index?id=" + e.id);
    },
  },
};
</script>

<style>
@import url("./index.css");
</style>