<template>

  <view class="list">
    
    <view class="search" v-if="showFrame">
      <div class="dist_search">
        <picker @change="bindPickerChange" :value="cityIndex" :range="cityArr">
            <view class="district">{{cityArr[cityIndex]}}</view>
        </picker>
        <view class="icon"></view>
      </div>
      
      <view class="separate">

      </view>
      <view class="inp">
        <view class="icon">
        </view>
        <input type="text" v-model="filterCityText" placeholder="请输入油站名称" />
      </view>
    </view>
    
    <view class="postion" v-if="showFrame">
      <view class="icon"></view>
      <view class="current" @click="reGetLocation">
        当前位置：{{location}}
      </view>
      <view class="refresh" @click="refresh">
      </view>
    </view> 
   
    <view class="distance" 
      style="margin-top: 200rpx;text-align: center;"
      v-if="moreDistanceTipShow"
    >
      您附近{{distanceShow}}公里内没有油站
    </view>
    <view class="collection">
      <view class="station" 
        v-for="ele in filterDistanceArr"
        @click="goBuy($event, ele.stationId)"
      >
        <view class="content">
          <image :src="ele.stationPic" mode=""></image>
          <view class="detail">
            <view class="name">{{ ele.stationName }}</view>
            <view class="other">
              <text v-if="ele.distance!==undefined">{{ele.distance + ' '}}km | </text> 
              {{ ' ' + ele.stationAddress }}
            </view>
          </view>
        </view>
        <view class="footer">
          <view class="gothere" @click.stop="goThere($event, ele.stationLatitude, ele.stationLongitude, ele.stationName, ele.stationAddress)">
            去这里
          </view>
          <view class="separator">|</view>
          <view class="gobuy" @click.stop="goBuy($event, ele.stationId)">
            去买单
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations,
    mapGetters
  } from "vuex";
  import Parse from "../../util/parse.js"
  import settings from '@/settings.js'

  // import getPermission from "../../util/permission.js"
  export default {
    data() {
      return {
        // notice: '',
        stationList: [],
        filterCityText: '',
        res: {},
        // cityArr:['泰安市','济南市'],
        cityIndex:0,
        location:'正在拼命拉取中...',
        showFrame:false,
        showDistanceEmptyListTip:false,
        distanceShow:settings.distanceShow
      }
    },
    async created() {
      // 调试
      // wx.setEnableDebug({
      //   enableDebug: true
      // })
      this.initAli()
      this.init()
    },
    computed: {
      moreDistanceTipShow(){
        return settings.distanceFlag && settings.distanceShow!=0 && this.filterDistanceArr.length == 0 && this.showDistanceEmptyListTip
      },
      filterCityArr(){        
        return this.stationList.filter((ele)=>{
          if(this.cityArr[this.cityIndex] == '全部'){
            return ele.stationName.includes(this.filterCityText) || ele.stationAddress.includes(this.filterCityText)
          }
          return ele.city === this.cityArr[this.cityIndex] && (ele.stationName.includes(this.filterCityText) || ele.stationAddress.includes(this.filterCityText))
        })
      },
      cityArr(){
        const cityArrSet = new Set(['全部']);
        this.stationList.map((ele)=>{
          cityArrSet.add(ele.city)
        })
        return [...cityArrSet]
      },
      filterDistanceArr(){
        if(settings.distanceFlag){
          if(settings.distanceShow!=0){
            return this.filterCityArr.filter((ele)=>{
              return ele.distance <= settings.distanceShow
            })
          }
        }
        return this.filterCityArr
      }
    },
    methods: {
      ...mapMutations(["updateStationId","clearEmployeeId"]),
      test() {
        console.log(132)
      },
      initAli(){
        // #ifdef  MP-ALIPAY
        settings.distanceFlag = true;
        settings.distanceShow = settings.aLiDistanceShow;
        // #endif
      },
      async init() {
        uni.showLoading({
          title: '加载中...',
          mask: true
        });
        const oldStationList = this.stationList;
        const oldLocation = this.location
        try{
          this.location = '正在拼命拉取中...'
          //#ifdef MP-WEIXIN
          const stationListData = await this.$Request({
            url: "/getStationListByAppId",
            method: "GET",
            data: {
              appId: this.appId
            }
          })
          //#endif
          //#ifdef MP-ALIPAY
          const stationListData = await this.$Request({
            url: "/getStationListToAliPay",
            method: "GET",
            data: {
              // appId: this.appId
            }
          })
          //#endif
          if(stationListData.retCode !== 0){
            throw new Error("初始油站信息失败")
          }
          // 单站
          if(stationListData.data.length === 1){
            this.updateStationId(stationListData.data[0].stationId)
            const [redirectErr, redirectData] = await uni.redirectTo({
              url: "/pages/index/index"
            })
            return
          }
          
          if(settings.distanceFlag && settings.distanceShow==0){
            this.stationList = []
          }else{
            this.stationList = stationListData.data;
            this.showFrame = true;
          }
          
          
          const locationData = await uni.getLocation()
          if(locationData[0] !== null && locationData[0].errMsg === 'getLocation:fail auth deny' ){
            // 用户拒绝位置
            this.location = "您拒绝了授权，点击重新获取~"
            this.showFrame = true;
            uni.hideLoading();
            return
          }else if(locationData[0] !== null && locationData[0].errMsg === 'getLocation:fail 频繁调用会增加电量损耗，可考虑使用 wx.onLocationChange 监听地理位置变化' ){
            // 频繁调用时兼容处理
            this.location = oldLocation
            this.stationList = oldStationList
            this.showFrame = true;
            uni.hideLoading();
            return
          }else if(locationData[0] !== null && locationData[0].errMsg === 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF' ){
            this.location = "您的手机未开启定位"
            this.showFrame = true;
            uni.hideLoading();
            return
          }else if(locationData[0] !== null){
            this.location = "没有获取到您的位置"
            this.showFrame = true;
            uni.hideLoading();
            return
          }
          //#ifdef MP-WEIXIN
          const stationLocationData = await this.$Request({
            url: "/getStationInfoListNew",
            method: "GET",
            data: {
              stationLongitude:locationData[1].longitude,
              stationLatitude: locationData[1].latitude,
              pageNum: 1,
              pageSize:1000,
              appId: this.appId
            }
          })
          //#endif
          //#ifdef MP-ALIPAY
          const stationLocationData = await this.$Request({
            url: "/getStationInfoListNewToAliPay",
            method: "GET",
            data: {
              stationLongitude:locationData[1].longitude,
              stationLatitude: locationData[1].latitude,
              pageNum: 1,
              pageSize:1000,
              appId: this.appId
            }
          })
          //#endif
          if(stationLocationData.retCode !== 0){
            throw new Error("获取定位信息失败")
          }
          
          this.location = stationLocationData.data.address
        
          if(settings.distanceFlag && settings.distanceShow==0){
            this.goBuyReplace(stationLocationData.data.stationInfoResponseList[0].stationId)
            this.stationList = []
          }else{
            this.showDistanceEmptyListTip = true
            this.stationList = stationLocationData.data.stationInfoResponseList
          }
          
          // const stationLocationListData = await this.$Request({
          //   url: "/getStationInfoList",
          //   method: "GET",
          //   data: {
          //     stationLongitude:locationData[1].longitude,
          //     stationLatitude: locationData[1].latitude,
          //     pageNum: 1,
          //     pageSize:1000,
          //     appId: this.appId
          //   }
          // })
          
          // if(stationLocationListData.retCode !== 0){
          //   throw new Error("获取详细油站信息失败")
          // }
          // this.stationList = stationLocationListData.data.stationInfoResponseList
          
          uni.hideLoading();
        }catch(e){
          // uni.hideLoading();
          uni.showToast({
            title: e
          })
        }
      },
      goBuy(e, stationId) {
        if(!!e){
          e.stopPropagation()
        }
        this.updateStationId(stationId)
        this.clearEmployeeId()
        uni.navigateTo({
          url: "/pages/index/index"
        })
        return
      },
      goBuyReplace(stationId) {
        this.updateStationId(stationId)
        this.clearEmployeeId()
        uni.redirectTo({
          url: "/pages/index/index"
        })
        return
      },
      goThere(e, latitude, longitude, stationName, stationAddress) {
        e.stopPropagation()
        uni.openLocation({
          name: stationName,
          address: stationAddress,
          latitude: parseFloat(latitude),
          longitude: parseFloat(longitude),
          success: function() {
            console.log('success');
          }
        });
      },
      async refresh(){
        // uni.getSetting({
        //    success(res) {
        //       console.log(res.authSetting)
        //    }
        // })
        this.init()
      },
      async reGetLocation(){
        const that = this
        // try{
          const getSetPro = await uni.getSetting()
          if(getSetPro[0] === null){
            if(!getSetPro[1].authSetting['scope.userLocation']){
              uni.openSetting({
                success(res) {
                  if(res.authSetting['scope.userLocation']){
                    that.refresh();
                  }else{
                    uni.showToast({
                      icon:'error',
                      title:'还没授权呦~',
                      mask: true
                    })
                  }
                }
              })
            }else{
              that.refresh()
            }
          }else{
            throw new Error("")
          }
          
        // }catch(e){
        //   uni.showToast({
        //     icon:'error',
        //     title:'授权时出错~',
        //     duration:1200,
        //     mask: true
        //   })
        //   setTimeout(()=>{
        //     that.refresh();
        //   },1600)
        // } 
      },
      bindPickerChange(e){
        this.cityIndex = e.detail.value
      }
    }
  }
</script>

<style lang="scss">
  page {
    .list {
      padding: 30rpx;
      background: #F6F6F6;
      height: 100vh;

      .search {
        width: 690rpx;
        height: 80rpx;
        background: #FFFFFF;
        box-shadow: 0px 2rpx 9rpx 4rpx rgba(99, 99, 99, 0.1);
        border-radius: 40rpx;
        // position: relative;
        display:flex; 
        flex-direction: row; 
        justify-content:space-around;
        align-items: center;
        
        
        .dist_search {
          height: 80rpx;
          max-width: 130rpx;
          white-space: nowrap;
          display: flex;
          margin-left: 20rpx;

          .district {
            height: 80rpx;
            font-size: 28rpx;
            font-weight: bold;
            color: #111111;
            line-height: 80rpx;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            max-width: 110rpx;
          }

          >.icon {
            background: url(../../static/icon/1_b01_down.2x.png) no-repeat 0px 0px;
            background-size: 100% 100%;
            width: 13rpx;
            height: 8rpx;
            line-height: 80rpx;
            margin-top: 38rpx;
            margin-left: 10rpx;
          }
        }

        .separate {
          width: 0rpx;
          height: 35rpx;
          border: 1rpx solid #CCCCCC;
          box-sizing: border-box;
          // position: absolute;
          // top: 20rpx;
          // left: 180rpx;
        }

        .inp {
          // position: absolute;
          // top: 15rpx;
          // left: 200rpx;
          width: 450rpx;
          height: 80rpx;
          // position: relative;
          

          .icon {
            display: inline-block;
            background: url(../../static/icon/1_b01_search.2x.png) no-repeat 0px 0px;
            background-size: 100% 100%;
            width: 26rpx;
            height: 26rpx;
            margin-bottom: 25rpx;
            // // top: 162rpx;
            // position: absolute;
            // top: 27rpx;
          }

          >input {
            display: inline-block;
            margin-left: 20rpx;
            width: 310rpx;
            height: 80rpx;
            line-height: 80rpx;
            background:none;  
            outline:none;  
            border:none;
          }
        }
      }

      .postion {
        margin: 30rpx 30rpx 0 30rpx ;
        
        .icon {
          background: url(../../static/icon/1_b01_location.2x.png) no-repeat 0px 0px;
          background-size: 100% 100%;
          width: 33rpx;
          height: 35rpx;
          display: inline-block;
        }

        .current {
          margin-left: 20rpx;
          display: inline-block;
          height: 40rpx;
          font-size: 28rpx;
          color: #868686;
          line-height: 40rpx;
          max-width: 550rpx;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        .refresh {
          background: url(../../static/icon/icon_shuaxin.2x.png) no-repeat 0px 0px;
          background-size: 100% 100%;
          // background-color: #868686;
          margin-top: 5rpx;
          width: 27rpx;
          height: 27rpx;
          float: right;
        }

      }

      .collection {
        margin-top: 30rpx;

        .station {
          margin-bottom: 30rpx;
          // padding: 30rpx;
          padding: 40rpx;
          width: 690rpx;
          height: 285rpx;
          background: #FFFFFF;
          box-shadow: 0px 2rpx 9rpx 4rpx rgba(99, 99, 99, 0.1);
          border-radius: 18rpx;
          box-sizing: border-box;

          .content {
            display: flex;

            >image {
              width: 155rpx;
              height: 155rpx;
              display: inline-block;
            }

            .detail {
              margin-left: 20rpx;
              width: 450rpx;
              height: 155rpx;
              display: inline-block;

              .name {
                height: 45rpx;
                font-size: 32rpx;
                font-weight: bold;
                color: #111111;
                line-height: 45rpx;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
            }

          }

          .footer {
            margin-top: 40rpx;
            display: flex;
            justify-content: space-around;

            .gothere {
              height: 40rpx;
              width: 250rpx;
              font-size: 28rpx;
              font-weight: bold;
              color: #6c6c6c;
              line-height: 40rpx;
              text-align: center;
            }

            .separator {
              // width: 1px;
              // height: 46rpx;
              // border: 1px solid #CCCCCC;
              color: #CCCCCC;
            }

            .gobuy {
              height: 40rpx;
              font-size: 28rpx;
              font-weight:bold;
              width: 250rpx;
              color: #F3B235;
              line-height: 40rpx;
              text-align: center;
            }
          }
        }
      }
    }

  }
</style>
