<template>
  <u-navbar :autoBack="false" :placeholder="true" :safeAreaInsetTop="true" :bgColor="proxy.$settingStore.themeColor.color">
    <template #left>
      <view class="u-navbar__content__left__item">
        <view class="u-navbar__content__left__item__title">应用中心</view>
      </view>
    </template>
    <template #center>
      <view class="u-navbar__content__left__item"> </view>
    </template>
    <template #right>
      <view class="u-navbar__content__left__item">
        <text class="iconfont oaIcon-jiahao font20" @click="rightButtonClick()"></text>
      </view>
    </template>
  </u-navbar>

  <!-- <u-no-network :zIndex="10080" @disconnected="disconnected" @connected="connected" @retry="retry"></u-no-network> -->

  <oa-scroll
    customClass="scroll-height"
    :customStyle="{ height: `calc(100vh - (94px + ${proxy.$settingStore.StatusBarHeight} + ${proxy.$settingStore.tabBarHeight}))` }"
    :refresherLoad="false"
    :refresherEnabled="true"
    :refresherEnabledTitle="false"
    :refresherDefaultStyle="'none'"
    :refresherThreshold="44"
    :refresherBackground="'#f5f6f7'"
    @refresh="refresh"
  >
    <template #default>
      <view class="home-container">
        <!-- 右侧弹窗 -->
        <u-transition :show="dialogFlag" :duration="200" mode="fade">
          <view class="transition" @click="rightButtonClick()">
            <view class="transition-section" :style="{ top: '44px' + proxy.$settingStore.StatusBarHeight }">
              <view class="transition-section-content" @click="scanCode()">
                <text class="transition-section-content-icon iconfont oaIcon-saoyisao"></text>
                <view class="transition-section-content-text"> 扫一扫 </view>
              </view>
            </view>
          </view>
        </u-transition>

        <!-- 轮播图 -->
        <u-swiper v-if="state.swiperBool" :list="state.swiperList" :interval="state.swiperTime" indicatorMode="line" radius="0" height="160" indicator circular keyName="url" @click="swiperClick">
        </u-swiper>
        <image v-if="!state.swiperBool" style="width: 100%; height: 160px" src="http://192.168.123.165:9300/statics/images/index/banner1.png"></image>

        <!-- 天气 -->
        <!-- #ifdef APP-PLUS || H5 -->
        <oaWeather ref="oaWeatherRef"></oaWeather>
        <!-- #endif -->

        <!-- 最近使用宫格 -->
        <view class="grid-area bg-white" v-if="state.recentlyUsed.length > 0">
          <view class="grid-area_title">最近使用</view>
          <view class="grid-area_center cu-list grid col-5 no-border">
            <view class="grid-area_center_item cu-item justify-center align-center" @tap="navItemClick(item)" v-for="(item, index) in state.recentlyUsed.slice(0, 5)" :key="index">
              <image class="grid-area_center_item_image" :src="item.meta.icon"></image>
              <text class="grid-area_center_item_title">{{ item.meta.aliasTitle ? item.meta.aliasTitle : item.meta.title }}</text>
            </view>
          </view>
        </view>

        <!-- 常用功能宫格 -->
        <view class="grid-area bg-white">
          <view class="grid-area_title">常用功能</view>
          <view class="grid-area_center cu-list grid col-5 no-border">
            <view class="grid-area_center_item cu-item justify-center align-center" @tap="navItemClick(item)" v-for="(item, index) in state.cuIconList" :key="index">
              <image class="grid-area_center_item_image" :src="item.meta.icon"></image>
              <text class="grid-area_center_item_title">{{ item.meta.aliasTitle ? item.meta.aliasTitle : item.meta.title }}</text>
            </view>
          </view>
        </view>
      </view>
    </template>
  </oa-scroll>

  <oaTabbar :tabbarValue="0" :tabbarList="proxy.$constData.homeTabbar"></oaTabbar>
</template>

<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import { onReady, onLoad, onShow, onNavigationBarButtonTap, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
import { ref, onMounted, inject, shallowRef, reactive, getCurrentInstance, toRefs, nextTick } from "vue";
/*----------------------------------接口引入-----------------------------------*/
import { scan_push, getHomePageData, getFunctionalModuleStatistics, getAppRouters, qrCodeSend, getMobileBanner } from "@/api/index";
/*----------------------------------组件引入-----------------------------------*/
import oaWeather from "@/components/oa-weather/index"
import oaTabbar from "@/components/oa-tabbar/index";
/*----------------------------------store引入-----------------------------------*/
import { useStores } from "@/store/modules/index";
/*----------------------------------公共方法引入-----------------------------------*/
import * as jwx from "@/utils/jssdk.js"; //引入js sdk的封装
import { getToken, setToken, removeToken } from "@/utils/auth";
import { storage, storageSystem } from "@/utils/storage"; // 公共方法引用
/*----------------------------------公共变量-----------------------------------*/
const { proxy } = getCurrentInstance();
const useStore = useStores();
/*----------------------------------变量声明-----------------------------------*/
const state = reactive({
  dialogFlag: false,

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

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

const { dialogFlag } = toRefs(state);

/**
 * @初始化
 */
async function init(options) {
  //#ifdef H5
  await useStore.GetWxOpenId(2, options); //调用获取微信公众号openId
  //#endif

  setTimeout(() => {
    getAppRoutersData(); //调用路由信息接口
    getMobileBannerApi(); //调用banner图接口
    getLocation(); //调用获取地理位置方法
  }, 1000);

  //#ifdef APP-PLUS
  proxy.$settingStore.baseAppInfo(), setInterval(proxy.$settingStore.baseAppInfo, 1000 * 60 * 5); //动态获取用户设备信息
  proxy.$settingStore.openWebSocket(); //开启WebSocket
  //#endif
}

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

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

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

    state.recentlyUsed.push(item);
    state.recentlyUsed = proxy.$common.uniq(state.recentlyUsed, "path");
    state.recentlyUsed.filter((el) => {
      if (el.path === item.path) {
        el.meta.icon = item.meta.icon;
        el.sort++;
      }
    });
    state.recentlyUsed = proxy.$common.sortEvent(state.recentlyUsed, 1);

    storageSystem.set("homeList", state);

    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 connected() {
//   refresh();
//   uni.setNavigationBarColor({
//     frontColor: "#FFFFFF", //字体颜色
//   });
// }

// function disconnected() {
//   uni.setNavigationBarColor({
//     frontColor: "#000000", //字体颜色
//   });
// }

/**
 * @scrollView刷新数据
 */
function refresh() {
  getAppRoutersData(); //调用路由信息接口
  getMobileBannerApi(); //调用banner图接口
  getLocation(); //调用获取地理位置方法
}

/**
 * @扫码功能
 */
function scanCode() {
  //#ifdef H5 || MP-WEIXIN
  jwx.configWeiXin((jweixin) => {
    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({
    autoZoom: false,
    scanType: ["qrCode"],
    success: (res) => {
      let list = JSON.parse(res.result);
      uni.showToast({
        title: "扫码成功",
        icon: "none",
      });
      qrCodeSend({
        qrCode: list.uid,
        tenantId: useStore.tenantId,
        userName: useStore.name,
      }).then((res) => {});
    },
    fail: (err) => {
      console.log("扫码失败", err);
    },
    complete: () => {
      console.log("扫码结束");
    },
  });
  //#endif
}

/**
 * @获取地理位置
 */
function getLocation() {
  var latitude = proxy.$settingStore.deviceList.latitude;
  var longitude = proxy.$settingStore.deviceList.longitude;

  //#ifdef H5 || MP-WEIXIN
  // jwx.configWeiXin((jweixin) => {
  //   // 微信公众号获取位置
  //   jweixin.getLocation({
  //     type: "gcj02", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
  //     success: function (res) {
  //       alert(res.longitude);
  //     },
  //   });
  // });
  proxy.$refs["oaWeatherRef"].getWeather("上海");
  //#endif

  //#ifdef APP-PLUS
  if (latitude && longitude) {
    proxy.$refs["oaWeatherRef"].getWeather(latitude + ":" + longitude);
  } else {
    proxy.$refs["oaWeatherRef"].getWeather("上海");
  }
  //#endif
}

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

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

      for (let i = 1; i <= 5; i++) {
        if (res.data[0]["bannerPath" + i]) {
          state.swiperList.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().then((res) => {
    state.cuIconList = res.data;
    storageSystem.set("homeList", state);
  });
}

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

onShow(() => {
  var storages = storageSystem.get("homeList");
  Object.keys(storages).forEach((key) => {
    state[key] = storages[key];
  });
});
</script>

<style lang="scss" scoped>
.home-container {
  .transition {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1100;

    &-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);

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

      &-content {
        display: flex;
        padding: 15px 20px;

        &-icon {
          font-size: 18px;
          color: #000;
        }

        &-text {
          margin: 0 20px;
        }
      }

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

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

      &-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);
      }
    }
  }

  .grid-area {
    margin-bottom: 10px;

    &_title {
      padding: 10px 10px 5px 10px;
      color: #000000;
      font-size: $uni-font-size-base;
    }

    &_center {
      &_item {
        &_image {
          width: 40px;
          height: 40px;
        }

        &_title {
          font-size: $uni-font-size-sm;
        }
      }
    }
  }
}
</style>
