<template>
  <view class="page">
    <view v-if="iniLoading" class="guide-container">
      <view class="select">
        <!-- 搜索 -->
        <view class="search-wrapper">
          <view class="search-left">
            <image src="/static/data/images/searchs.png" />
            <input
              :value="guideTitle"
              @input="handleInput"
              confirm-type="search"
              @confirm="handleSearch"
              placeholder="搜索"
              placeholder-class="input-placeholder"
            />
          </view>
          <!-- 收藏 -->
          <view class="search-right">
            <view v-if="isFocus" class="" @click="handleCancle">取消</view>
            <navigator v-else class="search-collect" url="/pages/collect/index">
              <image src="/static/data/images/collect.png" />
              <view class="">收藏</view>
            </navigator>
          </view>
        </view>

        <!-- <view class="m-crumbs"><text>当前组织：{{ agencyName }}</text></view> -->

        <!-- 所属组织 -->
        <!-- <view class="m-filter" @click="selectAgency">
          <text>{{ gridShowName || agencyName }}</text>
          <image
            src="/static/data/images/arrow4-down.png"
            mode="aspectFit"
          ></image>
        </view> -->

        <view :class="'filter-wrapper ' + (showMask && 'show-wrapper')">
          <view class="filter-arrow">
            <view @click="handleDown">
              <image src="/static/data/images/arrow-up.png" />
            </view>
          </view>
          <view class="filter-list">
            <view
              class="filter-item"
              :data-id="item.categoryCode"
              :data-index="index"
              @click="handleDownFilter"
              v-for="(item, index) in tabsList"
              :key="index"
            >
              {{ item.categoryName }}
            </view>
          </view>
        </view>

        <!-- 指南类型 -->
        <view :class="'tabs-wrapper ' + (showMask && 'tabs-no')">
          <scroll-view
            class="tabs"
            :scroll-x="true"
            :enhanced="true"
            :show-scrollbar="false"
            :scroll-into-view="toTabs"
          >
            <view class="tabs-list">
              <view
                :id="'index' + index"
                :class="'tabs-item ' + (tabsCurrent === index && 'tabs-on')"
                :data-id="item.categoryCode"
                :data-index="index"
                @click="handleTabs"
                v-for="(item, index) in tabsList"
                :key="index"
              >
                {{ item.categoryName }}
              </view>
            </view>
          </scroll-view>
          <view class="tabs-down" @click="handleDown">
            <image
              src="/static/data/images/arrow-down3.png"
              mode="aspectFit"
            ></image>
          </view>
        </view>
      </view>

      <!-- 文章列表 -->
      <view :class="'tabs-mask ' + (showMask && 'show-mask')"></view>
      <view>
        <view v-if="guideList.length > 0">
          <view class="m-list">
            <view
              class="item"
              :data-aid="item.issueApplicationId"
              :data-gid="item.gridId"
              :data-id="item.guideId"
              @click="selectIssue"
              v-for="(item, index) in guideList"
              :key="index"
            >
              <view class="row row1" style="display: flex">
                <view class="readFlag">
                  {{ item.readFlag === 1 ? "已读" : "未读" }}
                </view>
                <text class="title">{{ item.title }}</text>
              </view>
            </view>
          </view>

          <view class="m-more">
            <text v-if="noMore">没有更多了</text>
            <text v-else-if="!noMore">上拉查看更多</text>
          </view>
        </view>

        <view class="m-nothing" v-if="pageEmpty">
          <image
            class="arrow"
            src="/static/data/images/empty.png"
            style="width: 464rpx; height: 530rpx"
          />
          <view></view>
        </view>
      </view>
    </view>

    <view v-if="selectGrid">
      <select-grid
        :grid-id-list="gridIdList"
        @onClose="closeAgency"
        @onConfirm="confirmAgency"
      />
    </view>
  </view>
</template>

<script>
import selectGrid from "@/components/select-grid/select-grid";
import * as userTools from "../../utils/user";
import CustomerApi from "../../utils/api";
const app = getApp();
export default {
  components: {
    selectGrid,
  },
  data() {
    return {
      userInfo: null,
      gridInfo: null,
      iniLoading: false,
      showMask: false,
      pageEmpty: false,
      noMore: false,
      isFocus: false,
      agencyId: "",
      agencyName: "",
      toTabs: "index0",
      tabsCurrent: 0,
      tabsList: [],
      gridIdList: [],
      gridShowName: "",
      selectGrid: false,
      guideList: [],
      pageNo: 1,
      pageSize: 20,
      categoryId: "",
      guideTitle: "",
      agencyInfo: {},
      showPage: false,
    };
  },
  onLoad() {
    function getIframeQueryParams() {
      // 使用URLSearchParams解析查询参数
      function getStringAfterQuestionMark(str) {
        return str.split("?").pop();
      }
      var result = getStringAfterQuestionMark(window.location.href);
      var params = new URLSearchParams(result);
      // 创建一个对象来存储解析后的参数
      var queryParams = {};
      // 遍历所有查询参数并存储到对象中
      params.forEach((value, key) => {
        queryParams[key] = value;
      });

      return queryParams;
    }
    const query = getIframeQueryParams();
    const token =
      process.env.NODE_ENV == "development"
        ? "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhcHAiOiJnb3YiLCJjbGllbnQiOiJ3ZWIiLCJleHAiOjE4MTQxNDkxOTksInVzZXJJZCI6IjE3MTQ1Njc3MDIxNDQ3NzgyNDEiLCJpYXQiOjE3MTk1NDExOTl9.Rm5CP020giWIlMDXUin22Td4vJIRlCxRsM9YBsRTyrOvEjqjdlR554R3PtAkwDErgVYkBLgnmqpomDKo_Mfktg"
        : query.token;
    const gridId =
      process.env.NODE_ENV == "development"
        ? "32a6084b-f7c9-11ee-96cf-fa163ef15b63"
        : query.gridId;
    userTools.setStoreUserInfo(
      JSON.stringify({
        gridId: gridId,
        authorization: token,
        customerId: "1535072605621841922",
      })
    );
    userTools.setStoreGridInfo(
      JSON.stringify({
        gridId: gridId,
      })
    );
    this.init();

    // 授权登录、注册返回
    // if (app.globalData.session) {
    //   _this.init();
    //   console.log("标识");
    // }
  },
  onShow() {
    this.setData({
      tabsCurrent: 0,
    });
    if (this.showPage) {
      uni.showLoading();
      this.fetchAgencyList();
      this.fetchGuideCategory();
    }
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      pageNo: 1,
      guideList: [],
    });
    this.fetchGuideList();
  },
  // 上拉加载
  onReachBottom() {
    // 页面被拉到底部
    if (this.noMore) {
      return;
    }
    let page = this.pageNo + 1;
    this.setData({
      pageNo: page,
    });
    this.fetchGuideList();
  },
  methods: {
    init() {
      let userInfo = userTools.getStoreUserInfo();
      let gridInfo = userTools.getStoreGridInfo();
      this.setData({
        userInfo,
        gridInfo,
        showPage: true,
      });
      this.fetchAgencyList();
      this.fetchGuideCategory();
    },

    async fetchAgencyList() {
      let result = await CustomerApi.fetchAgencyList();
      let { code, data } = result;
      if (code == 0) {
        this.setData({
          agencyInfo: data,
          agencyId: data.agencyId,
          agencyName: data.agencyName,
          gridIdList: [data.agencyId],
        });
      }
    },

    async fetchGuideCategory() {
      let params = {
        queryOrigin: "query",
      };
      let result = await CustomerApi.fetchGuideCategory(params);
      let { code, data } = result;
      if (code == 0) {
        this.setData(
          {
            tabsList: data,
            categoryId: data[0].categoryCode,
            guideList: [],
          },
          () => {
            this.fetchGuideList();
          }
        );
      }
    },

    async fetchGuideList() {
      let { categoryId, agencyId, guideTitle, pageNo, pageSize } = this;
      let params = {
        categoryCode: categoryId,
        agencyId: agencyId,
        guideTitle: guideTitle,
        pageNo: pageNo,
        pageSize: pageSize,
      };
      let result = await CustomerApi.fetchGuideList(params);
      let { code, data } = result;
      if (code == 0) {
        uni.hideLoading();
        let list = data.list;
        this.setData({
          iniLoading: true,
		  guideList: list,
        });
        // this.p_formatItemForData(list);
        this.p_judgeNoMoreData(list);
        this.p_judgePageEmpty(list);
        uni.stopPullDownRefresh();
      }
    },

    // 格式化数据
    // p_formatItemForData(list) {
    //   this.$spliceData({
    //     guideList: [this.guideList.length, 0, ...list],
    //   });
    // },

    // 页面是否为空
    p_judgePageEmpty(list) {
      if (this.pageNo == 1 && list.length == 0) {
        this.setData({
          pageEmpty: true,
        });
      } else {
        this.setData({
          pageEmpty: false,
        });
      }
    },

    // 本次加载是否为空
    p_judgeNoMoreData(list) {
      if (list.length < this.pageSize) {
        this.setData({
          noMore: true,
        });
      } else {
        this.setData({
          noMore: false,
        });
      }
    },

    handleInput(e) {
      let val = e.detail.value;
      if (!val) {
        this.setData(
          {
            pageNo: 1,
            noMore: false,
            isFocus: false,
            guideTitle: val,
            guideList: [],
          },
          () => {
            this.fetchGuideList();
          }
        );
      } else {
        this.setData({
          isFocus: true,
        });
      }
    },

    handleSearch(e) {
      let val = e.detail.value;
      this.setData(
        {
          pageNo: 1,
          noMore: false,
          guideTitle: val,
          guideList: [],
        },
        () => {
          this.fetchGuideList();
        }
      );
    },

    // handleFocus() {
    //   this.setData({
    //     isFocus: !this.data.isFocus
    //   });
    // },
    handleCancle() {
      this.setData({
        guideTitle: "",
        isFocus: false,
        noMore: false,
        pageNo: 1,
        guideList: [],
      });
      this.fetchGuideList();
    },

    handleTabs(e) {
      console.log("eeeee", e.currentTarget.dataset);
      var _a = e.currentTarget.dataset;
      var index = _a.index;
      var id = _a.id;
      this.setData({
        tabsCurrent: index,
        pageNo: 1,
        noMore: false,
        categoryId: id,
        guideList: [],
      });
      console.log("tabsCurrent", index, this.tabsCurrent);
      this.fetchGuideList();
    },

    handleDownFilter(e) {
      var _a = e.currentTarget.dataset;
      var index = _a.index;
      var id = _a.id;
      this.setData({
        tabsCurrent: index,
        toTabs: "index" + index,
        showMask: false,
        pageNo: 1,
        noMore: false,
        categoryId: id,
        guideList: [],
      });
      this.fetchGuideList();
    },

    handleDown() {
      this.setData({
        showMask: !this.showMask,
      });
    },

    closeAgency() {
      this.setData({
        selectGrid: false,
      });
    },

    confirmAgency(obj) {
      let { gridIdList, gridInfo, showName } = obj;
      console.log(gridInfo.agencyName, gridInfo.agencyId);
      this.setData(
        {
          gridIdList: gridIdList,
          gridShowName: showName,
          agencyId: gridInfo.agencyId,
          pageNo: 1,
          guideList: [],
        },
        () => {
          this.fetchGuideList();
        }
      );
    },

    selectAgency() {
      this.setData(
        {
          selectGrid: true,
          guideList: [],
        },
        () => {
          this.fetchGuideList();
        }
      );
    },

    selectIssue(e) {
      var _a = e.currentTarget.dataset;
      var id = _a.id;
      var gid = _a.gid;
      var aid = _a.aid; // promise_wx_api_1.wxNavigateTo("/subpages/index/pages/workguide/detail", {
      //   guideId: id
      // });
      uni.navigateTo({
        url: `/pages/detail/index?guideId=${id}`,
      });
    },
  },
};
</script>
<style>
@import "/data/acss/converge-issue.css";
@import "/data/acss/work-guide.css";

.readFlag {
  width: 50rpx;
  height: 30rpx;
  border: 2rpx solid gray;
  font-size: 20rpx;
  margin-right: 10rpx;
  text-align: center;
  border-radius: 2rpx;
  line-height: 30rpx;
  margin-top: 8rpx;
}
</style>
