<template>
  <view class="home-page">
    <view
      class="home-page__layers"
    >
      <HomeSearch
        :inputTypeVisible="show"
        :layerVisible="layerVisible"
        :searchTypeName="currentTypeName"
        :searchType="currentType"
        :warningData="warningData"
        @inputTypeChange="handleInputTypeChange"
        @layerChange="handleLayerChange"
        @search="handleSearch"
        @deviceStatusChecked="handleDeviceStatusChange"
      />
    </view>
    <view class="home-page__canvas">
      <Map
        :deviceList="deviceList"
        :landList="landList"
        :inputTag="inputTag"
        :blockList="blockList"
        :inputValue="inputValue"
        :inputType="currentType"
        :mapRenderTypes="mapRenderTypes"
        :isShowSatellite="isShowSatellite"
        :deviceStatusCheckedList="deviceStatusCheckedList"
        @deviceClick="handleDeviceClick"
        @landClick="handleLandClick"
        @plotClick="handlePlotClick"
        @getLocation="handleGetLocation"
      />
    </view>
    <u-picker
      v-model="show"
      :range="searchTypes"
      mode="selector"
      :default-selector="[0]"
      range-key="label"
      confirmColor="#14A478"
      @cancel="closeHandler"
      @confirm="confirmHandler"
    ></u-picker>
    <LayerPopup :visible.sync="layerVisible" @confirm="handleLayerConfirm" />
    <DevicePopup
      :visible.sync="deviceLayerVisible"
      :dataSource="currentSelectedData"
    />
    <LandPopup
      :visible.sync="landLayerVisible"
      :dataSource="currentSelectedLandData"
    />
    <BlockPopup
      :visible.sync="blockLayerVisible"
      :dataSource="currentSelectedBlockData"
    />
    <AppPopup :visible.sync="appLayerVisible" />
  </view>
</template>

<script>
import { mapGetters } from 'vuex';

import Map from './components/Map.vue';
import LayerPopup from './components/LayerPopup.vue';
import HomeSearch from './components/HomeSearch.vue';
import DevicePopup from './components/DevicePopup.vue';
import LandPopup from './components/LandPopup.vue';
import BlockPopup from './components/BlockPopup.vue';
import AppPopup from './components/AppPopup.vue';
import { cloneDeep, slice, take } from 'lodash-es';
import HeartBeat from '@/libs/HeartBeat';

// #ifdef APP-PLUS
var Color = plus.android.importClass('android.graphics.Color');
plus.android.importClass('android.view.Window');
var mainActivity = plus.android.runtimeMainActivity();
var window_android = mainActivity.getWindow();
window_android.setNavigationBarColor(Color.parseColor('#fff'));
// #endif

export default {
  name: 'Home',
  components: {
    HomeSearch,
    Map,
    LayerPopup,
    DevicePopup,
    LandPopup,
    BlockPopup,
    AppPopup
  },
  data() {
    return {
      layerVisible: false,
      show: false,
      currentType: 'device',
      currentTypeName: '设备/ID',
      searchTypes: [
        {
          label: '设备/ID',
          id: 'device'
        },
        {
          label: '基地',
          id: 'land'
        },
        {
          label: '地块',
          id: 'block'
        },
        {
          label: '作物',
          id: 'crop'
        }
      ],
      warningText: '',
      deviceList: [],
      blockList: [],
      oldDeviceList: [],
      landList: [],
      inputValue: '',
      deviceLayerVisible: false,
      currentSelectedData: {},
      appLayerVisible: false,
      projectLocation: {},
      currentSelectedLandData: {},
      currentSelectedBlockData: {},
      landLayerVisible: false,
      blockLayerVisible: false,
      warningData: {},
      mapRenderTypes: ['device', 'land', 'block', 'crop'],
      isShowSatellite: true,
      deviceStatusCheckedList: ['0', '1', '3'],
      unReadMessageTotal: 0,
      inputTag: false,
      warningLatest: [],
      weatherWarningData: {}
    };
  },
  onReady() {
    plus.navigator.setStatusBarStyle('light'); // 设置状态栏字体为黑色，背景透明（在某些设备上可能无效）

    // #ifdef APP-PLUS
    var Color = plus.android.importClass('android.graphics.Color');
    plus.android.importClass('android.view.Window');
    var mainActivity = plus.android.runtimeMainActivity();
    var window_android = mainActivity.getWindow();
    window_android.setNavigationBarColor(Color.parseColor('#fff'));
    // #endif
    console.log('on ready');
  },
  onShow() {
    console.log('----------------- onshow ');

    // #ifdef APP-PLUS
    if (plus) {
      // 确保在App环境下运行
      plus.navigator.setStatusBarStyle('light'); // 设置状态栏字体为黑色，背景透明（在某些设备上可能无效）
      // 注意：直接设置状态栏背景色在某些Android版本上可能不生效，可以考虑使用第三方库或者原生代码来实现更复杂的自定义。
    }
    var Color = plus.android.importClass('android.graphics.Color');
    plus.android.importClass('android.view.Window');
    var mainActivity = plus.android.runtimeMainActivity();
    var window_android = mainActivity.getWindow();
    window_android.setNavigationBarColor(Color.parseColor('#fff'));
    // #endif
    this.getWarningLatest();

    setTimeout(() => {
      this.initData();
    }, 500);

    this.getWeatherWarning();
  },
  onLoad() {
    console.log('----------------- onload ');

    // #ifdef APP-PLUS
    var Color = plus.android.importClass('android.graphics.Color');
    plus.android.importClass('android.view.Window');
    var mainActivity = plus.android.runtimeMainActivity();
    var window_android = mainActivity.getWindow();
    window_android.setNavigationBarColor(Color.parseColor('#fff'));
    // #endif

    this.updateMessageCount();
  },
  mounted() {},
  methods: {
    handleGetLocation(options) {
      const { lat, lng } = options;
      // lat && this.getWeatherWarning(lng, lat);
    },
    getWeatherWarning(longitude, latitude) {
      // const that = this;
      // // 获取当前经纬度
      // uni.request({
      //   url: `https://devapi.qweather.com/v7/warning/now?location=${longitude},${latitude}&lang=zh&key=f55bd03fc95e4155b3c8abee8aa68886`,
      //   success(res) {
      //     if (res.statusCode == 200) {
      //       const data = res.data || {};
      //       if (data.code === '200') {
      //         const warningLatest = data.warning || [];
      //         let warningText = '';
      //         warningLatest.forEach((item) => {
      //           warningText += item.text + ',';
      //         });
      //         that.warningText = warningText;
      //         console.log(this.warningText, 'warningTextwarningText');
      //       }
      //     }
      //   }
      // });
    },
    initData() {
      Promise.all([
        this.getDeviceList(),
        this.getLandList(),
        this.getBlockList()
      ])
        .then(([deviceResponse, landResponse, blockResponse]) => {
          const deviceList = deviceResponse.data || [];
          // const deviceArr = [];
          // deviceList.forEach((item) => {
          //   if (item.devStatus == 0) {
          //     deviceArr.push(item);
          //   }
          // });
          this.deviceList = deviceList || [];
          this.blockList = blockResponse.data || [];
          this.oldDeviceList = cloneDeep(deviceList);
          this.landList = landResponse.data || [];
        })
        .catch((err) => {
          console.log('-------------------------------fffff error', err);
        });
    },
    handleLayerChange(value) {
      console.log('handleLayerChange', value);
      this.layerVisible = value;
    },
    openSearchType() {
      this.show = true;
    },
    closeHandler() {
      console.log('closeHandler');
      this.show = false;
    },
    handleInputTypeChange(value) {
      this.show = value;
    },
    confirmHandler(index) {
      const item = this.searchTypes[index]
      const { id,label } = item;
      this.currentType = id;
      this.currentTypeName = label;
      this.closeHandler();
    },
    getDeviceList() {
    },
    getBlockList() {
    },
    getLandList() {
    },
    handleSearch(val) {
      console.log(val, 'handle search 1212121111111111111111');
      this.inputValue = val;
      this.inputTag = !this.inputTag;
    },
    handleDeviceClick(row) {
      console.log('handleDeviceClick', row);
      this.currentSelectedData = row;
      this.deviceLayerVisible = true;
    },
    handleLandClick(row) {
      console.log('handleLandClick', row);
      this.currentSelectedLandData = row;
      this.landLayerVisible = true;
    },
    handlePlotClick(row) {
      console.log('handlePlotClick', row);
      // 可以在这里添加地块点击的处理逻辑
      // 比如显示地块详情弹窗等
      // uni.showToast({
      //   title: `点击了地块: ${row.blockName}`,
      //   icon: 'none'
      // });

      this.currentSelectedBlockData = row;
      this.blockLayerVisible = true;
    },
    // 根据城市查询经纬度
    getWarningLatest() {
    },
    handleLayerConfirm(row = {}) {
      this.isShowSatellite = row.isSatellite;
      this.mapRenderTypes = row.renderTypes || [];

      console.log(
        'handleLayerConfirm',
        this.isShowSatellite,
        this.mapRenderTypes
      );
    },
    handleDeviceStatusChange(checkList) {
      // if (checkList.length === 2) {
      //   this.deviceList = cloneDeep(this.oldDeviceList);
      // } else if (!checkList.length) {
      //   this.deviceList = cloneDeep(this.oldDeviceList);
      // } else {
      //   const checkId = checkList[0];
      //   const deviceList = [];
      //   this.oldDeviceList.forEach((item) => {
      //     if (item.devStatus == checkId) {
      //       deviceList.push(item);
      //     }
      //   });
      //   this.deviceList = deviceList;
      // }

      const newCheckList = slice(checkList || [], 0);

      if (newCheckList.includes('0')) {
        newCheckList.push('3');
      }

      this.deviceStatusCheckedList = newCheckList;
    },
    updateMessageCount() {
      HeartBeat.getInstance().handle({
        type: 'TASK_MESSAGE_UNREAD',
        intervalTimes: 4,
        handler: () => {
          return this.getMessageUnreadCount();
        }
      });
    },
    getMessageUnreadCount() {
    }
  },
  onHide() {}
};
</script>

<style lang="scss" scoped>
page {
  background: #f3f3f3;
}

.home-page__tabs {
  background: #f3f3f3;
}
.weather-warning {
  display: flex;
  height: 64rpx;
  padding: 0 10rpx;
  justify-content: center;
  align-items: center;
  border-radius: 16rpx;
  background: #ffffffcc;
  backdrop-filter: blur(3rpx);
  margin-bottom: 14rpx;
  pointer-events: auto;

  &__list {
    color: #364d46;
    font-family: 'Source Han Sans CN VF';
    font-size: 28rpx;
    font-weight: 400;
  }
}
.home-page {
  width: 100%;
  // height: calc(100vh - 50px - env(safe-area-inset-bottom));
  height: 100%;

  &__canvas {
    width: 100%;
    height: 100%;
  }

  &__layers {
    position: fixed;
    width: 100%;
    left: 0;
    right: 0;
    z-index: 401;
    padding: 0 32rpx;
    pointer-events: none;
    transition: all 0.3s ease-in-out;
  }

  ::v-deep .tdt-bottom {
    display: none;
  }

  &__app {
    position: absolute;
    width: 180rpx;
    height: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    bottom: 0rpx;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    padding: 24rpx;
    background-color: #fff;
    border-radius: 16rpx 16rpx 0 0;
  }
}
</style>
