<template>
  <view class="home">
    <view class="welcom">{{ hello }} 欢迎登录</view>
    <view class="weather-bg">
      <view class="weather-box">
        <view class="weather">
          <view class="weatext">
            <view
              >今天<span class="text-span">{{
                weatherinfo.air_level
              }}</span></view
            >
            <view class="text-value">{{ weatherinfo.at }}℃</view>
          </view>
          <view class="weatext">
            <image
              v-if="weatherinfo.wea && weatherinfo.wea != '-'"
              :src="
                'https://webstaticimg.oss-cn-hangzhou.aliyuncs.com/bigdata_app/img/weather/' +
                weatherinfo.wea +
                '.png'
              "
              mode=""
              class="weaimg"
            ></image>

            <view class="weatext_title">
              {{ weatherinfo.wea }}
            </view>
          </view>
        </view>
        <view class="weather">
          <view class="weatext">
            <view
              >湿度<span class="text-span">{{
                weatherinfo.ah | ahFilter
              }}</span></view
            >
            <view class="text-value">{{ weatherinfo.ah }}</view>
          </view>
          <view class="weatext">
            <view>PM2.5</view>
            <view class="textbox">
              {{ weatherinfo.air_pm25 }}
            </view>
          </view>
        </view>
      </view>
      <view class="weather-warning" v-if="weatherinfo.alarm_content">
        <image
          class="weather-alert"
          :src="$imageURL + '/bigdata_app/newImg/home/weather-alert.png'"
          mode=""
        ></image>
        {{ weatherinfo.alarm_content }}
      </view>
    </view>
    <view class="ai-box">
      <view class="ai-content" @click="tabfunction(4)">
        <image
          :src="$imageURL + '/bigdata_app/newImg/home/ai-bot.png'"
          class="float-left"
          mode=""
        ></image>
        <view class="ai-text">
          <view class="ai-text-title">我是千耘农业种植大模型</view>
          <view class="ai-text-subtitle">耕耘千百变，智慧一点通</view>
        </view>
        <view class="float-right"> 问一问 </view>
      </view>
    </view>
    <view class="functionbox">
      <view class="functionbox_text">
        <view
          class="functionbox_text_item"
          @click="tabfunction(0, item)"
          v-for="(item, index) in menuTop9"
          :key="index"
        >
          <image :src="item.app_menu_icon" mode="" class="itemimg"> </image>
          <view class="icon_text"> {{ getSlice(item.purview_name) }} </view>
        </view>
        <view
          class="functionbox_text_item"
          @click="tabfunction(9)"
          v-if="menuList.length >= 9"
        >
          <image
            :src="$imageURL + '/bigdata_app/newImg/home/moreIcon.png'"
            mode=""
            class="itemimg"
          ></image>
          <view class=""> 更多功能 </view>
        </view>
      </view>
    </view>
    <view class="facilitybox">
      <view class="facilitybox-content">
        <view class="facilitybox_title"> 智慧助手 </view>
        <view style="display: flex; flex-direction: column">
          <view class="facilitybox_itembox">
            <view
              class="facilitybox_item facilitybox-zhuanjia"
              @click="tabfunction(2)"
            >
              <image
                :src="$imageURL + '/bigdata_app/newImg/home/zjhk.png'"
                mode=""
                class="itemimg"
              >
              </image>
              <view class="facilitybox_span">
                <text style="font-weight: 700"> 专家库 </text>
                <view class="text">农业相关博士、教授、研究员</view>
              </view>
            </view>
            <view
              class="facilitybox_item"
              style="display: flex; flex-direction: column; gap: 24rpx"
            >
              <view class="facilitybox-suishi" @click="tabfunction(1)">
                <image
                  style="width: 72rpx; height: 72rpx; margin-right: 10rpx"
                  :src="$imageURL + '/bigdata_app/newImg/home/tjss.png'"
                  mode=""
                  class="itemimg float-right"
                >
                </image>
                <view class="facilitybox_span"> 田间随识 </view>
              </view>
              <view class="facilitybox-bchk" @click="worm">
                <image
                  :src="$imageURL + '/bigdata_app/newImg/home/cshk.png'"
                  mode=""
                  class="itemimg"
                >
                </image>
                <view style="width: 69%" class="facilitybox_span">
                  病虫草鼠害库
                </view>
              </view>
            </view>
          </view>
          <!-- <view class="facilitybox_itembox">
						<view class="facilitybox_item facilitybox-jwjy"
							@click="tabequipment('../prevention/index')">
							<image :src="$imageURL+'/bigdata_app/newImg/home/jwjy.png'" mode="" class="itemimg">
							</image>
							<view class="facilitybox_span"> 积温积雨 </view>
						</view>
						<view class="facilitybox_item facilitybox-jgqs"
							@click="tabequipment('../monitor/index')">
							<image :src="$imageURL+'/bigdata_app/newImg/home/jgqs.png'" mode="" class="itemimg">
							</image>
							<view class="facilitybox_span"> 价格趋势 </view>
						</view>
					</view> -->
        </view>
      </view>
      <view class="banner-ad" @click="tabs">
        <view class="ad-text">
          <view class="title">
            <!-- 松墨天牛拍照性诱智能监测 -->
          </view>
          <view class="sub-title">
            <!-- AI慧眼识天牛    智守青山护松林 -->
          </view>
          <view class="btn"> 查看详情 </view>
        </view>
      </view>
    </view>
    <ImagePopup :imageUrl="popupImageUrl" @close="handlePopupClose" />
  </view>
</template>

<script>
import { Debounce } from '../../util/anitthro.js';
import ImagePopup from './components/ImagePopup.vue';
export default {
  components: {
    ImagePopup,
  },
  // // 分享给朋友
  // onShareAppMessage() {
  //   return {
  //     title: '云飞智控', // 分享标题
  //     path: 'pages/index/index', // 分享路径，通常包含页面参数
  //     imageUrl: 'http://www.hnyfwlw.com:8006/data/home_logo/log1.jpg', // 分享图片，可选
  //     success: (res) => {
  //       // 分享成功回调
  //       uni.showToast({
  //         title: '分享成功',
  //         icon: 'success'
  //       })
  //     },
  //     fail: (err) => {
  //       // 分享失败回调
  //       console.log('分享失败', err)
  //     }
  //   }
  // },
  // // 分享到朋友圈（基础库2.11.3+）
  // onShareTimeline() {
  //   return {
  //     title:  '云飞智控', // 分享标题
  //     query: 'id=123', // 页面参数，不同于分享给朋友的path，这里用query
  //     imageUrl: 'http://www.hnyfwlw.com:8006/data/home_logo/log1.jpg' // 分享图片，可选
  //   }
  // },
  filters: {
    ahFilter(value) {
      if (value > 70) {
        return '湿润';
      } else if (value < 30) {
        return '干燥';
      } else {
        return '正常';
      }
    },
  },
  data() {
    return {
      menuList: [],
      indicatorDots: true,
      autoplay: false,
      interval: 2000,
      duration: 500,
      weatherinfo: {
        wea: '-',
        air_level: '-',
        at: '-',
        air_pm25: '-',
        ah: '-',
        alarm_content: '',
      },
      hello: '',
      show: false,
      url: '',
      loadTF: false,
      popupImageUrl:
        'https://s3.hnyfwlw.com/webstaticimg/bigdata_app/version/app-version.png',
    };
  },
  watch: {
    url(news) {
      if (news != '') {
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 500,
        });
      }
    },
  },
  computed: {
    menuTop9() {
      return (this.menuList || []).slice(0, 9);
    },
  },
  methods: {
    handlePopupClose() {
      console.log('弹窗已关闭');
    },
    tabs() {
      uni.navigateTo({
        url: '/pages/banner/index',
      });
    },
    getSlice(name) {
      return name.slice(0, 4);
    },
    async getcity(lng, lat) {
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=device.device_manage.weathers',
        data: {
          lng: lng,
          lat: lat,
        },
      });
      this.weatherinfo = res[0];
    },
    async getUserlogin() {
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=user.login.user_login_info',
        data: {
          is_app: 1,
        },
      });
      const menuList = [];
      res.forEach((item) => {
        if (item.children) {
          menuList.push(...item.children);
        }
      });
      const children = [];
      menuList.forEach((item) => {
        if (item.children) {
          children.push(...item.children);
        }
      });
      const myuser_type = res[0]?.myuser_type || '';
      const myuid = res[0]?.myuid || '';
      uni.setStorage({
        key: 'jurisdiction',
        data: JSON.stringify(children),
      });
      uni.setStorage({
        key: 'myuser_type',
        data: JSON.stringify(myuser_type),
      });
      uni.setStorage({
        key: 'myuid',
        data: JSON.stringify(myuid),
      });
      this.menuList = menuList || [];
      uni.setStorage({
        key: 'menuList',
        data: JSON.stringify(menuList || []),
      });
    },
    loadMenuFromCache() {
      try {
        const cached = uni.getStorageSync('menuList');
        if (cached) this.menuList = JSON.parse(cached) || [];
      } catch (e) {
        console.error('读取 menuList 缓存失败:', e);
      }
    },
    tabfunction(index, item) {
      const purId = item?.pur_id || '';
      if (purId == 25) {
        uni.navigateTo({
          url: '/pages/fourBase/index',
        });
      } else if (purId == 125) {
        uni.navigateTo({
          url: '/pages/expertDiagnosis/index',
        });
      } else if (purId == 126) {
        uni.navigateTo({
          url: '/pages/expertDiagnosis/wormcase?name=虫情百科',
        });
      } else if (purId == 29) {
        uni.navigateTo({
          url: '/pages/equipMange/index/index',
        });
      } else if (purId == 156) {
        uni.navigateTo({
          url: '/pages/afterSale/index',
        });
      } else if (purId == 422) {
        uni.navigateTo({
          url: '/pages/warning/index',
        });
      } else if (index == 0) {
        uni.switchTab({
          url: '/pages/equipList2/index',
          success: () => {
            setTimeout(() => {
              uni.$emit('purId', {
                purId,
                menu: item.children[0]?.menu || '',
                device_model: item.children[0]?.device_model || '',
              });
            }, 50);
          },
        });
      } else if (index == 1) {
        uni.navigateTo({
          url: '/pages/identifyPest/identifyPest',
        });
      } else if (index == 2) {
        uni.navigateTo({
          url: '../expertDiagnosis/index',
        });
      } else if (index == 3) {
        uni.navigateTo({
          url: '../afterSale/index',
        });
      } else if (index == 4) {
        uni.navigateTo({
          url: '/pages/index/developing',
        });
      } else if (index == 9) {
        uni.navigateTo({
          url: '/pages/server/index',
        });
      }
    },
    tabequipment(url, type) {
      console.log(url);
      uni.navigateTo({
        url: `${url}${type ? `?typeId=${type}` : ''}`,
      });
    },
    worm() {
      uni.navigateTo({
        url: '../expertDiagnosis/wormcase?name=虫情百科',
      });
    },
    checkLocationPermission(isTest) {
      let session_key = uni.getStorageSync('session_key');
      console.log(session_key, 'session_key');
      let _this = this;
      // 当用户登录之后再弹位置权限框
      if (session_key) {
        uni.getSetting({
          success(res) {
            console.log(res, 'resres');
            if (res.authSetting['scope.userLocation']) {
              uni.getLocation({
                type: 'wgs84 ',
                success: (res) => {
                  _this.getcity(res.longitude, res.latitude);
                },
                fail(e) {
                  uni.showToast({
                    title: '系统未开启定位或未授权微信定位',
                    duration: 5000,
                    icon: 'none',
                  });
                },
              });
            } else {
              uni.authorize({
                scope: 'scope.userLocation',
                success: () => {
                  // 用户已授权
                  uni.getLocation({
                    type: 'wgs84 ',
                    success: (res) => {
                      console.log(res, 'loacation');
                      _this.getcity(res.longitude, res.latitude);
                    },
                  });
                },
                fail: () => {
                  // 用户拒绝授权，可引导用户至设置页手动开启
                  if (isTest) {
                    uni.showModal({
                      title: '需要授权',
                      content:
                        '天气功能需要获取您的地理位置，请在设置中打开位置权限',
                      success: (modalRes) => {
                        if (modalRes.confirm) {
                          uni.openSetting();
                        } else {
                          uni.showToast({
                            title: '您拒绝了授权，将无法查看天气信息',
                            duration: 2000,
                            icon: 'none',
                          });
                        }
                      },
                    });
                  }
                },
              });
            }
          },
        });
      }
    },
  },
  onLoad() {
    var time = new Date();
    var hours = time.getHours();
    if (hours < 12) {
      this.hello = '上午好!';
    } else {
      this.hello = '下午好!';
    }
    this.checkLocationPermission(true); // 首次加载弹框提醒
  },
  onShow() {
    this.loadTF = false;
    this.getUserlogin().catch((e) => {
      console.error('getUserlogin 失败:', e);
      this.loadMenuFromCache();
    });
    this.checkLocationPermission();
  },
};
</script>

<style lang="less">
page {
  background:
    linear-gradient(
      180deg,
      #1fc676 11.72%,
      #1fc676 11.52%,
      #d5f9e7 29.83%,
      #f5f6fa 36.96%
    ),
    #fff;
  background-size: 100%;
  background-repeat: no-repeat;
  background-color: #f9f9f9;
}
.home {
  width: 100%;
  height: 100%;
  padding-top: 94rpx;
  box-sizing: border-box;
}
.welcom {
  height: 64rpx;
  line-height: 64rpx;
  padding-left: 16rpx;
  font-size: 40rpx;
  color: #fff;
}
.weather-bg {
  width: 100%;
  background-image: url(https://s3.hnyfwlw.com/webstaticimg/bigdata_app/newImg/home/banner-bg.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.weather-box {
  display: flex;
  margin: 24rpx 0 16rpx 0;
}
.weather:nth-child(1) {
  border-right: 1px solid rgba(255, 255, 255, 0.6);
}
.weather {
  flex: 1;
  display: flex;
  .weaimg {
    width: 42rpx;
    height: 42rpx;
  }
  .weatext {
    gap: 8rpx;
    display: flex;
    flex-direction: column;
    padding-left: 44rpx;
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.8);
  }
  .weatext_title {
    font-size: 24rpx;
    color: #fff;
  }
  .text-span {
    color: #0bbc58;
    margin-left: 16rpx;
    padding: 0 2px;
    border-radius: 4px;
    background: rgba(255, 255, 255, 0.6);
  }
  .text-value {
    font-size: 48rpx;
    color: #fff;
  }
}
.weather-warning {
  margin: 20rpx 0;
  padding: 0 40rpx;
  color: #fff;
  .weather-alert {
    width: 30rpx;
    height: 30rpx;
    margin-right: 10rpx;
  }
}
.ai-box {
  width: 100%;
  padding: 0 40rpx;
  box-sizing: border-box;
  height: 128rpx;
  margin-bottom: 12rpx;
  position: relative;
  .ai-content {
    box-sizing: border-box;
    height: 100%;
    border-radius: 8px;
    border: 1.5px solid #fff;
    background: linear-gradient(180deg, #ffffffa3 0%, #fff 100%);
    padding: 24rpx;
    image {
      width: 80rpx;
      height: 80rpx;
      float: left;
      margin-right: 16rpx;
    }
    .float-right {
      float: right;
      padding: 4px 12px;
      color: #fff;
      border-radius: 28px;
      background: #0bbc58;
      margin: 12rpx 0;
    }
    .ai-text {
      float: left;
    }
    .ai-text-title {
      color: #333834;
      line-height: 40rpx;
      font-size: 28rpx;
      font-weight: 700;
    }
    .ai-text-subtitle {
      color: #7b9783;
      line-height: 40rpx;
      font-size: 20rpx;
      font-weight: 400;
    }
  }
}
.functionbox {
  width: 100%;
  padding: 0rpx 32rpx 0 32rpx;
  box-sizing: border-box;
  margin-bottom: 16rpx;
  .swiper {
    height: 208rpx;
  }
  .functionbox_title {
    padding-left: 20rpx;
    font-size: 34rpx;
  }
  .functionbox_text {
    display: flex;
    flex-wrap: wrap;
    margin-top: 30rpx;
    .functionbox_text_item {
      width: 20%;
      text-align: center;
      color: #616666;
      font-size: 24rpx;
      margin-bottom: 32rpx;
      .itemimg {
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 16rpx;
      }
      .icon_text {
        // 超出隐藏
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
.facilitybox {
  width: 100%;
  padding: 0 32rpx;
  box-sizing: border-box;
  background: #f5f6fa;
  .facilitybox-content {
    border-radius: 16rpx;
    background: #fff;
    padding: 32rpx;
  }
  .facilitybox_title {
    font-size: 30rpx;
    color: #333;
    margin-bottom: 24rpx;
    font-weight: 700;
  }
  .facilitybox_itembox {
    display: flex;
    gap: 32rpx;
    .facilitybox_item {
      flex: 1;
      color: #616666;
      .facilitybox_span {
        padding: 16rpx 24rpx;
        width: 50%;
        color: #0b3f5d;
        font-weight: 700;
        font-size: 28rpx;
        .text {
          font-size: 20rpx;
          color: #4e916e;
          font-weight: 400;
          margin-top: 9rpx;
        }
      }
      .itemimg {
        width: 90rpx;
        height: 90rpx;
        float: right;
        margin: 7rpx 0;
      }
    }
    .facilitybox-zhuanjia {
      border-radius: 8px;
      background: linear-gradient(180deg, #d3fbe6 0%, #f5f7fa 100%);
      position: relative;
      .itemimg {
        width: 112rpx;
        height: 146rpx;
        position: absolute;
        bottom: 0;
        right: 16rpx;
      }
      text {
        color: #003318;
        font-weight: 500;
        font-size: 28rpx;
      }
    }
    .facilitybox-suishi {
      border-radius: 8px;
      background: linear-gradient(180deg, #caecff 0%, #f5f7fa 99.89%);
      padding: 9rpx 0;
      .facilitybox_span {
        color: #0b3f5d;
      }
    }
    .facilitybox-bchk {
      border-radius: 8px;
      background: linear-gradient(180deg, #eee5f6 0%, #f5f7fa 95.65%);
      padding: 10rpx 0;
      .facilitybox_span {
        color: #3e2b50;
      }
      .itemimg {
        width: 78rpx;
        height: 72rpx;
        margin-right: 10rpx;
      }
    }
    .facilitybox-jgqs {
      border-radius: 8px;
      background: linear-gradient(180deg, #d2e5ff 0%, #f5f7fa 95.65%);
      .facilitybox_span {
        color: #0d2e5b;
      }
    }
    .facilitybox-jwjy {
      border-radius: 8px;
      background: linear-gradient(180deg, #fff4d2 0%, #f5f7fa 95.65%);
      .facilitybox_span {
        color: #3d4012;
      }
    }
  }
}
.banner-ad {
  margin: 32rpx 0;
  height: 210rpx;
  border-radius: 8px;
  background-size: 100% 100%;
  background-image: url(https://s3.hnyfwlw.com/webstaticimg/bigdata_app/newImg/home/banner1.png);
  .ad-text {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    padding: 20rpx 40rpx;
    box-sizing: border-box;
    .title {
      color: #333333;
      font-size: 28rpx;
      font-style: normal;
      font-weight: 700;
      line-height: normal;
    }
    .sub-title {
      color: #666666;
      font-size: 20rpx;
      font-style: normal;
      font-weight: 500;
      line-height: normal;
    }
    .btn {
      text-align: center;
      width: 112rpx;
      color: #fff;
      padding: 4px 0px;
      font-size: 20rpx;
      border-radius: 4px;
      background: linear-gradient(106deg, #0bbc58 2.6%, #7ce6fb 86.51%);
    }
  }
}
.insectattack {
  width: 90%;
  margin: 0 auto;
  padding: 30rpx;
  .insectattack_title {
    font-size: 34rpx;
    display: flex;
    justify-content: space-between;
    .iconbox {
      width: 40rpx;
      height: 40rpx;
      background-color: #cfd6d6;
      color: #909696;
      border-radius: 40rpx;
      line-height: 40rpx;
      text-align: center;
      font-size: 20rpx;
    }
  }
  .insectattack_listbox {
    overflow-x: auto;
    .insectattack_list {
      width: 1104rpx;
      display: flex;
      margin-top: 30rpx;
      flex-wrap: wrap;
      .list_box {
        background-size: 100% 100%;
        width: 246rpx;
        height: 324rpx;
        margin-right: 30rpx;
        border-radius: 20rpx;
        position: relative;
        .list_boxbg {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          z-index: -1;
          .list_boxbg_img {
            width: 100%;
            height: 100%;
          }
        }
        .list_box_xiang {
          width: 95%;
          margin-top: 0rpx auto;
          display: flex;
          justify-content: flex-end;
          padding-top: 20rpx;
          .list_box_xiang_click {
            padding: 8rpx 15rpx;
            background-color: rgba(0, 0, 0, 0.2);
            color: #fff;
            font-size: 20rpx;
            border-radius: 52rpx;
          }
        }
        .list_box_info {
          width: 90%;
          margin: 130rpx auto 0;
          height: 120rpx;
          border-radius: 10rpx;
          background-image: linear-gradient(
            to right,
            #ffffff,
            rgba(255, 255, 255, 0.44)
          );
          padding: 10rpx;
          box-sizing: border-box;
          .list_box_info_name {
            font-weight: 700;
          }
          .list_box_info_text {
            font-size: 18rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
          }
        }
      }
    }
  }
}
.loading {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 100;
  width: 100%;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
