<template>
  <div class="main">
      <div class="leftArrow" :style="{top:(menu.top + ((menu.height - 24)/2) )+ 'px'}" @click="handleBack">
          <image class="img" src="https://eshangtech.com/ShopICO/ahyd-BID/commercial/navigation-left.svg"></image>
      </div>
      <view class="mapBox" v-if="isShowMap">
        <map  id="myMap" :longitude="longitude" :latitude="latitude" :markers="markers" class="map" show-location></map>
        <view class="ydBox" @click="handleClickYD">
          <image class="ydIcon" src="/static/images/tabBar/company_active.png"/>
        </view>
      </view>
      <view v-else class="map"></view>
      <div class="list" :style="{transform:isMoveUp?`translateY(calc(-40vh + ${menu.bottom + 5}px))`:''}">
          <div class="top">
              <div class="topImg" @click="handleChangeUp">
                  <image class="packUp" :style="{transform:isMoveUp?'rotate(180deg)':''}" src="https://eshangtech.com/ShopICO/ahyd-BID/service/packUp.svg"></image>
              </div>
              <div class="search">
                  <div class="left">
                      <picker class="pick" @change="handleChangeService($event)" :value="selectIndex" :range="array" range-key="name">
                          <div class="box">
                              <view class="picker">
                                  {{array[selectIndex].name?array[selectIndex].name:''}}
                              </view>
                              <image class="selectIcon"  src="https://eshangtech.com/ShopICO/ahyd-BID/service/upArrow.svg"></image>
                          </div>
                      </picker>
                  </div>
                  <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>
          <div class="serviceList" :style="{height:isMoveUp?`calc(100vh - 90px - ${menu.bottom + 5}px)`:''}">
              <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">{{serviceTypeObj[item.SERVERPART_TYPE]}}</view>
                    </view>
                      <div class="box">
                          <div class="imgBox">
                              <image class="icon" src="https://eshangtech.com/ShopICO/ahyd-BID/service/phone.svg"></image>
                          </div>
                          <div class="imgBox" style="margin-right: 0px" @click.stop="handleGomap(item)">
                              <image class="icon" src="https://eshangtech.com/ShopICO/ahyd-BID/service/map.svg"></image>
                          </div>
                      </div>
                  </div>
                  <p class="distance">距您 <text class="number">{{item.SERVERPART_DISTANCE}}</text> km</p>
                  <div class="info">
                      <image class="infoIcon" src="https://eshangtech.com/ShopICO/ahyd-BID/service/address.svg"></image>
                      <p class="address">{{item.SERVERPART_ADDRESS}}</p>
                  </div>
                  <div class="info" v-if="item.STARTDATE">
                      <image class="infoIcon" src="https://eshangtech.com/ShopICO/ahyd-BID/service/time.svg"></image>
                      <p class="time">{{item.STARTDATE}}</p>
                  </div>
                  <div class="typeList">
                      <image class="typeItem" v-if="item.SERVERPART_TYPE"  src="https://eshangtech.com/ShopICO/ahyd-BID/service/health.svg"></image>
                      <image class="typeItem" v-if="item.HASMOTHER" src="https://eshangtech.com/ShopICO/ahyd-BID/service/baby.svg"></image>
                      <image class="typeItem" v-if="item.HASPILOTLOUNGE" src="https://eshangtech.com/ShopICO/ahyd-BID/service/car.svg"></image>
                      <image class="typeItem" v-if="item.HASCHARGE" src="https://eshangtech.com/ShopICO/ahyd-BID/service/Charging.svg"></image>
                      <image class="typeItem" v-if="item.HASGUESTROOM" src="https://eshangtech.com/ShopICO/ahyd-BID/service/hotel.svg"></image>
                  </div>
              </div>
          </div>
      </div>
  </div>
</template>

<script>
import request from '@/util/index.js'
import {getFieldEnum} from "../../util/dateTime";
export default {
    name: "index",
    data(){
        return {
            isShowMap:false,
            longitude: null,
            latitude: null,
            userLongitude:null,
            userLatitude:null,
            mapCtx: {},
            menu:{},//手机参数
            statusBarHeight:'',// 每个手机的状态栏高度
            selectIndex:null,//服务区选择器选择的值
            array:[],//服务区选择器选择的列表
            serviceList:[],
            searchText:'',
            isMoveUp:false, //是否展开
            chartType:false,//是否从图表也跳过来
            page:'',//从哪个图表也跳过来
            markers:'',//地图属性
            covers:'',//地图属性
            area:'',//当前选中片区名称
            serviceInfo:{},
          type:'',// 哪里进来
          serviceTypeObj:{},
          serviceMessage:{},// 当前选中的服务区
        }
    },
    onLoad(option){
        wx.getFuzzyLocation({
            type:'gcj02',
            altitude:true,
            success: (res) =>{
                let seatInfo = {
                    latitude:res.latitude,
                    longitude:res.longitude
                }
                uni.setStorageSync('seatInfo', seatInfo);
                this.seat = seatInfo
                let userSeat = uni.getStorageSync('seatInfo')
                this.userLatitude = userSeat.latitude
                this.userLongitude = userSeat.longitude
                this.getServiceList()
            }
        })
      if (option.serviceInfo){
        this.serviceInfo = JSON.parse(option.serviceInfo)
      }
        if (option.chartType){
            this.chartType = true
        }
        this.page = option.page
        this.type = option.type
      console.log('type',this.type)
    },
    onShow(){
        let seat = uni.getStorageSync('currentService')
      console.log('seat',seat)
        if (seat && !seat.latitude){
            JSON.parse(seat)
        }
        if (seat){
            this.longitude = seat.longitude
            this.latitude = seat.latitude
            this.area = seat.SPREGIONTYPE_NAME
            // 标点
            this.addMarkers(seat)
            this.getServiceList()
        }else{
            // 查详情
            this.getServiceDetail(this.serviceInfo.Serverpart_ID)
        }
        // 获取手机参数
        let systemInfo = uni.getSystemInfoSync()
        this.statusBarHeight = Number(systemInfo.statusBarHeight)
        this.menu = uni.getMenuButtonBoundingClientRect()
        // 地图初始化
        this.mapCtx = uni.createMapContext('myMap')
      // 服务区类型枚举
      this.handleServiceType()
        // this.getLocation()
        // this.getListData()
    },
    onHide(){
        this.isShowMap = true
    },
    onUnload(){
        this.isShowMap = false
        this.$util.addUserBehavior()
    },
    watch:{
        // 监听经纬度
        latitude:{
            handler(value){
                if (value){
                    this.getListData()
                }
            },
            deep:true,
            immediate:true
        }
    },
    methods:{
      // 点击驿达表示 默认选择驿达
      handleClickYD(){
        let YD = {
          SERVERPART_NAME: "安徽驿达",
          SPREGIONTYPE_NAME: "",
          SPRegionType_ID: null,
          Serverpart_ID: 424,
          latitude: 32,
          longitude: 117,
        }
        uni.setStorageSync('currentService',YD)
        uni.navigateBack({
          delta: 1
        })
      },
      // 枚举服务区类型 SERVERPART_TYPE
      async handleServiceType(){
        const data = await getFieldEnum({ FieldExplainField: 'SERVERPART_TYPE' });
        console.log('data',data)
        let obj = {}
        data.forEach(item=>{
          obj[Number(item.value)] = item.label
        })
        console.log('obj',obj)
        this.serviceTypeObj = obj
      },
        //跳转到腾讯地图
        handleGomap(item){
            let seat = uni.getStorageSync('seatInfo')
            let key='STWBZ-DKCR4-J6UUF-FRD5I-3EBN2-GDBOT'
            let referer ='goMap'
            let startPoint = {
                name:'我的位置',
                latitude:seat.latitude,
                longitude:seat.longitude
            }
            let endPoint={
                'name': item.SERVERPART_NAME,
                latitude: item.SERVERPART_Y,
                longitude: item.SERVERPART_X
            }
            wx.navigateTo({
                url: `plugin://routePlan/index?key=${key}&referer=${referer}&endPoint=${JSON.stringify(endPoint)}&startPoint=${JSON.stringify(startPoint)}`
            });
        },
        //返回上一级页面
        handleBack(){
            uni.navigateBack({
                delta: 1
            })
        },
        //获取服务区详情信息
        async getServiceDetail(id){
          let req = {
              ServerpartId:id
          }
          const data = await request.$webGet('CommercialApi/BaseInfo/GetServerpartInfo',req)
          this.longitude = data.Result_Data.ServerpartInfo.SERVERPART_X
          this.latitude = data.Result_Data.ServerpartInfo.SERVERPART_Y
          this.isShowMap = true
        },
        //获取片区列表
        async getServiceList(){
            let req = {
                Province_Code:'340000'
            }
            const data = await request.$webGet('CommercialApi/BaseInfo/GetSPRegionList',req)
            console.log('data123',data)
            let list = []
            data.Result_Data.List.forEach(item=>{
              list.push({name:item.name,value:item.value})
            })
            // let list = [{name:'安徽驿达',value:'0'}]
            // data.Result_Data.List.forEach(item=>{
            //   list.push({name:item.name,value:item.value})
            // })
          let seat = uni.getStorageSync('currentService')
          if (seat && seat.SERVERPART_NAME==='安徽驿达'){
            this.selectIndex = 0
            this.serviceMessage = seat
          }
            this.array = list
            if (this.area){
                this.array.forEach((item,index)=>{
                    if (item.name === this.area){
                        this.selectIndex = index
                    }
                })
            }
            await this.getLocation()
        },
        //选择片区
        handleChangeService(e){
          console.log('e',e)
          this.selectIndex = Number(e.detail.value)
          console.log(this.selectIndex)
          if (this.selectIndex===0){
            let res = {
              SERVERPART_NAME: '安徽驿达',//服务区
              SPREGIONTYPE_NAME: '安徽驿达',//片区
              Serverpart_ID: null,
              SPRegionType_ID: null,
              longitude:'117.200927',
              latitude:'31.832905',
            }
            uni.setStorageSync('currentService',res) //当前选中服务区信息
            if(this.type==='springTravel'){

            }else{
              if (this.chartType){
                uni.navigateBack({
                  delta: 1
                })
              }else{
                uni.navigateBack({
                  delta: 1
                })
              }
            }
          }
          this.getListData()

        },
        //搜索框触发的方法
        async handleSearch(){
            let req = {
                longitude:this.longitude,
                Province_Code:'340000',
                latitude:this.latitude,
                Serverpart_Name:this.searchText
            }
            const data = await request.$webGet('CommercialApi/BaseInfo/GetServerpartList',req)
            this.serviceList = data.Result_Data.List
        },
        //跳转相对应的服务区详情界面
        handleGoDetail(id,item){
            let res = {
                SERVERPART_NAME:item.SERVERPART_NAME,//服务区
                SPREGIONTYPE_NAME:item.SPREGIONTYPE_NAME,//片区
                Serverpart_ID:item.SERVERPART_ID,
                SPRegionType_ID:item.SPREGIONTYPE_ID,
                longitude:item.SERVERPART_X,
                latitude:item.SERVERPART_Y,
            }
            uni.setStorageSync('currentService',res) //当前选中服务区信息
            let pageList = getCurrentPages()
          if (this.type==='index'){
            this.$util.toNextRoute('navigateTo', `/pages/summaryOfPortraits/index?index=0`)
          }else if(this.type==='springTravel'){
            uni.setStorageSync('springService',res) //当前选中服务区信息
            uni.navigateBack({
              delta: 1
            })
          }
          else{
            if (this.chartType){
              uni.navigateBack({
                delta: 1
              })
            }else{
              if (pageList.length>2){
                uni.navigateBack({
                  delta: 1
                })
              }
            }
          }
        },
        async getListData(){
          let id
          let user =  uni.getStorageSync('seatInfo')
          let current = uni.getStorageSync('currentService')
          let nearService = uni.getStorageSync('nearService')
            if (!this.selectIndex && this.selectIndex!==0){
                if (!current){
                    id = nearService.SPRegionType_ID
                }else{
                    id = current.SPRegionType_ID
                }
                this.array.forEach((item,index)=>{
                    if (Number(item.value) === Number(id)){
                        this.selectIndex = index
                    }
                })
            }else{
                id = this.array[this.selectIndex].value
            }
            // if (seat){
            // }else{
            //     if (this.array[this.selectIndex] && this.array[this.selectIndex].value){
            //         id = this.array[this.selectIndex].value
            //     }
            // }
            let req = {
                Province_Code: '340000',
                SPRegionType_ID: id,
                Serverpart_ID:current.Serverpart_ID,
                longitude:user.longitude,
                latitude:user.latitude
            }
            const data = await request.$webGet('CommercialApi/BaseInfo/GetServerpartList',req)
            this.serviceList = data.Result_Data.List
          console.log(' this.serviceList', this.serviceList)
          if (this.serviceMessage && this.serviceMessage.SERVERPART_NAME){
            if (this.serviceList && this.serviceList.length>0){
              this.longitude = this.serviceList[0].SERVERPART_X
              this.latitude = this.serviceList[0].SERVERPART_Y
            }
          }
        },
        //点击向上移动
        handleChangeUp(){
            if (this.isMoveUp){
                this.isMoveUp = false
            }else{
                this.isMoveUp = true
            }
        },
         async getLocation(){
            let seat = uni.getStorageSync('seatInfo')
            if (!seat){
                uni.getFuzzyLocation({
                    type:'gcj02',
                    altitude:true,
                    success:function (res){
                        this.latitude = res.latitude
                        this.longitude = res.longitude
                    }
                })
            }else {
                await this.getListData()
            }

        },
        //添加标点
        addMarkers(value){
            let markers = []
            markers.push({
                // iconPath: 'https://eshangtech.com/ShopICO/ahyd-BID/service/health.svg',
                id: value.Serverpart_ID,
                latitude: value.latitude,
                longitude: value.longitude
            })
            // }
            this.markers = markers
            this.isShowMap = true
        }
    }
}
</script>

<style scoped lang="scss">
.main{
  max-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 16px;
        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{
              margin-left: 12px;
              .searchText{
                  font-size: 14px;
                  font-family: PingFangSC-Regular, PingFang SC;
                  font-weight: 400;
                  color: #A69E9F;
                  line-height: 20px;
              }
          }
      }
    }
      .serviceList{
          margin-top: 12px;
          width: 100%;
          height: calc(100% - 90px);
          box-sizing: border-box;
          padding: 0 16px ;
          overflow-y: auto;
          .serviceItem{
              width: 100%;
              padding: 12px;
              box-sizing: border-box;
              background: #FFFFFF;
              border-radius: 8px;
              margin-bottom: 12px;
              .topItem{
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                .leftItem{
                  display: flex;
                  align-items: center;
                  .title{
                    font-size: 14px;
                    font-family: PingFangSC-Semibold, PingFang SC;
                    font-weight: 600;
                    color: #160002;
                    line-height: 20px;
                  }
                  .typeBox{
                    background: linear-gradient(180deg, rgba(49, 144, 255, 0.2) 0%, rgba(22, 87, 255, 0.2) 100%);
                    border-radius: 8rpx;
                    padding: 0 16rpx;
                    font-size: 28rpx;
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    color: #1E67FF;
                    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%;
                          .icon{
                              width: 100%;
                              height: 100%;
                          }
                      }
                  }
              }
              .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;
                  .infoIcon{
                      width: 12px;
                      height: 15px;
                      margin-right: 4px;
                  }
                  .address,.time{
                      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: 16px;
                      height: 16px;
                      margin-right: 9px;
                  }
              }
          }
      }
  }
}
</style>
