<template>
  <view class="main">
    <view class="bannerBox" :style="{ height: bannerHeight + 'px' }">
      <swiper
        class="swiper"
        circular
        :indicator-dots="true"
        :autoplay="true"
        :interval="4000"
      >
        <swiper-item
          class="swiperItem"
          v-for="(image, i) in bannerList"
          :key="i"
        >
          <image class="swiperImg" :src="image"></image>
        </swiper-item>
      </swiper>
    </view>
    <!-- :style="{ height: `calc(100vh - ${bannerHeight + 40}px)` }" -->
    <view class="communityContent" :style="{ height: `100vh` }">
      <view class="contentTab">
        <view
          :class="
            tabSelect === item.value ? 'tabItem selectTabItem' : 'tabItem'
          "
          v-for="(item, index) in tabList"
          :key="index"
          @click="handleChangeTabSelect(item.value)"
        >
          {{ item.label }}
        </view>
      </view>

      <scroll-view
        scroll-y
        class="scrollContent"
        refresher-enabled
        :refresher-triggered="triggered"
        @scrolltolower="handleScrollBottom"
        @refresherrefresh="handleRefresh"
      >
        <view
          class="scrollItem"
          v-for="(item, index) in postList"
          :key="index"
          @click="handleGoDetail(item)"
        >
          <view class="itemTop">
            <view class="topLeft">
              <view class="profileBox">
                <image
                  class="profile"
                  :src="
                    item.AUTHOR_HEADIMAGEURL ||
                    '/static/images/home/defaultProfit.svg'
                  "
                />
              </view>
              <view class="otherBox">
                <view class="userName">{{ item.AUTHOR_NAME || "-" }}</view>
                <view class="timeBox">{{ item.PUBLISH_TIME || "-" }}</view>
              </view>
            </view>

            <view class="rightBox">
              <view class="commentBox">
                <image
                  class="commentIcon"
                  src="/static/images/home/commentIcon.svg"
                />
                <span class="commentText">
                  {{ item.POST_COMMENTCOUNT || 0 }}</span
                >
              </view>
              <view class="commentBox" @click.stop="handleThumbsUp(item)">
                <image
                  class="commentIcon"
                  :src="
                    item.isthumbsUp
                      ? '/static/images/home/thumbsUp.svg'
                      : '/static/images/home/nothumbsUp.svg'
                  "
                />
                <span
                  class="thumbsUp"
                  :style="{ color: item.isthumbsUp ? '#BA922F' : '#716F69' }"
                  >{{ item.POST_LIKECOUNT || 0 }}</span
                >
              </view>
            </view>
          </view>

          <view class="itemContent"
            >{{
              item.isShowSmall === 1 ? item.smallText : item.POST_TITLE || ""
            }}<span
              v-if="item.isShowSmall > 0"
              class="expend"
              @click.stop="handleChangeIsShowSmall(item)"
              >{{
                item.isShowSmall === 1
                  ? "展开"
                  : item.isShowSmall === 2
                  ? "收起"
                  : ""
              }}</span
            >
          </view>

          <view
            class="imageList"
            v-if="item.ImageList && item.ImageList.length > 0"
          >
            <view
              class="imageItem"
              v-for="(subItem, subIndex) in item.ImageList"
              :key="subIndex"
              @click.stop="handlePreviewImage(item, subIndex)"
            >
              <image class="image" :src="subItem.ImageUrl" />
            </view>
          </view>
        </view>

        <view class="inBottom" v-if="postList && postList.length > 0">
          <text class="bottomText">{{
            listDetail.isOver ? "我是有底线的" : "下拉加载更多"
          }}</text>
        </view>

        <div v-else style="width: 100%; height: 100%">
          <no-data text="暂无帖子" :isShow="true" :type="1"></no-data>
        </div>
      </scroll-view>
    </view>

    <view class="addNewPost" @click="handleAddNewPost">
      <view class="newPostBox">
        <image class="addIcon" src="/static/images/home/addPost.svg" />
        <text class="addText">我要发帖</text>
      </view>
    </view>
  </view>
</template>


<script>
import { mapGetters } from "vuex";
import NoData from "../../components/noData.vue";
export default {
  data() {
    return {
      screenWidth: 0, // 当前手机的宽度
      bannerHeight: 0, // 计算出来的轮播框高度
      tabList: [],
      bannerList: [
        "https://eshangtech.com/ShopICO/yifu/banner/banner1.png",
        "https://eshangtech.com/ShopICO/yifu/banner/banner2.png",
        "https://eshangtech.com/ShopICO/yifu/banner/banner3.png",
      ], // 轮播框内容
      tabObj: {}, // tab的枚举
      tabSelect: 0, // 选择的tab
      postList: [], // 当前的贴子
      isFirst: true, // 判断是不是第一次进入到页面 先拿枚举 再去调用列表
      listDetail: {
        pageSize: 10,
        pageIndex: 1,
        isOver: false,
      },
      triggered: false, // 下拉状态
      thumbedUpList: [], // 点赞过的id列表
      thumbedUpDetailList: [], // 点过赞的详情列表
    };
  },
  components: {
    NoData,
  },
  computed: {
    ...mapGetters({
      user: "user",
    }),
  },
  async onLoad() {
    let systemInfo = uni.getSystemInfoSync();
    console.log("systemInfo", systemInfo);
    this.screenWidth = systemInfo.screenWidth;
    console.log("this.screenWidth", this.screenWidth);
    let bannerH = (312 * this.screenWidth) / 750;
    console.log("bannerH", bannerH);
    this.bannerHeight = parseInt(bannerH);

    this.handleGetTypeList();

    // 获取当前点过赞的帖子列表
    // this.handleGetThumbedUp();
  },
  async onShow() {
    // if (!this.isFirst) {
    //   //   //  当前的发帖列表
    //   this.handleGetNowPostList();
    // }
  },
  methods: {
    // 当前点过赞的帖子列表
    async handleGetThumbedUp() {
      const req = {
        SearchParameter: {
          MEMBERSHIP_ID: this.user.MEMBERSHIP_ID,
          POSTDETAIL_TYPE: 2000, // 用户行为
          POSTDETAIL_STATE: 1,
        },
        PageIndex: 1,
        PageSize: 99999,
      };
      const data = await this.$api.$post("/Member/GetPOSTDETAILList", req);
      let list = data.Result_Data.List;
      console.log("handleGetThumbedUp", list);
      let POST_IDList = [];
      if (list && list.length > 0) {
        list.forEach((item) => {
          POST_IDList.push(item.POST_ID);
        });
      }
      this.thumbedUpList = POST_IDList;
      this.thumbedUpDetailList = list;
    },
    // 点赞
    async handleThumbsUp(obj) {
      console.log("obj", obj);
      console.log("user", this.user);
      console.log("this.thumbedUpList", this.thumbedUpList);

      if (!this.user.MEMBERSHIP_ID) {
        let _this = this;
        uni.showModal({
          title: "温馨提示",
          content: "请您授权登录后再操作。",
          success(res) {
            if (res.confirm) {
              if (_this.loginType === "min") {
                uni.navigateTo({ url: "/pages/register/index" });
              } else {
                uni.navigateTo({ url: "/pages/login/index" });
              }
            }
          },
        });
        return;
      }

      if (
        this.thumbedUpList.indexOf(obj.POST_ID) === -1 ||
        !(this.thumbedUpList && this.thumbedUpList.length > 0)
      ) {
        // 没有点过赞 给它点赞
        const req = {
          POST_ID: obj.POST_ID, // 帖子id
          POSTDETAIL_PID: -1, // 点赞的时候为-1
          MEMBERSHIP_ID: this.user.MEMBERSHIP_ID, // 会员内码
          POSTDETAIL_TYPE: 2000, // 用户行为
          NICK_NAME: this.user.MEMBERSHIP_NAME, // 用户昵称
          POSTDETAIL_STATE: 1, // 状态
        };
        const data = await this.$api.$post("/Member/SynchroPOSTDETAIL", req);
        console.log("handleThumbsUp", data);
        if (data.Result_Code === 100) {
          await this.handleGetThumbedUp();
          this.handleGetDetailIntoList(obj.POST_ID);
        } else {
          uni.showToast({
            title: data.Result_Desc,
            icon: "none",
          });
        }
      } else {
        // 点过赞 取消赞
        let currentObj =
          this.thumbedUpDetailList[this.thumbedUpList.indexOf(obj.POST_ID)];
        console.log("currentObj", currentObj);

        const req = {
          ...currentObj,
          POSTDETAIL_STATE: 0, // 状态
        };
        const data = await this.$api.$post("/Member/SynchroPOSTDETAIL", req);
        console.log("data", data);
        if (data.Result_Code === 100) {
          await this.handleGetThumbedUp();
          this.handleGetDetailIntoList(obj.POST_ID);
        } else {
          uni.showToast({
            title: data.Result_Desc,
            icon: "none",
          });
        }
      }
    },
    // 请求到这个id的详情 并替换到列表中去
    async handleGetDetailIntoList(id) {
      uni.showLoading({
        title: "加载中...",
      });
      const req = {
        POSTId: id,
      };
      const data = await this.$api.$get("/Member/GetPOSTDetail", req);
      let detailObj = data.Result_Data;
      console.log("handleGetPostDetail", detailObj);

      console.log("this.thumbedUpList", this.thumbedUpList);

      if (this.thumbedUpList.indexOf(detailObj.POST_ID) >= 0) {
        detailObj.isthumbsUp = true;
      } else {
        detailObj.isthumbsUp = false;
      }
      if (detailObj.POST_TITLE.length > 100) {
        detailObj.isShowSmall = 1;
        detailObj.smallText = detailObj.POST_TITLE.slice(0, 100);
      } else {
        detailObj.isShowSmall = 0;
      }
      let newList = [];
      this.postList.forEach((item) => {
        if (item.POST_ID === detailObj.POST_ID) {
          newList.push(detailObj);
        } else {
          newList.push(item);
        }
      });

      this.postList = newList;
      this.$forceUpdate();
      uni.hideLoading();
    },
    // 下拉刷新
    async handleRefresh(e) {
      console.log("handleRefresh", e);
      this.triggered = true;
      this.postList = [];
      this.listDetail = {
        pageIndex: 1,
        pageSize: 10,
        isOver: false,
      };
      await this.handleGetNowPostList();
      this.triggered = false;
    },
    // 把全部的/" 变为 "  全部的''变为'
    handleGetShowNewStr(str) {
      return str.replace(/\/"/g, '"').replace(/''/g, "'");
    },
    // 预览图片
    handlePreviewImage(obj, index) {
      let imgList = [];
      if (obj.ImageList && obj.ImageList.length > 0) {
        obj.ImageList.forEach((item) => {
          imgList.push(item.ImageUrl);
        });
      }
      console.log("imgList", imgList);
      console.log("index", index);
      uni.previewImage({
        current: imgList[index], // 当前显示图片的http链接
        urls: imgList, // 需要预览的图片http链接列表
      });
    },
    //   跳转详情
    handleGoDetail(obj) {
      console.log("obj", obj);
      uni.navigateTo({ url: `/pages/community/detail?id=${obj.POST_ID}` });
    },
    //   滚动到底部
    handleScrollBottom() {
      this.listDetail.pageIndex += 1;
      if (!this.listDetail.isOver) {
        this.handleGetNowPostList();
      }
    },
    //   展开
    handleChangeIsShowSmall(obj) {
      this.postList.forEach((item) => {
        if (obj.POST_ID === item.POST_ID && obj.isShowSmall > 0) {
          if (obj.isShowSmall === 1) {
            item.isShowSmall = 2;
          } else {
            item.isShowSmall = 1;
          }
        }
      });
    },
    // 拿到类型枚举
    async handleGetTypeList() {
      uni.showLoading({
        title: "加载中...",
      });
      const data = await this.$api.$get(
        "/EShangApiMain/FrameWork/GetFieldEnumTree",
        { FieldExplainField: "business_target" }
      );
      let list = this.$utils.wrapTreeNode(data.Result_Data.List);
      console.log("listlistlist", list);
      let typeList = [];
      let typeObj = {};
      // 拿到发帖的枚举
      if (list && list.length > 0) {
        list.forEach((item) => {
          if (item.value === 7000) {
            console.log("item", item);
            if (item.children && item.children.length > 0) {
              item.children.forEach((subItem) => {
                typeList.push(subItem);
                typeObj[subItem.value] = subItem.label;
              });
            }
          }
        });
      }
      this.tabObj = typeObj;
      this.tabList = typeList;
      this.tabSelect = typeList[0].value;
      uni.hideLoading();
      if (this.isFirst) {
        this.handleGetNowPostList();
      }
      console.log("this.tabSelect", this.tabSelect);
      console.log("handleGetTypeList");
    },
    // 拿到当前的发帖列表
    async handleGetNowPostList() {
      uni.showLoading({
        title: "加载中...",
      });

      await this.handleGetThumbedUp();

      const req = {
        searchParameter: {
          WECHATAPP_APPID: "wx4c497eddcec4a0e7",
          POST_STATE: 1,
          POST_TAGS: this.tabSelect,
        },
        SortStr: "PUBLISH_TIME desc",
        PageIndex: this.listDetail.pageIndex,
        PageSize: this.listDetail.pageSize,
      };
      console.log("handleGetNowPostListREq");
      const data = await this.$api.$post("/Member/GetPOSTList", req);
      let list = data.Result_Data.List;

      console.log("datadsad", list);

      if (list && list.length > 0) {
        list.forEach((item) => {
          item.POST_TITLE = this.handleGetShowNewStr(item.POST_TITLE);
          item.POST_CONTENT = this.handleGetShowNewStr(item.POST_CONTENT);
          if (this.thumbedUpList.indexOf(item.POST_ID) >= 0) {
            item.isthumbsUp = true;
          } else {
            item.isthumbsUp = false;
          }
          if (item.POST_TITLE.length > 100) {
            item.isShowSmall = 1;
            item.smallText = item.POST_TITLE.slice(0, 100);
          } else {
            item.isShowSmall = 0;
          }
        });

        if (list.length < this.listDetail.pageSize) {
          this.listDetail.isOver = true;
        }
      }

      let oldList = [];
      if (this.postList && this.postList.length > 0) {
        oldList = JSON.parse(JSON.stringify(this.postList));
      }

      this.postList = oldList.concat(list);
      console.log("handleGetNowPostList");
      this.isFirst = false;
      uni.hideLoading();
    },
    //   切换tab的选择
    async handleChangeTabSelect(value) {
      this.tabSelect = value;
      this.postList = [];
      this.listDetail = {
        pageSize: 10,
        pageIndex: 1,
        isOver: false,
      };
      await this.handleGetNowPostList();
      this.$forceUpdate();
    },
    // 新增发帖
    handleAddNewPost() {
      if (!this.user.MEMBERSHIP_ID) {
        let _this = this;
        uni.showModal({
          title: "温馨提示",
          content: "请您授权登录后再操作。",
          success(res) {
            if (res.confirm) {
              if (_this.loginType === "min") {
                uni.navigateTo({ url: "/pages/register/index" });
              } else {
                uni.navigateTo({ url: "/pages/login/index" });
              }
            }
          },
        });
        return;
      }

      uni.navigateTo({
        url: "/pages/community/addNewPost",
      });
    },
  },
};
</script>

<style scoped lang="less">
.main {
  width: 100vw;
  height: 100vh;
  .bannerBox {
    width: 100%;
    .swiper {
      width: 100%;
      height: 100%;
      .swiperItem {
        width: 100%;
        height: 100%;
        .swiperImg {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .communityContent {
    width: 100%;
    box-sizing: border-box;
    padding-bottom: 58px;
    .contentTab {
      width: 100%;
      height: 90rpx;
      border-bottom: 1px solid #f5f6f7;
      display: flex;
      .tabItem {
        width: calc(100% / 3);
        text-align: center;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #716f69;
        line-height: 40rpx;
        font-style: normal;
        box-sizing: border-box;
        padding-top: 32rpx;
      }
      .selectTabItem {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #130f05;
        line-height: 40rpx;
        font-style: normal;
        position: relative;
      }
      .selectTabItem:after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        background: #ba922f;
        width: 2rem;
        height: 6rpx;
      }
    }

    .scrollContent {
      width: 100%;
      height: calc(100% - 90rpx);
      box-sizing: border-box;
      padding: 0 32rpx;
      .scrollItem {
        width: 100%;
        border-bottom: 1px solid #f5f6f7;
        padding: 24px 0;
        .itemTop {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .topLeft {
            width: calc(100% - 190rpx);
            display: flex;
            align-items: center;
            .profileBox {
              width: 72rpx;
              height: 72rpx;
              margin-right: 16rpx;
              .profile {
                width: 100%;
                height: 100%;
                border-radius: 50%;
              }
            }
            .otherBox {
              width: calc(100% - 88rpx);
              .userName {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 28rpx;
                color: #130f05;
                line-height: 40rpx;
                text-align: left;
                font-style: normal;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
              }
              .timeBox {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 24rpx;
                color: #716f69;
                line-height: 36rpx;
                text-align: left;
                font-style: normal;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
              }
            }
          }

          .rightBox {
            width: 180rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .commentBox {
              display: flex;
              align-items: center;
              .commentIcon {
                width: 32rpx;
                height: 32rpx;
                margin-right: 4rpx;
              }
              .commentText {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 24rpx;
                color: #716f69;
                line-height: 36rpx;
                text-align: left;
                font-style: normal;
              }
              .thumbsUp {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 24rpx;
                color: #ba922f;
                line-height: 36rpx;
                text-align: left;
                font-style: normal;
              }
            }
          }
        }

        .itemContent {
          width: 100%;
          margin-top: 16rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 28rpx;
          color: #130f05;
          line-height: 40rpx;
          text-align: justify;
          font-style: normal;
          margin-bottom: 12rpx;
          .expend {
            margin-left: 8rpx;
            color: #ba922f;
          }
        }

        .imageList {
          width: 100%;
          margin-top: 12rpx;
          display: flex;
          align-items: center;
          //   justify-content: space-between;
          flex-wrap: wrap;
          .imageItem {
            width: 218rpx;
            height: 218rpx;
            margin-right: 8rpx;
            margin-bottom: 8rpx;
            border-radius: 8rpx;
            overflow: hidden;
            .image {
              width: 100%;
              height: 100%;
            }
          }
        }
      }

      .inBottom {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        .bottomText {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 26rpx;
          color: #d0d0d0;
          line-height: 40rpx;
          text-align: justify;
          font-style: normal;
          position: relative;
          padding: 6rpx 0;
        }
        .bottomText::after {
          content: "";
          width: 30vw;
          height: 2rpx;
          background: #e0e0e0;
          position: absolute;
          left: -32vw;
          top: 50%;
        }
        .bottomText::before {
          content: "";
          width: 30vw;
          height: 2rpx;
          background: #e0e0e0;
          position: absolute;
          right: -32vw;
          top: 50%;
        }
      }
    }
  }
  .communityContent ::-webkit-scrollbar {
    width: 0;
  }

  .addNewPost {
    width: 100%;
    height: 56px;
    padding-bottom: 32rpx;
    // display: inline-block;
    // padding: 16rpx 24rpx;
    // border-radius: 36rpx;
    // background: #ba922f;
    box-sizing: border-box;
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    // bottom: 40px;
    // left: 50%;
    // transform: translateX(-50%);
    .newPostBox {
      display: flex;
      align-items: center;
      padding: 16rpx 24rpx;
      border-radius: 36rpx;
      background: #ba922f;
      .addIcon {
        width: 28rpx;
        height: 28rpx;
        margin-right: 8rpx;
      }
      .addText {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #ffffff;
        line-height: 40rpx;
        text-align: justify;
        font-style: normal;
      }
    }
  }
}
</style>
