<template>
  <!-- <u-sticky bgColor="#fff"> </u-sticky> -->

  <u-navbar :autoBack="false" :placeholder="true" :safeAreaInsetTop="true" :bgColor="proxy.$settingStore.themeColor.color" @rightClick="rightButtonClick()">
    <template #left>
      <view class="u-nav-slot">
        <!-- <u-icon name="arrow-left" size="19" color="#fff" style="display: none"></u-icon> -->
        <view class="u-navbar__content__title" style="color: #fff">应用中心</view>
      </view>
    </template>
    <template #center>
      <view class="u-nav-slot"> </view>
    </template>
    <template #right>
      <view class="u-nav-slot">
        <u-icon name="plus" size="19" color="#fff"></u-icon>
      </view>
    </template>
  </u-navbar>

  <!-- <pagesHarder></pagesHarder> -->

  <oa-scroll
    class="scroll-height"
    :style="{ height: `calc(100vh - (50px + ${proxy.$settingStore.barHightTop} + ${proxy.$settingStore.tabBarHeight}))` }"
    :refresherLoad="false"
    :refresherEnabled="true"
    :refresherDefaultStyle="'none'"
    :refresherThreshold="44"
    :refresherBackground="'#f5f6f7'"
    @refresh="refresh"
  >
    <template #default>
      <!-- <u-loadmore :status="arrayList.loadStatus" loadingText="" loadmoreText="" :icon="true" /> -->
      <view class="home-container uni-content-body">
        <!-- 下拉列表 开始 -->
        <u-transition :show="dialogFlag" :duration="200" mode="fade">
          <view class="transition" @click="rightButtonClick()">
            <view class="transition-section" :style="{ top: proxy.$settingStore.barHightTop }">
              <view class="transition-section-content" @click="scanCode()">
                <text class="transition-section-content-icon iconfont ucicon-saoyisao"></text>
                <view class="transition-section-content-text"> 扫一扫 </view>
              </view>
              <!-- <div class="transition-section-divider"></div>
            <view class="transition-section-content">
              <text class="transition-section-content-icon iconfont ucicon-saoyisao"></text>
              <view class="transition-section-content-text">发起群聊 </view>
            </view> -->
            </view>
          </view>
        </u-transition>
        <!-- 下拉列表 结束 -->

        <!-- 轮播图 开始 -->
        <u-swiper v-if="swiperBool" :list="swiperList" :interval="swiperTime" indicatorMode="line" radius="0" height="160" indicator circular keyName="url" @click="swiperClick" @change="swiperChange">
        </u-swiper>

        <image v-if="!swiperBool" style="width: 100%; height: 160px" src="@/static/images/index/banner1.png"></image>

        <view class="app-info-notice bg-white radius shadow-default margin-lr-sm margin-bottom-sm">
          <view class="flex">
            <view class="info-title text-df">综合智慧云</view>
            <view class="info-time text-sm">07-25 19:23</view>
          </view>
          <view class="info-content text-sm">综合智慧云app，助力企业数字化转型升级，超多业务功能，全新部署上线，操作简单流畅...</view>
        </view>

        <!-- 轮播图 结束 -->

        <!-- 宫格列表 -->
        <view class="section2 section bg-white margin-bottom-sm" v-if="recentlyUsed.length > 0">
          <view style="color: #000000; font-size: 14px; padding: 10px 10px 5px 10px">最近使用</view>
          <view class="cu-list grid col-5 no-border">
            <view class="cu-item justify-center align-center" @tap="navItemClick(item)" v-for="(item, index) in recentlyUsed.slice(0, 5)" :key="index">
              <image :src="item.meta.icon" style="width: 40px; height: 40px"></image>
              <!-- <view class="cu-tag badge" v-if="item.badge != 0">
              <block v-if="item.badge != 0">{{ item.badge > 99 ? "99+" : item.badge }}</block>
            </view> -->
              <text style="font-size: 12px">{{ item.meta.title }}</text>
            </view>
          </view>
        </view>
        <!-- 宫格列表 end -->

        <!-- 宫格列表 -->
        <view class="section2 section bg-white">
          <view style="color: #000000; font-size: 14px; padding: 10px 10px 5px 10px">常用功能</view>
          <view class="cu-list grid col-5 no-border">
            <view class="cu-item justify-center align-center" @tap="navItemClick(item)" v-for="(item, index) in cuIconList" :key="index">
              <image :src="item.meta.icon" style="width: 40px; height: 40px"></image>
              <!-- <view class="cu-tag badge" v-if="item.badge != 0">
              <block v-if="item.badge != 0">{{ item.badge > 99 ? "99+" : item.badge }}</block>
            </view> -->
              <text style="font-size: 12px">{{ item.meta.title }}</text>
            </view>
          </view>
        </view>
        <!-- 宫格列表 end -->
      </view>
    </template>
  </oa-scroll>

  <oa-tabbar :tabbarValue="0"></oa-tabbar>
</template>

<script setup>
import searchSelect from "@/components/searchSelect/searchSelect.vue";

import * as jwx from "@/utils/jssdk.js"; //引入js sdk的封装

import { onReady, onLoad, onShow, onNavigationBarButtonTap, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
import { ref, onMounted, inject, shallowRef, reactive, getCurrentInstance, toRefs } from "vue";
import { getToken } from "@/utils/auth";
import { useStores, publicStores } from "@/store/modules/index";

import { scan_push, getHomePageData, getFunctionalModuleStatistics, getAppRouters, qrCodeSend, getMobileBanner } from "@/api/index";

const useStore = useStores();
const publicStore = publicStores(); //全局公共Store
const BASE_URL = inject("$BASE_URL");
const { proxy } = getCurrentInstance();

const arrayList = reactive({
  dialogFlag: false,

  swiperBool: false,
  swiperIndex: 0,
  swiperTime: 5000,
  swiperList: [],

  cuIconList: [],
  recentlyUsed: [],
});

const { dialogFlag, swiperBool, swiperIndex, swiperTime, swiperList, cuIconList, recentlyUsed } = toRefs(arrayList);

/**
 * @获取轮播图下标
 * @change事件
 */
function swiperChange(e) {
  swiperIndex.value = e.current;
}

/**
 * @轮播图点击事件
 */
function swiperClick(list) {
  if (typeof list == "object") {
    let linkType = swiperList.value[swiperIndex.value].linkType;
    let url = swiperList.value[swiperIndex.value].link;

    if (url) {
      if (linkType == 1) {
        uni.navigateTo({
          url: url,
        });
      } else {
        uni.navigateTo({
          url: "/pages/common/webview/index?url=" + url,
        });
      }
    }
  }
}

onLoad((option) => {
  uni.hideTabBar(); //隐藏自带tabbar

  if (uni.getStorageSync(useStore.$state.name + useStore.$state.tenantId)) {
    recentlyUsed.value = uni.getStorageSync(useStore.$state.name + useStore.$state.tenantId);
  }

  getAppRoutersData(); //调用路由信息接口
  getMobileBannerApi(); //调用banner图接口
});

/**
 * @scrollView刷新数据
 */
function refresh() {
  getAppRoutersData(); //调用路由信息接口
  getMobileBannerApi(); //调用banner图接口
}

/**
 * @扫码功能
 */
function scanCode() {
  //#ifdef H5 || MP-WEIXIN
  jwx.configWeiXin((jweixin) => {
    console.log(2);
    jweixin.scanQRCode({
      needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
      scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
      success: function (res) {
        setTimeout(function () {
          scan_push({ ercode: res.resultStr }).then((res) => {
            if (res.data.flag) {
              uni.showToast({
                title: "扫码成功",
                icon: "none",
              });
            }
          });
        }, 1000);
      },
    });
  });
  //#endif

  //#ifdef APP-PLUS
  uni.scanCode({
    scanType: ["qrCode"],
    success: (res) => {
      let list = JSON.parse(res.result);
      uni.showToast({
        title: "扫码成功",
        icon: "none",
      });
      qrCodeSend({
        qrCode: list.uid,
        tenantId: useStore.$state.tenantId,
        userName: useStore.$state.name,
      }).then((res) => {});
    },
    fail: (err) => {
      console.log("扫码失败", err);
    },
    complete: () => {
      console.log("扫码结束");
    },
  });
  //#endif
}

/**
 * @获取地理位置
 */
function getLocation() {
  jwx.configWeiXin((jweixin) => {
    // 微信公众号获取位置
    jweixin.getLocation({
      type: "gcj02", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function (res) {
        alert(res.longitude);
      },
    });
  });
}

/**
 * @九宫格页面跳转
 */
function navItemClick(item) {
  if (item.path) {
    item.sort = 0;

    recentlyUsed.value.push(item);

    if (recentlyUsed.value.length > 0) {
      recentlyUsed.value = recentlyUsed.value.filter((currentValue, currentIndex, selfArr) => {
        return selfArr.findIndex((x) => x.path === currentValue.path) === currentIndex;
      });

      recentlyUsed.value.filter((el) => {
        if (el.path === item.path) {
          el.sort++;
        }
      });
    }

    recentlyUsed.value = publicStore.sortEvent(recentlyUsed.value, 1);

    uni.setStorageSync(useStore.$state.name + useStore.$state.tenantId, recentlyUsed.value);

    if (item.path.indexOf("http") != -1) {
      uni.navigateTo({
        url: "/pages/common/webview/index?url=" + item.path,
      });
    } else {
      uni.navigateTo({
        url: item.path,
      });
    }
  } else {
    uni.showModal({
      title: "Tips",
      content: "此模块开发中~",
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
        } else if (res.cancel) {
        }
      },
    });
  }
}

/**
 * @右侧按钮点击事件
 */
function rightButtonClick() {
  dialogFlag.value = !dialogFlag.value;
}

/**
 * @轮播图
 * @api接口请求
 */
function getMobileBannerApi() {
  getMobileBanner({
    tenantId: useStore.$state.tenantId,
  }).then((res) => {
    if (res.data.length > 0) {
      swiperList.value = [];
      swiperBool.value = res.data[0].openNot == 1 ? true : false;
      swiperTime.value = res.data[0].carouselTime * 1000;

      for (let i = 1; i <= 5; i++) {
        if (res.data[0]["bannerPath" + i]) {
          swiperList.value.push({
            url: res.data[0]["bannerPath" + i],
            link: res.data[0]["linkUrl" + i],
            linkType: res.data[0]["linkType" + i],
            type: "image",
          });
        }
      }
    }
  });
}

/**
 * @获取路由信息
 * @api接口请求
 */
function getAppRoutersData() {
  getAppRouters({
    // domain: window.location.host.indexOf("localhost") != -1 ? "localhost:81" : window.location.host,
    // platformType: "MOB",
    // domain :'172.16.120.165:13201'
    // domain :'172.16.120.165:13203'
  }).then((res) => {
    res.data.forEach((el) => {
      el.meta.icon = `/static/icons/index/${el.meta.icon}.png`;
    });

    cuIconList.value = res.data;
  });
}

onShow(() => {});

// 自定义导航事件
onNavigationBarButtonTap((e) => {
  if (e.float == "right") {
    // alert("你点击了扫一扫");
    scanCode();
  } else {
    rightButtonClick();
  }
});
</script>

<style lang="scss" scoped>
.home-container {
  .uni-content-body {
    // #ifdef H5
    padding-bottom: 50px;
    // #endif

    .transition {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 1100;

      .transition-section {
        position: absolute;
        top: 10px;
        right: 15px;
        background-color: #fff;
        border-radius: 10px;
        box-shadow: 0px 0px 15px 0 rgba(0, 0, 0, 0.2);

        .transition-section-divider {
          border-bottom: 0.5px rgba(0, 0, 0, 0.1) solid;
          margin: 0 20px;
        }

        .transition-section-content {
          display: flex;
          padding: 15px 20px;

          .transition-section-content-icon {
            font-size: 18px;
            color: #000;
          }

          .transition-section-content-text {
            margin: 0 20px;
          }
        }

        .transition-section-content:first-child {
          padding-top: 15px;
          border-radius: 10px 10px 0 0;
        }

        .transition-section-content:last-child {
          padding-bottom: 15px;
          border-radius: 0 0 10px 10px;
        }

        .transition-section-content:hover {
          // transform: 3s;
          // transition: all 600ms cubic-bezier(0.3, 1, 0.2, 1);
          transition: all 3s cubic-bezier(0.7, -0.5, 0.2, 2);
          background-color: rgba(0, 0, 0, 0.1);
        }
      }
    }
  }
}
</style>
