<template>
  <div class="main">
    <view class="mapBox" v-if="isShowMap">
      <map
        id="myMap"
        :longitude="longitude"
        :latitude="latitude"
        :markers="markers"
        class="map"
        show-location
      ></map>
    </view>
    <div
      class="list"
      :style="{
        transform: isMoveUp ? `translateY(calc(-40vh + 40px))` : '',
      }"
    >
      <div class="top">
        <div class="topImg">
          <image
            class="packUp"
            :style="{ transform: isMoveUp ? 'rotate(180deg)' : '' }"
            src="https://eshangtech.com/ShopICO/ahyd-BID/service/packUp.svg"
            @click="handleClickShowMoveUp"
          ></image>
        </div>
        <div class="search">
          <div class="right">
            <input
              class="searchText"
              v-model="searchText"
              confirm-type="search"
              @confirm="handleSearch"
              placeholder="搜索服务区"
              placeholder-style="font-size: 14px;color: #A69E9F;"
            />
          </div>
        </div>
      </div>
      <scroll-view
        class="serviceList"
        scroll-y
        :style="{ height: isMoveUp ? `calc(100vh - 130px)` : '' }"
        @scrolltolower="handleScrollTolower"
      >
        <div
          class="serviceItem"
          v-for="(item, index) in serviceList"
          :key="index"
          @click="handleGoDetail(item.SERVERPART_ID, item)"
        >
          <div class="topItem">
            <view class="leftItem">
              <p class="title">{{ item.SERVERPART_NAME }}</p>
              <view class="typeBox">{{
                item.SERVERPART_TYPE ? serviceTypeObj[item.SERVERPART_TYPE] : ""
              }}</view>
            </view>
            <div class="box">
              <div class="imgBox" @click.stop="handleGoPhone(item)">
                <image class="icon" src="/static/images/home/phone.png"></image>
              </div>
              <div
                class="imgBox"
                style="margin-right: 0px"
                @click.stop="handleGomap(item)"
              >
                <image class="icon" src="/static/images/home/map.png"></image>
              </div>
            </div>
          </div>
          <div class="info">
            <image
              class="infoIcon"
              src="/static/images/home/addressSelectIcon.png"
            ></image>
            <div class="addressBox">
              <span class="distance">{{ item.SERVERPART_DISTANCE }}km</span>
              <div class="line"></div>
              <span class="address">{{ item.SERVERPART_ADDRESS }}</span>
            </div>
          </div>
          <div class="info" v-if="item.STARTDATE">
            <image class="infoIcon" src="/static/images/home/time.png"></image>
            <p class="time">{{ item.STARTDATE }}</p>
          </div>
          <div class="typeList">
            <image
              class="typeItem"
              :src="
                item.HASCHARGE
                  ? '/static/images/home/Charging.svg'
                  : '/static/images/home/noCharging.svg'
              "
            ></image>
            <image
              class="typeItem"
              :src="
                item.HASPILOTLOUNGE
                  ? '/static/images/home/jinCar.svg'
                  : '/static/images/home/noJinCar.svg'
              "
            ></image>
            <!-- <image
              class="typeItem"
              :src="
                item.SERVERPART_TYPE
                  ? '/static/images/home/health.svg'
                  : '/static/images/home/noHealth.svg'
              "
            ></image> -->
            <image
              class="typeItem"
              :src="
                item.HASMOTHER
                  ? '/static/images/home/baby.svg'
                  : '/static/images/home/nobaby.svg'
              "
            ></image>

            <image
              class="typeItem"
              :src="
                item.HASGUESTROOM
                  ? '/static/images/home/hotel.svg'
                  : '/static/images/home/nohotel.svg'
              "
            ></image>
          </div>
        </div>
        <view class="inBottom" v-if="serviceList && serviceList.length > 0">
          <text class="bottomText">{{
            pageMsg.isOver ? "我是有底线的" : "下拉加载更多"
          }}</text>
        </view>
      </scroll-view>
    </div>
  </div>
</template>

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

import {
  handleHavePointInMin,
  handleHavePointInApp,
} from "../../../utils/publicMethods";
export default {
  data() {
    return {
      menu: {}, // 手机参数
      longitude: null,
      latitude: null,
      userLongitude: null,
      userLatitude: null,
      seat: "",
      statusBarHeight: "",
      isMoveUp: false, // 是否展开
      array: [], // 服务区选择器选择的列表
      selectIndex: null, // 服务区选择器选择的值
      selectValue: "", // 选择的值
      selectName: "", // 选择的片区名字
      searchText: "",
      serviceList: [],
      isShowMap: false,
      serviceTypeObj: {},
      currentServiceMessage: {}, // 当前的服务区数据
      seatInfo: {}, // 经纬度
      loginType: "", // 登录类别
      comeForm: "",
      pageMsg: {
        pageIndex: 1,
        pageSize: 20,
        isOver: false,
      },
      isMoreLoading: false,
    };
  },
  computed: {
    ...mapGetters({
      user: "user",
      tableNum: "orderTable",
      orderRemark: "orderRemark",
      provinceCode: "provinceCode",
      couponPrice: "couponPrice",
      nowStore: "nowStore",
    }),
  },
  async onLoad(option) {
    console.log("option", option);
    if (option.comeForm) {
      this.comeForm = option.comeForm;
    }
    // 获取手机参数
    let systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = Number(systemInfo.statusBarHeight);
    this.menu = uni.getMenuButtonBoundingClientRect();
    // 地图初始化
    this.mapCtx = uni.createMapContext("myMap");
    let seatInfo = uni.getStorageSync("seatInfo");
    if (seatInfo) {
      this.seatInfo = JSON.parse(seatInfo);
    }
    let type = uni.getStorageSync("loginType");
    this.loginType = type;
    if (this.seatInfo.longitude && this.seatInfo.latitude) {
      let res = uni.getStorageSync("currentService");
      console.log("res", res);
      // 已经拿到选中的服务区了
      if (res) {
        this.currentServiceMessage = res;
      }
      // 获取片区列表
      // await this.getServiceList();
      // 服务区的枚举类型
      await this.handleServiceType();

      // 拿到服务区的列表
      await this.handleGetServiceList();
    } else {
      if (this.loginType === "min") {
        handleHavePointInMin().then((res) => {
          console.log("handleHavePointInMin", res);
          _this.handleGetOnLoad();
        });
      } else if (this.loginType === "android") {
        handleHavePointInApp().then((res) => {
          console.log("handleHavePointInApp", res);
        });
      }
    }
    this.$utils.addUserBehaviorNew();
  },
  onHide() {
    this.isShowMap = true;
  },
  onUnload() {
    this.isShowMap = false;
  },
  methods: {
    // 下拉加载更多
    handleScrollTolower() {
      if (this.isMoreLoading) {
        return;
      }
      this.isMoreLoading = true;
      this.pageMsg.pageIndex = this.pageMsg.pageIndex + 1;
      this.handleGetServiceList();
    },
    // 点击了展开
    handleClickShowMoveUp() {
      if (this.isMoveUp) {
        this.isMoveUp = false;
      } else {
        this.isMoveUp = true;
      }
    },
    // 切换片区
    handleChangeService(e) {
      console.log("e", e);
      this.selectIndex = Number(e.mp.detail.value);
      this.selectValue = this.array[this.selectIndex].value;
      this.selectName = this.array[this.selectIndex].name;
    },
    // 获取片区列表
    async getServiceList() {
      let req = {
        Province_Code: this.user.PROVINCE_CODE || "530000",
      };
      const data = await this.$api.$get(
        "/CommercialApi/BaseInfo/GetSPRegionList",
        req
      );
      console.log("data", data);
      this.array = data.Result_Data.List;
      // 已经有选择的服务区的话 根据数据 自动把片区选择起来
      if (this.currentServiceMessage.SPREGIONTYPE_ID) {
        console.log("1");
        let selectIndex = 0;
        this.array.forEach((item, index) => {
          if (item.value === this.currentServiceMessage.SPREGIONTYPE_ID) {
            selectIndex = index;
          }
        });
        this.selectIndex = selectIndex;
        this.selectValue = this.currentServiceMessage.SPREGIONTYPE_ID;
        this.selectName = this.currentServiceMessage.SPREGIONTYPE_NAME;
      } else {
        console.log("2");
        this.selectIndex = 0;
        this.selectValue = this.array[this.selectIndex].value;
        this.selectName = this.array[this.selectIndex].name;
      }
    },
    // 拿到服务区列表
    async handleGetServiceList() {
      if (!(this.seatInfo.longitude && this.seatInfo.latitude)) {
        return;
      }
      // 如果是搜索 那就不能调到这个
      if (this.searchText) {
        return;
      }

      uni.showLoading({
        title: "加载中...",
      });

      let req = {
        Province_Code: this.user.PROVINCE_CODE || "530000",
        // SPRegionType_ID: this.selectValue,
        Serverpart_ID: this.currentServiceMessage.Serverpart_ID || "",
        // 用自己当前位置去查找
        longitude: this.seatInfo.longitude,
        showservice: true,
        latitude: this.seatInfo.latitude,
        PageIndex: this.pageMsg.pageIndex,
        PageSize: this.pageMsg.pageSize,
        // longitude: this.currentServiceMessage.ServerPart_X || "",
        // latitude: this.currentServiceMessage.ServerPart_Y || "",
      };
      const data = await this.$api.$get(
        "/CommercialApi/BaseInfo/GetServerpartList",
        req
      );
      let list =
        data &&
        data.Result_Data &&
        data.Result_Data.List &&
        data.Result_Data.List.length > 0
          ? data.Result_Data.List
          : [];

      if (list && list.length < this.pageMsg.pageSize) {
        this.pageMsg.isOver = true;
      }
      let oldList = [];
      if (this.serviceList && this.serviceList.length > 0) {
        oldList = JSON.parse(JSON.stringify(this.serviceList));
      }
      this.serviceList = oldList.concat(list);
      console.log("this.serviceList", this.serviceList);
      await this.getServiceDetail(this.serviceList[0].SERVERPART_ID);

      this.isMoreLoading = false;
      uni.hideLoading();
    },
    // 选择的服务区详情
    handleGoDetail(id, obj) {
      console.log("id", id);
      console.log("obj", obj);
      let res = this.handleChangeServiceInfo(obj);
      uni.setStorageSync("rankNumber", "");
      uni.setStorageSync("currentService", res); // 当前选中服务区信息
      if (this.comeForm === "home") {
        uni.navigateTo({ url: "/pages/serviceDetail/index" });
      } else {
        uni.navigateBack({
          delta: 1,
        });
      }
    },
    // 兼容一下老接口要的服务区对象的内容
    handleChangeServiceInfo(obj) {
      let newObj = {
        ...obj,
        Distance: obj.SERVERPART_DISTANCE,
        OwnerUnitId: obj.OWNERUNIT_ID,
        OwnerUnitName: obj.OWNERUNIT_NAME,
        ProvinceCode: this.user.PROVINCE_CODE || "530000",
        ServerPart_Id: obj.SERVERPART_ID,
        ServerPart_Name: obj.SERVERPART_NAME,
        ServerPart_Tel: "",
        ServerPart_X: obj.SERVERPART_X,
        ServerPart_Y: obj.SERVERPART_Y,
        showName: `${obj.SERVERPART_NAME}(${obj.SERVERPART_DISTANCE}km)`,
      };
      return newObj;
    },
    // 获取服务区详情信息
    async getServiceDetail(id) {
      let req = {
        ServerpartId: id,
        longitude: this.seatInfo.longitude,
        latitude: this.seatInfo.latitude,
      };
      const data = await this.$api.$get(
        "/CommercialApi/BaseInfo/GetServerpartInfo",
        req
      );
      console.log("data", data);
      this.longitude = data.Result_Data.ServerpartInfo.SERVERPART_X;
      this.latitude = data.Result_Data.ServerpartInfo.SERVERPART_Y;
      this.isShowMap = true;
    },
    // 枚举服务区类型 SERVERPART_TYPE
    async handleServiceType() {
      const data = await this.$api.$get(
        "/EShangApiMain/FrameWork/GetFieldEnumByField",
        { FieldExplainField: "SERVERPART_TYPE" }
      );
      console.log("data", data);
      let obj = {};
      data.Result_Data.List.forEach((item) => {
        obj[Number(item.value)] = item.label;
      });
      console.log("obj", obj);
      this.serviceTypeObj = obj;
    },
    // 搜索框触发的方法
    async handleSearch() {
      this.pageMsg.isOver = false;

      // 如果没有搜索文字 那么就把gapgeMsg变回默认 服务区列表也变为空 重新请求
      if (!this.searchText) {
        this.pageMsg = {
          pageIndex: 1,
          pageSize: 20,
          isOver: false,
        };
        this.serviceList = [];
        this.handleGetServiceList();
        return;
      }
      this.serviceList = [];

      uni.showLoading({
        title: "加载中...",
      });
      let req = {
        // longitude: this.longitude,
        Province_Code: this.user.PROVINCE_CODE || "530000",
        longitude: this.seatInfo.longitude,
        latitude: this.seatInfo.latitude,
        Serverpart_Name: this.searchText,
        showservice: true,
      };
      const data = await this.$api.$get(
        "/CommercialApi/BaseInfo/GetServerpartList",
        req
      );
      let list = data.Result_Data.List;
      if (list && list.length < this.pageMsg.pageSize) {
        this.pageMsg.isOver = true;
      }
      let oldList = [];
      if (this.serviceList && this.serviceList.length > 0) {
        oldList = JSON.parse(JSON.stringify(this.serviceList));
      }
      this.serviceList = oldList.concat(list);
      this.pageMsg.isOver = true;
      uni.hideLoading();
    },
    handleGomap(obj) {
      uni.openLocation({
        latitude: obj.latitude ? obj.latitude * 1 : obj.SERVERPART_Y * 1,
        longitude: obj.longitude ? obj.longitude * 1 : obj.SERVERPART_X * 1,
        scale: 16, // 缩放比例
        name: obj.SERVERPART_NAME,
        // address: "", // 这个可能会影响地图的定位，所以可以选择不填
        success(data) {
          console.log(data);
        },
        fail(err) {
          console.log(err);
        },
      });
    },
    handleGoPhone(obj) {
      if (obj.SERVERPART_TEL) {
        uni.makePhoneCall({
          phoneNumber: obj.SERVERPART_TEL,
        });
      } else {
        uni.showToast({
          title: "暂无联系电话！",
          icon: "none",
        });
      }
    },
  },
};
</script>
<style scoped lang="stylus">
.main {
  height: 100vh;
  width: 100%;
  position: relative;

  .leftArrow {
    width: 24px;
    height: 24px;
    position: absolute;
    left: 16px;
    z-index: 99999999999;

    .img {
      width: 100%;
      height: 100%;
    }
  }

  .mapBox {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 40vh;

    .map {
      width: 100%;
      height: 40vh;
    }

    .ydBox {
      width: 40px;
      height: 40px;
      background: #fff;
      border-radius: 50%;
      position: absolute;
      bottom: 40px;
      left: 16px;
      display: flex;
      align-items: center;
      justify-content: center;

      .ydIcon {
        width: 30px;
        height: 30px;
      }
    }
  }

  .list {
    width: 100%;
    height: calc(60vh + 20px);
    box-sizing: border-box;
    transform: translateY(-20px);
    background: #F2F4F5;
    position: absolute;
    top: 40vh;

    .top {
      width: 100%;
      height: 74px;
      padding: 0 16px;
      // border-radius: 20px 20px 0 0;
      box-sizing: border-box;
      background: #fff;
      box-shadow: 0 4px 4px 0 rgba(22, 0, 2, 0.04);

      .topImg {
        display: flex;
        justify-content: center;

        .packUp {
          width: 26px;
          height: 5px;
          margin-top: 8px;
        }
      }

      .search {
        width: 100%;
        height: 36px;
        background: #F2F4F5;
        border-radius: 4px;
        margin-top: 13px;
        box-sizing: border-box;
        padding: 8px 24rpx;
        display: flex;
        align-items: center;

        .left {
          width: 40%;
          position: relative;

          .pick {
            .box {
              display: flex;
              align-items: center;

              .picker {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #160002;
                line-height: 20px;
              }

              .selectIcon {
                width: 15px;
                height: 15px;
                margin-left: 6px;
              }
            }
          }
        }

        .left:after {
          content: '';
          width: 2px;
          height: 20px;
          position: absolute;
          right: 0;
          top: 0;
          background: #E1DFDF;
        }

        .right {
          width: 100%;

          .searchText {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #A69E9F;
            line-height: 20px;
          }
        }
      }
    }

    .serviceList {
      width: 100%;
      height: calc(100% - 90px);
      box-sizing: border-box;
      padding: 0 16px;
      overflow-y: auto;
      background: #FFFFFF;

      .serviceItem {
        width: 100%;
        padding: 12px;
        box-sizing: border-box;
        background: #FFFFFF;
        border-radius: 8rpx;
        border: 2rpx solid #F5F6F7;
        margin-bottom: 12px;

        .topItem {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .leftItem {
            display: flex;
            align-items: center;

            .title {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 32rpx;
              color: #130F05;
              line-height: 44rpx;
              text-align: left;
              font-style: normal;
              margin-right: 12rpx;
            }

            .typeBox {
              // background: linear-gradient(180deg, rgba(49, 144, 255, 0.2) 0%, rgba(22, 87, 255, 0.2) 100%);
              background: #FEF7E5;
              border-radius: 8rpx;
              padding: 0 8rpx;
              font-size: 24rpx;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              // color: #1E67FF;
              color: #BA922F;
              line-height: 40rpx;
              margin-left: 16rpx;
            }
          }

          .box {
            display: flex;
            align-items: center;

            .imgBox {
              width: 28px;
              height: 28px;
              // border: 1px solid #F1F1F1;
              // overflow: hidden;
              margin-right: 16px;
              border-radius: 50%;
              background: #F5F6F7;
              display: flex;
              align-items: center;
              justify-content: center;

              .icon {
                width: 32rpx;
                height: 32rpx;
              }
            }
          }
        }

        .distance {
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #786B6C;
          line-height: 18px;

          .number {
            color: #D7000F;
            margin: 0 2px;
          }
        }

        .info {
          display: flex;
          align-items: center;
          margin-top: 4px;

          .time {
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #786B6C;
            line-height: 18px;
          }

          .infoIcon {
            width: 24rpx;
            height: 24rpx;
            margin-right: 8rpx;
          }

          .addressBox, .time {
            display: flex;
            align-items: center;
            width: 100%;

            .distance {
              color: #130F05;
              margin-right: 4rpx;
            }

            .line {
              width: 1px;
              height: 24rpx;
              background: #E7E7E6;
              margin: 0 16rpx;
            }

            .address {
              font-size: 12px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: #786B6C;
              line-height: 18px;
            }
          }
        }

        .typeList {
          margin-top: 8px;
          display: flex;
          align-items: center;

          .typeItem {
            width: 40rpx;
            height: 40rpx;
            margin-right: 16rpx;
          }
        }
      }

      .inBottom {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        .bottomText {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 26rpx;
          color: #d0d0d0;
          line-height: 40rpx;
          text-align: justify;
          font-style: normal;
          position: relative;
          padding: 6rpx 0;
        }

        .bottomText::after {
          content: '';
          width: 30vw;
          height: 2rpx;
          background: #e0e0e0;
          position: absolute;
          left: -32vw;
          top: 50%;
        }

        .bottomText::before {
          content: '';
          width: 30vw;
          height: 2rpx;
          background: #e0e0e0;
          position: absolute;
          right: -32vw;
          top: 50%;
        }
      }
    }
  }
}
</style>
