<template>
  <view class="home-page home-page--h5" :class="{ 'home-page--elder': $uiStyle === 'elder' }" v-if="isBinded">
    <image class="home-bg" :src="homeBg"></image>
    <uni-search-bar class="custom-search" v-model="searchValue" radius="20" maxlength="200" cancelButton="none"
                    bgColor="rgba(255,255,255,0.2)" placeholder="搜服务、搜门牌" @focus="handleSearchFocus"></uni-search-bar>
    <view class="info">
      <view class="user">
        <!-- <view class="user-avatar" @click="handleAvatarClick">
          <image :src="userInfo.avatarUrl || '/static/images/common/avatar.png'" />
        </view> -->
        <view class="user-address">
          <view class="user-address__detail">
            {{ userInfo.address }}
          </view>
          <view class="user-address__area">
            {{ userInfo.address }}
          </view>
        </view>
      </view>
      <!-- <view v-if="bindStatus !== DOOR_BIND_STATUS.BINDED.VALUE" class="btn-mine" type="primary" @tap="goToBind">
        码户绑定
      </view> -->
      <view class="door">
        <view class="door-code" @tap="handleQr">
          <image src="/static/images/common/icon_qr.png" />
          <text>门牌二维码</text>
        </view>
        <view class="door-detail" @tap="handleDoor">
          <image src="/static/images/common/icon_door.png" />
          <text>门牌详情</text>
        </view>
      </view>
    </view>
    <!-- <view class="notice" @tap="handleInform">
      <uni-icons
        class="custom-uni-icon"
        type="sound"
        size="27"
        color="#1676fe"
      ></uni-icons>
      <swiper
        :vertical="true"
        class="notice-swiper"
        :autoplay="autoPlay"
        :circular="true"
        @change="noticeChanged"
      >
        <swiper-item
          v-for="(item, index) in noticeBarText"
          :key="index"
          :item-id="String(item.id)"
        >
          <view class="swiper-item" style="color: #1676fe">{{
            item.messageHeader
          }}</view>
        </swiper-item>
      </swiper>
    </view> -->
    <view class="notice">
      <image class="notice-logo" src="/static/images/home/notice-title.png" mode="scaleToFill" />
      <view class="notice-list" @tap="handleInform">
        <view v-for="item in noticeBarText" :key="item.id" class="item">
          <text>{{ item.messageHeader }}</text>
          <!-- <text class="notice-tag"></text>
          <uni-tag v-show="index === 0" text="最新" size="mini" type="error" /> -->
        </view>
      </view>
    </view>
    <view class="right-easy" @tap="handleJumpRightLink">
      <view>
        基层小微权力监督一点通
      </view>
      <image src="/static/images/home/right-easy.png" />

    </view>
    <view class="help">
      <!--   <view class="help-item custom-gray">
        <image src="/static/images/home/help.png" />
      </view> -->
      <view class="help-item" @tap="handleAlarm" style="width: 100%">
        <image src="/static/images/home/police_2.png" style="width: 100%" />
      </view>
    </view>
    <view class="service-list">
      <view class="list" v-for="(list, index) in serviceList" :key="index">
        <view class="list-title">{{ list.module }}</view>
        <swiper :indicator-dots="indicatorDots" style="height: 170px" adjust-height="none">
          <swiper-item class="list-cont" v-for="(item, itemIndex) in list.cleanAppList" :key="itemIndex">
            <!--  <view
            class="list-cont"
            v-for="(item, itemIndex) in list.cleanAppList"
            :key="itemIndex"> -->
            <view class="list-cell" v-for="(cell, cellIndex) in item" @click="handleModule(cell)" :key="cellIndex">
              <view class="list-cell__icon">
                <image :src="cell.picUrl" />
              </view>

              <text>{{ cell.name }}</text>
            </view>
            <!--   </view> -->
          </swiper-item>
        </swiper>
      </view>
      <view class="list local-feature">
        <view class="list-title">地区特色</view>
        <view class="list-cont" style="height: auto">
          <image src="/static/images/home/dmwh.png" @click="handlePlaceCulture" />
          <!--  <image src="/static/images/home/dmcx.png" @click="handlePlaceQuery" /> -->
          <!--  <image src="/static/images/home/dmhy.png" @click="handleQrMerge" /> -->
        </view>
      </view>
    </view>
    <view class="map-wrapper">
      <view class="map-head">
        <view class="map-head__title">15分钟生活圈</view>
        <view class="map-head__more" @tap="handleToLife">更多></view>
      </view>
      <map class="map" :markers="markers" :latitude="latitude" :longitude="longitude" title="啦啦啦"
           @markertap="handleMarkerTap">
        <cover-view class="map-cover">
          <view class="address">
            <text class="address__detail">{{ addressInfo.title }}</text>
            <text class="address__area">{{ addressInfo.address }}</text>
          </view>
          <view class="navigation" @tap="handleAddressGo" :data-addressinfo="addressInfo">
            <image class="navagation-icon" src="/static/images/home/navigation.png"></image>
          </view>
        </cover-view>
      </map>
      <!--搜索栏-->
      <view class="search-bar">
        <van-search v-model="searchMapValue" @search="handleMapSearch" placeholder="请输入搜索关键词" />
      </view>
      <custom-tabs type="c1" :value="activeTab" @change="handleTabChange" :animation="true" class="custom-tabs">
        <block v-for="(item, index) in tabs" :key="index">
          <custom-tab-pane class="custom-tab-pane" :label="item" :name="'c1_' + index"></custom-tab-pane>
        </block>
      </custom-tabs>
      <view class="address-list">
        <view class="list-cell" v-for="(item, index) in addressList" :key="index">
          <view class="list-cell__cont" @click="handleMarker" :data-addressinfo="item">
            <image class="point-icon" mode="aspectFit" src="/static/images/common/life_point.png">
            </image>
            <view>
              <view class="list-cell__title">{{ item.title }}</view>
              <view class="list-cell__distance">距离{{ item.distance }}KM</view>
              <view class="list-cell__address">{{ item.address }}</view>
            </view>
          </view>
          <image class="phone-icon" src="/static/images/common/phone_icon.png" @click="handlePhoneCall(item)"></image>
        </view>
      </view>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <view v-if="!hasBaseInfo" class="auth-mask" @click="handleAuthProfile"></view>
    <!-- #endif -->
    <!-- #ifdef MP-ALIPAY -->
    <button v-if="!hasBaseInfo" class="auth-mask" open-type="getAuthorize" scope="userInfo" hover-class="none"
            @getAuthorize="handleAuthProfile" @error="onAuthError"></button>
    <!-- #endif -->
    <auth-dialog ref="authDialogRef" class="custom-auth-popup" @close="authDialogClose"></auth-dialog>
    <uni-popup ref="popupQrCode" type="center">
      <view style="padding: 10px; background-color: #fff">
        <image style="width: 180px; height: 180px" mode="scaleToFill" @longpress="handleLongpress" :src="qrCodePath" />
      </view>
    </uni-popup>
    <custom-footer :class="{ 'custom-footer--elder': $uiStyle === 'elder' }"></custom-footer>
  </view>
</template>

<script>
import { geocoder, apiSearch } from "@/api/map.js";
import {
  getServiceList,
  getDoorplateInfo,
  getDoorList,
} from "@/api/control.js";
import {
  DOOR_PLATE_INFO,
  DOOR_BIND_STATUS,
  USER_INFO,
  JUMP_TYPE,
} from "@/utils/const";
import { getQrCode } from "@/api/wx";
import { getNoticeList } from "@/api/notice.js";
import { httpApi, doorplateImgUrl } from "@/common/js/baseUrl";
import { getUserInfo, updateUserInfo, getDoorplatePicUrl } from "@/api/user";
import { storageUserInfo } from "@/utils/index";
import { splitArr, getPlatformEnv } from "@/utils";
import { maskPhoneCall, getPointResByLabel } from "@/utils";
import {getVillageLink} from "@/api/system";
import dd from "gdt-jsapi";
import openLink from "gdt-jsapi/openLink";

const app = getApp();
export default {
  data() {
    return {
      options: null,
      isBinded: true,
      cur: "userInfo",
      scanedInfo: {
        avatarUrl: "",
        address: "",
        doorName: "",
      },
      userInfo: {
        avatarUrl: "",
        address: "",
        doorName: "",
      },
      searchValue: "",
      noticeBarText: [
        { id: "1", messageHeader: "" },
        { id: "2", messageHeader: "" },
        { id: "3", messageHeader: "" },
      ],
      currentNoticeId: "",

      autoPlay: true,
      circular: true,
      serviceList: [],
      homeBg: "/static/images/home/bg.png",
      cardBg: "/static/images/home/card_bg.png",
      latitude: 29.65945,
      longitude: 121.4405,
      markers: [],
      doorMarker: [],
      addressInfo: {
        title: "",
        address: "",
        latitude: 29.65945,
        longitude: 121.4405,
      },
      activeTab: 0,
      active: 2,
      addressList: [],
      sourceAddressList:[],
      searchMapValue: "",
      tabs: ["文物古迹", "超市", "美食", "加油站", "酒店", "学校", "医院"],
      phoneNumber: "",
      qrCode: "",
      hasBaseInfo: false,
      bindStatus: DOOR_BIND_STATUS.BINDED.VALUE,
      DOOR_BIND_STATUS,
      defaultQr: "",
      codeToQr: [
        {
          code: "11b11178adc94e348924b6da67f5cc09",
          qr: "/static/images/common/2-504.png",
        },
        {
          code: "05fbf95a93e94987bf9f1d774dc88212",
          qr: "/static/images/common/252.png",
        },
      ],
      qrCodePath: "",
      indicatorDots: true, //swiper的指示点
    };
  },
  created() {
    console.log("home created");
  },
  onLoad: function (params) {
    const options = this.configOptions(params);
    if (options && options.code) {
      app.globalData.NBID = options.NBID;
      app.globalData.options = options;
    }
    const userInfo = uni.getStorageSync(USER_INFO) || {};
    this.userInfo = { ...this.userInfo, ...userInfo };
    //多次请求了，删除
    /*  if (app.globalData.openid) {
       this.getUserInfo();
     } else {
       app.watch("openid", this.getUserInfo.bind(this));
     } */
    this.getServiceList();
    this.getNoticeList();

  },
  onShow: function () {
    const userInfo = uni.getStorageSync(USER_INFO) || {};
    this.userInfo = { ...this.userInfo, ...userInfo };
    if (this.userInfo.avatarUrl && this.userInfo.phoneWx) {
      this.hasBaseInfo = true;
    }
    if (
        app.globalData.doorplateInfo.code &&
        app.globalData.doorplateInfo.code !== app.globalData.options.code
    ) {
      app.globalData.options.code = app.globalData.doorplateInfo.code;
    }
    /* console.error(app.globalData.openid) */
    app.globalData.openid = userInfo.uuid; //h5端测试用
    if (app.globalData.openid) {
      this.getUserInfo();
    }
    this.getServiceList(); //以防设置长辈版，重新分配
    this.getDoorplateInfo();
  },
  destroyed() {
    console.log("homeview destoryed");
  },
  methods: {
    authDialogClose() {
      uni.showTabBar();
      this.getUserInfo();
    },
    handleAvatarClick() {
      const _that = this;
      if (!this.userInfo.avatarUrl) {
        // #ifdef MP-WEIXIN || MP-ALIPAY
        uni.getUserProfile({
          desc: "用于完善用户资料",
          success: (res) => {
            updateUserInfo({
              openId: app.globalData.openid,
              nickName: res.userInfo.nickName,
              phoneWx: "",
            });
            storageUserInfo(res.userInfo);
            _that.userInfo = { ...this.userInfo, ...res.data };
          },
        });
        // #endif
        // #ifdef H5
        uni.showToast({ title: "去浙里办上传头像" });
        // #endif
      }
    },
    configOptions(options) {
      const envVersion = uni.getEnvVersion();
      if (envVersion === "release") {
        return options;
      } else if (options.code) {
        return options;
      } else {
        return {
          NBID: "",
          Type: "",
          code: "",
        };
      }
    },
    handleAuthProfile() {
      const _that = this;
      if (!this.userInfo.avatarUrl) {
        // #ifdef MP-WEIXIN
        uni.getUserProfile({
          desc: "用于完善用户资料",
          success: (res) => {
            // updateUserInfo({
            //   openId: app.globalData.openid,
            //   nickName: res.userInfo.nickName,
            //   phoneWx: ''
            // });
            storageUserInfo(res.userInfo);
            _that.userInfo = { ..._that.userInfo, ...res.userInfo };
            _that.$refs.authDialogRef.open();
            uni.hideTabBar();
          },
        });
        // #endif
        // #ifdef MP-ALIPAY
        uni.getUserInfo({
          success: function (res) {
            // updateUserInfo({
            //   openId: app.globalData.openid,
            //   nickName: res.userInfo.nickName,
            //   phoneWx: ''
            // });
            storageUserInfo(res.userInfo);
            _that.userInfo = { ..._that.userInfo, ...res.userInfo };
            _that.$refs.authDialogRef.open();
          },
          fail: function (error) {
            console.log("获取会员基本信息失败：", error);
          },
        });
        // #endif
      } else if (!this.userInfo.phoneWx) {
        _that.$refs.authDialogRef.open();
      }
    },
    // 支付宝授权用户基本信息失败
    onAuthError() {
      const _this = this;
      uni.showModal({
        title: "提示",
        content: "取消授权，可能会使部分服务无法使用，或页面信息不完整",
        showCancel: false,
        confirmText: "我知道了",
        success: function (res) {
          if (res.confirm) {
            console.log("用户点击确定");
          } else if (res.cancel) {
            console.log("用户取消授权");
          }
        },
      });
    },

    async getUserInfo() {
      const res = await getUserInfo({
        openId: app.globalData.openid,
      });
      console.log("获取系统用户信息", res);
      if (res.data.uuid) {
        const userInfoStored = uni.getStorageSync("userInfo") || {};
        this.userInfo = { ...this.userInfo, ...res.data, ...userInfoStored };
        storageUserInfo(this.userInfo);
      }
      if (this.userInfo.avatarUrl && this.userInfo.phoneWx) {
        this.hasBaseInfo = true;
      }
    },
    isPhoneNumberPass() {
      const phoneNumber = uni.getStorageSync(USER_INFO).phoneWx;
      if (!phoneNumber) {
        uni.hideTabBar();
        this.$refs.authDialogRef.open();
      }
      return phoneNumber;
    },
    goToBind() {
      console.log("码户绑定点击", this.bindStatus);
      if (this.bindStatus === DOOR_BIND_STATUS.WAIT.VALUE) {
        uni.navigateTo({
          url: "/subPages/pages/bind/bind",
        });
      } else if (this.bindStatus === DOOR_BIND_STATUS.SUBMITTED.VALUE) {
        uni.navigateTo({
          url: "/subPages/pages/door/complete",
        });
      } else {
        uni.navigateTo({
          url: "/subPages/pages/door/door",
        });
      }
    },
    async getDoorList() {
      const res = await getDoorList({
        userInfoId: this.userInfo.uuid,
      });
      // if
      if (res.data.length) {
        console.log("有绑定列表");
        this.isBinded = true;
        uni.setStorage({
          key: DOOR_PLATE_INFO,
          data: res.data,
        });
        this.bindStatus = DOOR_BIND_STATUS.BINDED.VALUE;
        app.globalData.bindStatus = DOOR_BIND_STATUS.BINDED.VALUE;
        app.globalData.doorInfo = res.data[0];
        if (res.data[0] && res.data[0].baseInfo) {
          app.globalData.options = {
            NBID: "",
            Type: res.data[0].baseInfo.type,
            code: res.data[0].baseInfo.doorplateCode,
          };
        }
        this.setDoorInfo();
        this.handleVillageJump()
      } else {
        console.error('scancode1')
        uni.showToast({
          title: '该门牌数据不存在',
          icon: "none",
          duration: 2000,
        });
        setTimeout(() => {
          uni.navigateTo({ url: "/subPages/pages/scanCode/scanCode" });
        }, 1000)
      }
    },
    /* 获取门牌信息后初始化打点 */
    initDoorMarker() {
      /* 打点 */
      this.doorMarker = [
        {
          id: 10000,
          iconPath: "/static/images/common/point_common.png",
          longitude: this.longitude,
          latitude: this.latitude,
          width: 22,
          height: 32,
        },
      ];
    },
    async nearbySearch() {
      const { addressList, markers } = await apiSearch({
        location: `${this.longitude},${this.latitude}`,
        keyword: this.tabs[this.activeTab],
        numberLimit: 5,
      });
      this.addressList = addressList;
      this.sourceAddressList = addressList;
      const pointRes = getPointResByLabel(this.tabs[this.activeTab]);
      markers.forEach((item) => {
        item.iconPath = pointRes.iconPath;
        item.width = 40;
        item.height = 40;
      });
      this.markers = [...this.doorMarker, ...markers];
    },
    async setAddressInfo() {
      let address = "";
      // 为了防止请求经纬度失败去展示默认信息
      this.addressInfo = {
        title: app.globalData.doorInfo.baseInfo.bzdz,
        address: app.globalData.doorInfo.baseInfo.bzdz1,
      };
      if (
          app.globalData.doorInfo.baseInfo.x1 &&
          app.globalData.doorInfo.baseInfo.y1
      ) {
        this.longitude = app.globalData.doorInfo.baseInfo.x1;
        this.latitude = app.globalData.doorInfo.baseInfo.y1;
      } else {
        address = app.globalData.doorInfo.baseInfo.bzdz1;
        if (
            app.globalData.doorInfo.baseInfo.bzdz1.indexOf("宁波市奉化区") === -1
        ) {
          address = "宁波市奉化区" + app.globalData.doorInfo.baseInfo.bzdz1;
        } else {
          address = app.globalData.doorInfo.baseInfo.bzdz1;
        }
        try {
          const res = await geocoder({
            address,
          });
          const location = res.geocodes[0].location.split(",").map(Number);
          this.longitude = location[0];
          this.latitude = location[1];
          // 容错，暂时测试用
          app.globalData.doorInfo.baseInfo.x1 = location[0];
          app.globalData.doorInfo.baseInfo.y1 = location[1];
        } catch {
          uni.showToast({ title: "该门牌地址没有经纬度" });
        }
      }
      /* 设置门牌地址信息，用于搜索周边 */
      this.addressInfo = {
        ...this.addressInfo,
        longitude: this.longitude,
        latitude: this.latitude,
      };
    },
    async setDoorInfo() {
      this.userInfo.address = app.globalData.doorInfo.baseInfo.bzdz1;
      this.userInfo.doorName = app.globalData.doorInfo.baseInfo.bzdz;
      // this.getUserInfo();
      await this.setAddressInfo();
      this.initDoorMarker();
      this.nearbySearch();
    },
    async getDoorplateInfo() {
      const res = await getDoorplateInfo({
        doorplateCode: app.globalData.options.code || "",
        userInfoId: this.userInfo.uuid || "",
      });
      if (res.data && res.data.baseInfo) {
        app.globalData.options = {
          NBID: "",
          Type: res.data.baseInfo.type,
          code: res.data.baseInfo.doorplateCode,
        };
        this.bindStatus = res.data.wxBindStatus;
        app.globalData.bindStatus = res.data.wxBindStatus;
        app.globalData.doorInfo = res.data;
        this.setDoorInfo();
      } else {
        // 有门牌code,但是门牌信息有误
        if (res.code == 1 && this.userInfo.uuid) {
          this.getDoorList();
        } else {
          console.error('scancode2')
          uni.showToast({
            title: '该门牌数据不存在',
            icon: "none",
            duration: 2000,
          });
          setTimeout(() => {
            uni.navigateTo({ url: "/subPages/pages/scanCode/scanCode" });
          }, 1000)
        }
      }
    },
    getNoticeList() {
      const data = {
        current: 1,
        size: 3,
        status: 2
      };
      getNoticeList(data).then((res) => {
        this.noticeBarText = res.data.records;
        if (this.noticeBarText.length < 3) {
          let arr = [];
          for (let i = 0; i < (3 - this.noticeBarText.length); i++) {
            arr.push({ id: 'id' + i, messageHeader: '' })
          }
          this.noticeBarText = this.noticeBarText.concat(arr);
        }
        app.globalData.noticeList = res.data;
        if (res.data && res.data.length > 0) {
          this.currentNoticeId = res.data[0].uuid;
        }
      });
    },
    async getServiceList() {
      const res = await getServiceList();
      console.log("getServiceList", res);
      res.data.forEach((item) => {
        item.appList.forEach((item2) => {
          item2.picUrl = "/static/images/home/" + item2.picUrl + ".png";
        });
        item.appList = item.appList.filter(
            (serviceItem) =>
                serviceItem.jumpType != JUMP_TYPE.WX_APP.VALUE &&
                serviceItem.name !== "为老服务" &&
                serviceItem.name !== "流动人口" &&
                serviceItem.name !== "家门口"
        ); //zlb过滤掉微信跳转相关服务
        const appListLen = item.appList.length;
        // #ifdef MP-WEIXIN || MP-ALIPAY
        item.cleanAppList = splitArr(item.appList, 8);
        // #endif
        // #ifdef H5
        if (this.$uiStyle === "elder") {
          item.cleanAppList = splitArr(item.appList, 6);
          this.indicatorDots = appListLen > 6 ? true : false;
        } else {
          item.cleanAppList = splitArr(item.appList, 8);
          this.indicatorDots = appListLen > 8 ? true : false;
        }
        // #endif
      });
      console.log("servicelist", res.data);
      this.serviceList = res.data;
    },
    handleToLife() {
      uni.navigateTo({
        url: "/subPages/pages/life/life",
      });
    },

    noticeChanged(event) {
      // this.currentNoticeId = event.detail.currentItemId;
      const index = event.detail.current;
      this.currentNoticeId = this.noticeBarText[index].id;
    },

    handleInform() {
      uni.navigateTo({
        url: `/subPages/pages/inform/InformList`,
      });
    },

    handleHelp() {
      if (!this.isPhoneNumberPass()) {
        return;
      }
      uni.navigateTo({
        url: "/subPages/pages/help/helpCall",
      });
    },

    handleAlarm() {
      if (!this.isPhoneNumberPass()) {
        return;
      }
      uni.navigateTo({
        url: "/subPages/pages/alarm/alarmCall",
      });
    },

    handleSearchFocus() {
      uni.navigateTo({
        url: "/subPages/pages/search/search",
      });
    },

    async handleQr() {
      const baseUrl = httpApi.slice(0, httpApi.lastIndexOf("/"));
      let qrUrl = "";
      const env = uni.getEnvVersion();
      console.log(env);
      if (env === "release" || env === "production") {
        const res = await getDoorplatePicUrl({
          code: app.globalData.options.code,
        });
        if (res.code === 0) {
          qrUrl = doorplateImgUrl + "/" + res.data;
        }
      } else {
        qrUrl = this.defaultQr;
      }
      // #ifdef MP-WEIXIN
      if (env === "release") {
        wx.downloadFile({
          url: qrUrl,
          success(res) {
            if (res.statusCode === 200) {
              wx.showShareImageMenu({
                path: res.tempFilePath,
              });
            }
          },
        });
      } else {
        wx.showShareImageMenu({
          path: qrUrl,
        });
      }
      // #endif
      // #ifdef MP-ALIPAY || H5
      console.log("qrUrl", doorplateImgUrl);
      this.qrCodePath = qrUrl;
      this.$refs.popupQrCode.open();
      // #endif
    },
    /* 浙里办长按保存 */
    handleLongpress(type) {
      console.error("长按", type);
      // #ifdef H5
      ZWJSBridge.saveImage({
        url: this.qrCodePath,
      })
          .then((result) => {
            console.log(result);
          })
          .catch((error) => {
            console.log(error);
          });
      // #endif
    },
    handleDoor() {
      if (this.bindStatus === DOOR_BIND_STATUS.SUBMITTED.VALUE) {
        uni.navigateTo({
          url: "/subPages/pages/door/submitDetail",
        });
      } else {
        uni.navigateTo({
          url: "/subPages/pages/door/door",
        });
      }
    },
    handleToggle() {
      uni.getUserInfo({
        success: (res) => {
          console.log(res);
        },
      });
      if (this.cur === "scaned") {
        this.cur = "user";
      } else {
        this.cur = "scaned";
      }
    },

    handleTabChange(e) {
      this.setData({
        activeTab: this.tabs.indexOf(e.label),
      });
      console.log("activeTab", this.activeTab);
      this.nearbySearch();
    },
    /* 单独处理村务公开的逻辑跳转 */
    async handleVillageJump() {
      try {
        const res = await getVillageLink({
          code:app.globalData.doorInfo.doorplateCode
        })
        if(res.code === 0) {
          this.serviceList.map(item => {
            item.cleanAppList.map(item2 => {
              item2.map(item3 => {
                if(item3.name === '村务公开') {
                  item3.jumpUrl = res.data
                }
              })
            })
          })
        }
      }catch (e) {
        console.log('12',e)
      }
    },
    handleModule(item) {
      if(item.name === '村务公开') {
        this.handleVillageJump(item)
      }
      const platformEnv = getPlatformEnv();
      switch (item.jumpType) {
        case JUMP_TYPE.H5.VALUE:
          app.globalData.jumpUrl = item.jumpUrl;
          if (item.name === "户籍管理") {
            app.globalData.jumpUrl =
                "http://portal.zjzwfw.gov.cn/download/?_aaid=4&preferredContainer=zlb&goto=zwfw%3A%2F%2Fwebview%3Fh5Url%3Dhttps%3A%2F%2Fportal.zjzwfw.gov.cn%2Fportal%2Fpage%2Fathena-view.html%3FpageId%3D11276%26_tesseract_%3Dtrue";
          }
          // #ifdef MP-WEIXIN || H5
          if (platformEnv.bIsWxMini) {
            uni.navigateTo({
              url: "/pages/home/webView",
            });
          } else {
            uni.navigateTo({
              url: "/pages/home/webView",
            });
          }

          // #endif
          // #ifdef MP-ALIPAY
          if (uni.getEnvVersion() === "develop") {
            uni.navigateTo({
              url: "/pages/home/webView",
            });
          } else {
            uni.showToast({ title: "暂未开放", duration: 1000 });
          }
          // #endif
          break;
        case JUMP_TYPE.WX_APP.VALUE:
          uni.navigateToMiniProgram({
            appId: item.jumpUrl,
          });
          break;
        case JUMP_TYPE.ZFB_APP.VALUE:
          if (item.jumpUrl) {
            uni.navigateToMiniProgram({
              appId: item.jumpUrl,
            });
          } else {
            uni.showToast({ title: "暂未开放" });
          }
          break;
        case JUMP_TYPE.WX_INSIDE.VALUE:
          app.globalData.jumpUrl = item.jumpUrl;
          uni.navigateTo({
            url: item.jumpUrl,
          });
          break;
        case JUMP_TYPE.MAP.VALUE:
          uni.navigateTo({
            url: `/subPages/pages/mapService/mapService?category=${item.jumpUrl}&keyword=${item.name}`,
          });
          break;
        case JUMP_TYPE.INSIDE.VALUE:
          if(item.jumpUrl === '/subPages/pages/commitment/list/index') {
           /* 浙政钉端的企业承诺首页是这个 */
            uni.navigateTo({
              url: "/subPages/pages/commitment/home/index",
            });
          }else{
            uni.navigateTo({
              url: item.jumpUrl,
            });
          }
          break;
        default:
          break;
      }
    },

    handleAddressGo(e) {
      console.log("导航去那些位置");
      console.log(e);
      console.log(e.currentTarget.dataset["addressinfo"]);
      const targetAddress = e.currentTarget.dataset["addressinfo"];
      uni.openLocation({
        latitude: Number(targetAddress.latitude),
        longitude: Number(targetAddress.longitude),
        scale: 5,
        name: targetAddress.title,
        address: targetAddress.address,

        success(res) {
          console.log(res, "wx.getLocation");
        },
      });
    },

    handleMarker(e) {
      console.log("打点位置", e.currentTarget.dataset["addressinfo"]);
      this.addressInfo = e.currentTarget.dataset["addressinfo"];
      this.marker();
    },

    marker() {
      const targetAddress = this.addressInfo;
      const pointRes = getPointResByLabel(this.tabs[this.activeTab]);
      let markers = JSON.parse(JSON.stringify(this.markers));
      markers.forEach((item) => {
        if (item.title === targetAddress.title) {
          item.iconPath = pointRes.iconPathSelected;
          item.width = 50;
          item.height = 54;
        } else {
          if (item.id !== 10000) {
            item.iconPath = pointRes.iconPath;
            item.width = 40;
            item.height = 40;
          }
        }
      });
      this.markers = markers;
      this.latitude = targetAddress.latitude;
      this.longitude = targetAddress.longitude;
    },
    /* 地图上点击的打点 */
    handleMarkerTap(e) {
      console.log("地图上被点击的点", e.detail.markerId);
      // 10000代表门牌地址
      if (e.detail.markerId === 10000) {
        return;
      }
      const pointRes = getPointResByLabel(this.tabs[this.activeTab]);
      let markers = JSON.parse(JSON.stringify(this.markers));
      markers.forEach((item) => {
        if (item.id === e.detail.markerId) {
          console.log("选中的点", item);
          item.iconPath = pointRes.iconPathSelected;
          item.width = 50;
          item.height = 54;
          this.addressInfo = {
            title: item.title,
            address: "宁波市奉化区" + item.address,
            latitude: item.latitude,
            longitude: item.longitude,
          };
        } else {
          if (item.id !== 10000) {
            item.iconPath = pointRes.iconPath;
            item.width = 40;
            item.height = 40;
          }
        }
      });

      this.markers = markers;
    },
    handlePhoneCall(item) {
      if (!item.tel.length) {
        uni.showToast({
          title: "该商家暂未提供电话",
        });
        return;
      }
      const phoneNumber = item.tel.split(";")[0];
      maskPhoneCall(phoneNumber);
    },
    handlePlaceCulture() {
      const street = app.globalData.doorInfo.baseInfo.xiangzhen;
      const community = app.globalData.doorInfo.baseInfo.shequ;
      app.globalData.showPlaceCulture = false;
      uni.navigateTo({
        url: `/subPages/pages/placeCulture/placeCulture?street=${street}&community=${community}`,
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit("directToPlaceDesc", {
            data: {
              street,
              community,
            },
          });
        },
      });
    },
    handlePlaceQuery() {
      app.globalData.jumpUrl = "https://nbfh.diming123.com/db";
      // #ifdef MP-WEIXIN || H5
      uni.navigateTo({
        url: "/pages/home/webView",
      });
      // #endif
      // #ifdef MP-ALIPAY
      if (uni.getEnvVersion() === "develop") {
        uni.navigateTo({
          url: "/pages/home/webView",
        });
      } else {
        uni.showToast({ title: "暂未开放", duration: 1000 });
      }
      // #endif
    },
    handleQrMerge() {
      uni.navigateTo({
        url: "/subPages/pages/multiCodeMerge/multiCodeMerge",
      });
    },
    perfectInfo() {
      uni.navigateTo({
        url: "/pages/my/perfectInfo",
      });
    },
    async handleMapSearch(){
      //前端对addressList的title做一个模糊匹配
      if(!this.searchMapValue){
        await this.nearbySearch()
      }else {
        this.addressList = this.sourceAddressList.filter(item => item.title.includes(this.searchMapValue))
      }
    },
    /* 跳转基层权利一点通 */
    handleJumpRightLink() {
      app.globalData.jumpUrl = "https://jdydt.jhjw.jinhua.gov.cn/#/wbmh/home";
      uni.navigateTo({
        url: "/pages/home/webView",
      });
    },
  },
};
</script>
<style>
@import "./home.css";
</style>
<style lang="scss" scoped>
.address-list {
  flex: 1;
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
  background: #fff;
  min-height: 20vh;

  .list-cell {
    display: flex;
    padding: 20rpx 36rpx;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px dashed #dedede;

    &__cont {
      flex: 1;
      display: flex;

      .point-icon {
        width: 16px;
        height: 16px;
        margin-right: 5px;
        margin-top: 8px;
      }
    }

    &__title {
      font-size: 28rpx;
      font-weight: bold;
      padding: 14rpx 0;
    }

    &__distance {
      font-size: 20rpx;
      line-height: 28rpx;
      color: #999999;
    }

    &__address {
      font-size: 20rpx;
      line-height: 28rpx;
      color: #999999;
    }

    /* 电话图标 */
    .phone-icon {
      width: 36px;
      height: 36px;
    }
  }
}

.home-page--elder {
  .info {
    .user {
      .user-address {
        &__detail {
          font-size: calc(18px * $zlb-elder-font-scale);
        }

        &__area {
          font-size: calc(11px * $zlb-elder-font-scale);
        }
      }
    }

    .door {
      uni-text {
        font-size: calc(14px * $zlb-elder-font-scale);
      }
    }
  }

  .notice {
    .notice-swiper {
      font-size: calc(16px * $zlb-elder-font-scale) !important;
    }
  }

  /* */
  .service-list {
    ::v-deep uni-swiper {
      height: 256px !important;
    }

    .list-title {
      font-size: calc(16px * $zlb-elder-font-scale);
    }

    .list-cont {
      .list-cell {
        flex: 0 0 33%;

        uni-text {
          font-size: calc(12px * $zlb-elder-font-scale);
        }

        image {
          width: 72px;
          height: 72px;
        }
      }
    }
  }

  .map-head {
    &__title {
      font-size: calc(16px * $zlb-elder-font-scale);
      line-height: calc(16px * $zlb-elder-font-scale);
    }

    &__more {
      font-size: calc(11px * $zlb-elder-font-scale);
      line-height: calc(11px * $zlb-elder-font-scale);
    }
  }

  .map {
    .address {
      &__detail {
        font-size: calc(18px * $zlb-elder-font-scale);
        line-height: calc(28px * $zlb-elder-font-scale);
      }

      &__area {
        font-size: calc(13px * $zlb-elder-font-scale);
        line-height: calc(24px * $zlb-elder-font-scale);
      }
    }
  }

  .custom-tabs ::v-deep .txt {
    font-size: calc(14px * $zlb-elder-font-scale);
  }

  .address-list {
    .list-cell {
      &__title {
        font-size: calc(14px * $zlb-elder-font-scale);
      }

      &__distance {
        font-size: calc(10px * $zlb-elder-font-scale);
        line-height: calc(14px * $zlb-elder-font-scale);
      }

      &__address {
        font-size: calc(10px * $zlb-elder-font-scale);
        line-height: calc(14px * $zlb-elder-font-scale);
      }
    }

    .phone-icon {
      width: calc(36px * $zlb-elder-font-scale);
      height: calc(36px * $zlb-elder-font-scale);
    }
  }
}

.home-page--h5 {
  padding-bottom: 50px;
}

.custom-footer--elder {
  font-size: calc(12px * $zlb-elder-font-scale);
}
.right-easy {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  background: rgba(50, 89, 206, 0.349019607843137);
  color: #fff;
  font-size: 20px;
  height: 93px;
  border-radius: 10px;
  margin-top: 20px;
  view{
    flex: 1;
  }

  image {
    width: 50px;
    height: 50px;
  }
}
</style>
