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

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

  <scroll-view scroll-x>
    <view style="margin-bottom: 50px">
      <!-- 下拉选择 -->
      <!-- <view class="searchSelect shadow" v-if="flag">
        <view class="cu-bar search bg-white">
          <view class="search-form round" style="margin-top: 0">
            <input
              @focus="InputFocus"
              @blur="InputBlur"
              @input="handleInput()"
              v-model="searchInput"
              :adjust-position="false"
              type="text"
              placeholder=""
              confirm-type="search"
              style="border: none !important"
            />
            <text class="cuIcon-search"></text>
          </view>
        </view>
        <view class="select-items">
          <view
            class="site-item"
            v-if="!searchList.length"
            style="text-align: center"
            >暂无结果</view
          >
          <view
            class="select-item"
            v-for="(item, index) in searchList"
            @click="clickSelectItem(item, index)"
            :key="index"
            >{{ item.owner_name }}</view
          >
        </view>
      </view> -->
      <!-- 下拉选择 end -->

      <!-- 图表 -->
      <!-- <view class="section1 section bg-white padding-xs">
        <view
          class="
            static-tabs
            grid
            margin-bottom
            text-center
            col-3
            margin-top-sm margin-bottom-sm
          "
        >
          <view
            :class="['padding-sm ', Inv == 0 ? 'active' : '']"
            @click="Inv = 0"
            >报警信息统计</view
          >
          <view
            :class="['padding-sm ', Inv == 1 ? 'active' : '']"
            @click="Inv = 1"
            >数据等级统计</view
          >
          <view
            :class="['padding-sm ', Inv == 2 ? 'active' : '']"
            @click="Inv = 2"
            >设备运行状态</view
          >
        </view>
        <view class="time text-center"
          >统计时段：{{ staticData.statisticalPeriod }}
        </view>
        <view style="height: 570rpx">
          <view v-if="Inv == 0"> </view>
          <view v-if="Inv == 1"> </view>
          <view v-if="Inv == 2" class="chart3-box">
            <ul class="chart3-icon">
              <li>
                <image
                  src="@/static/images/index/chart3-1.png"
                  style="width: 64rpx; height: 64rpx"
                ></image>
              </li>
              <li>
                <image
                  src="@/static/images/index/chart3-2.png"
                  style="width: 64rpx; height: 64rpx"
                ></image>
              </li>
              <li>
                <image
                  src="@/static/images/index/chart3-3.png"
                  style="width: 64rpx; height: 64rpx"
                ></image>
              </li>
              <li>
                <image
                  src="@/static/images/index/chart3-4.png"
                  style="width: 64rpx; height: 64rpx"
                ></image>
              </li>
              <li>
                <image
                  src="@/static/images/index/chart3-5.png"
                  style="width: 64rpx; height: 64rpx"
                ></image>
              </li>
            </ul>
          </view>
        </view>
      </view> -->
      <!-- 图表 end-->

      <!-- 轮播图 开始 -->
      <u-swiper :list="arrayList.swiperList" indicator indicatorMode="line" radius="0" height="160" circular> </u-swiper>
      <!-- 轮播图 结束 -->

      <!-- 宫格列表 -->
      <view class="section2 section bg-white" style="margin-bottom: 10px" v-if="arrayList.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 arrayList.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 arrayList.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>
  </scroll-view>
</template>

<script setup>
import searchSelect from "@/components/searchSelect/searchSelect.vue";
import pagesHarder from "@/components/pages-harder/index.vue";

import json from "@/static/js/json.js"; //引入api请求封装方法
import * as jwx from "@/utils/jssdk.js"; //引入js sdk的封装

import { onReady, onLoad, onShow, onNavigationBarButtonTap } from "@dcloudio/uni-app";
import { ref, onMounted, inject, shallowRef, reactive, getCurrentInstance } from "vue";
import useStores from "@/store/modules/user.js";
import publicStore from "@/store/modules/public";

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

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

const arrayList = reactive({
  InputBottom: 0,
  staticData: "",
  indicator: [],
  datavalue: [],
  dataname: [],
  Inv: 0,
  flag: false,
  searchList: [],
  searchList2: [],
  searchInput: "",
  selectedCode: 10012,
  codeResult: "",

  swiperList: ["../static/images/index/banner1.png", "../static/images/index/banner2.jpg", "../static/images/index/banner3.jpg"],
  // cuIconList: json.cuIconList,
  recentlyUsed: [],
});

onLoad((option) => {
  //获取首页标题
  if (uni.getStorageSync("homeTitle")) {
    uni.setNavigationBarTitle({
      title: uni.getStorageSync("homeTitle"),
    });
  } else {
    uni.setNavigationBarTitle({
      title: "首页",
    });
  }

  if (uni.getStorageSync(useStore.$state.name)) {
    arrayList.recentlyUsed = uni.getStorageSync(useStore.$state.name);
  }

  // var res = uni.getStorageSync("selectedCode");
  // var res2 = uni.getStorageSync("selectedName");
  // if (res) {
  //   uni.setNavigationBarTitle({
  //     title: res2,
  //   });
  // }

  // // 图表切换渲染
  // hackReset.value = false;
  // nextTick(() => {
  //   hackReset.value = true;
  // });

  getAppRoutersData();
});

async function init() {
  window.location.href = BASE_URL + "Com/getPageAuthorization1";
}

//扫码
function scanQRCode() {
  // scanCode();
  jwx.configWeiXin((jweixin) => {
    jweixin.scanQRCode({
      needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
      scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
      success: function (res) {
        setTimeout(function () {
          /* 放1000ms后执行的代码 */
          alert(res.resultStr);
          getCodeResult({
            ercode: res.resultStr,
          });
        }, 1000);
      },
    });
  });
}

function scanCode() {
  uni.scanCode({
    scanType: ["qrCode"],
    success: (res) => {
      console.log("扫码成功", res);
    },
    fail: (err) => {
      console.log("扫码失败", err);
    },
    complete: () => {
      console.log("扫码结束");
    },
  });
}

// 扫码成功后请求
async function getCodeResult(param = {}) {
  scan_push(param).then((res) => {
    if (res.data.flag) {
      uni.showToast({
        title: "扫码成功",
        icon: "none",
      });
    }
  });
}

//获取地理位置
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;

    arrayList.recentlyUsed.push(item);

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

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

    arrayList.recentlyUsed = publicStores.sortEvent(arrayList.recentlyUsed, 1);

    uni.setStorageSync(useStore.$state.name, arrayList.recentlyUsed);

    uni.navigateTo({
      url: item.path,
    });
  } else {
    uni.showModal({
      title: "Tips",
      content: "此模块开发中~",
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
        } else if (res.cancel) {
        }
      },
    });
  }
}

function showTag() {
  arrayList.flag = !arrayList.flag;
}
// 下拉选择
function clickSelectItem(item, index) {
  arrayList.staticData = "";
  arrayList.selectedCode = item.owner_code;
  uni.setStorageSync("selectedCode", item.owner_code);
  uni.setStorageSync("selectedName", item.owner_name);
  arrayList.searchInput = item.owner_name;
  uni.setNavigationBarTitle({
    title: arrayList.searchInput,
  });

  getHomeData({
    company_code: uni.getStorageSync("selectedCode"),
  });
  getHandleData({
    company_code: uni.getStorageSync("selectedCode"),
  });

  arrayList.flag = false;
}

function handleInput() {
  var newlist = arrayList.searchList2.filter((item) => item.owner_name.indexOf(arrayList.searchInput) > -1);
  arrayList.searchList = newlist;
}

function InputFocus(e) {
  arrayList.InputBottom = e.detail.height;
}

function InputBlur(e) {
  arrayList.InputBottom = 0;
}

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) => {
    console.log(res.data);

    res.data.forEach((el) => {
      //  const modules = import.meta.glob("@/static/icons/*.svg");
      el.meta.icon = `/static/icons/index/${el.meta.icon}.svg`;
    });

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

//echarts图表请求
async function getHomeData(param = {}) {
  getHomePageData(param).then((res) => {
    // console.log('首页请求staticData')
    // console.log(res.data.data[0])
    arrayList.staticData = res.data.data[0];

    // var data = res.data.data[0]

    var datavalue = [
      arrayList.staticData.fire_water_count,
      arrayList.staticData.alarm_host_count,
      arrayList.staticData.electrical_fire_count,
      arrayList.staticData.other_count,
      arrayList.staticData.video_monitoring_count,
    ];
    var dataname = ["消防水系统", "报警主机", "电气火灾", "其他", "监控视频"];
    var color = ["#3C8BF0", "#06CDF8", "#0ECB70", "#6744EF", "#FFD803"];

    var aa = [
      arrayList.staticData.fire_water_count,
      arrayList.staticData.alarm_host_count,
      arrayList.staticData.electrical_fire_count,
      arrayList.staticData.other_count,
      arrayList.staticData.video_monitoring_count,
    ];
    aa.sort(function (a, b) {
      return a - b;
    });
    aa = aa.pop();
    var datamax = [aa, aa, aa, aa, aa];

    arrayList.datavalue = datavalue;
    arrayList.dataname = dataname;

    dataname.map((val, ind) => {
      arrayList.indicator.push({
        name: val,
        max: datamax[ind],
        color: color[ind],
      });
    });
    arrayList.indicator = arrayList.indicator.slice(-5);
  });
}

// 未处理告警请求
async function getHandleData(param = {}) {
  getFunctionalModuleStatistics(param).then((res) => {
    arrayList.cuIconList[0].badge = res.data.data[0].comprehensive_alarm_count;
    arrayList.cuIconList[2].badge = res.data.data[0].fire_brigade_inspector_count;
  });
}

// 自定义导航事件
onNavigationBarButtonTap((e) => {
  if (e.float == "right") {
    // alert("你点击了扫一扫");
    scanQRCode();
  } else {
    // alert("你点击了获取位置");
    // getLocation()
    showTag();
  }
});
</script>

<style lang="scss">
.select-items {
  overflow: auto;
  height: 80vh;
}

.static-tabs {
  border-radius: 50rpx;
  border: 1rpx solid #4074e7;

  > view {
    color: #4074e7;
    font-size: 30rpx;
  }

  > view.active {
    color: #fff;
    background: #4074e7;
  }

  > view:first-child {
    border-top-left-radius: 50rpx;
    border-bottom-left-radius: 50rpx;
  }

  > view:nth-child(2) {
    border-left: 1px solid #4074e7;
    border-right: 1px solid #4074e7;
  }

  > view:last-child {
    border-top-right-radius: 50rpx;
    border-bottom-right-radius: 50rpx;
  }
}

/* 检测时间 */
.time {
  border-radius: 50rpx;
  background: #fafcff;
  border: 1px solid #e8f1ff;
  padding: 20rpx;
  color: #666666;
  font-size: 30rpx;
}

.chart3-box {
  position: relative;
}

.chart3-icon {
  width: 90%;
  position: absolute;
  top: 60rpx;
  left: 30rpx;
  z-index: 1;
}

.chart3-icon li {
  padding-top: 25rpx;
}

ul,
li {
  padding: 0;
  margin: 0;
  list-style: none;
}
</style>
