<template>
<view>
	<view class="">
		<view class="cu-bar bg-white search " >
			<view class="search-form round">
				<text class="cuIcon-search"></text>
				<input type="text" confirm-type="search" @input="bindKeyInput" @blur="bindBlur" placeholder="输入城市名或拼音查询" placeholder-style="font-size: 28rpx" :value="inputName"></input>
			</view>
		</view>
	</view>
<view class="container-inner">
  <view class="searchLetter touchClass">
    <view class="thishotText" @tap="hotCity">
      <view style="margin-top:0;">当前</view>
      <view style="margin-top:0;">热门</view>
    </view>
    <view v-for="(item, index) in searchLetter" :key="index" class="text-red-btn" style="font-size:20rpx;" :data-letter="item.name" @click="clickLetter">{{item.name}}</view>
  </view>
  <view class="container">

    <block v-if="isShowLetter">
      <view class="showSlectedLetter">
        {{toastShowLetter}}
      </view>
    </block>
    <scroll-view scroll-y="true" :style="'height:' + winHeight + 'px'" @scroll="bindScroll" :scroll-into-view="scrollTopId" :scroll-top="scrollTop">
     <view class="bg-white">
      	<view class="solid-bottom  li" v-for="(item, index) in completeList" :key="index" @tap="bindCity" :data-city="item.city" :data-code="item.code" >
			<text class="padding-left-50">{{item.city}}</text>
      	</view>
      </view>
      <view v-if="condition" class="hotcity-common" style="margin-bottom: 10rpx;" >选择区县</view>
      <view v-if="condition" class="county">
        <block v-for="(item, index) in countyList" :key="index"  class="hotCity">
          <view class="weui-grid" style="margin-right: 16rpx;" :data-code="item.id" :data-city="item.fullname" @tap="bindCounty">
            <view class="weui-grid__label">{{item.fullname}}</view>
          </view>
        </block>
      </view>

      <view class="selectCity">
        <view class="hotcity-common" @tap="reGetLocation">重新定位城区</view>
        <view class="thisCityName" :data-city="city" :data-code="currentCityCode">{{city}}{{county}}</view>

        <view class="hotcity-common">热门城市</view>
        <view class="weui-grids">
          <view class="weui-grid" data-code="110000" data-city="北京市" @tap="bindCity">
            <view class="weui-grid__label">北京市</view>
          </view>
          <view class="weui-grid" data-code="310000" data-city="上海市" @tap="bindCity">
            <view class="weui-grid__label">上海市</view>
          </view>
          <view class="weui-grid" data-code="440100" data-city="广州市" @tap="bindCity">
            <view class="weui-grid__label">广州市</view>
          </view>
        </view>
        <view class="weui-grids">
          <view class="weui-grid" data-code="440300" data-city="深圳市" @tap="bindCity">
            <view class="weui-grid__label">深圳市</view>
          </view>
          <view class="weui-grid" data-code="330100" data-city="杭州市" @tap="bindCity">
            <view class="weui-grid__label">杭州市</view>
          </view>
          <view class="weui-grid" data-code="320100" data-city="南京市" @tap="bindCity">
            <view class="weui-grid__label">南京市</view>
          </view>
        </view>
        <view class="weui-grids">
          <view class="weui-grid" data-code="420100" data-city="武汉市" @tap="bindCity">
            <view class="weui-grid__label">武汉市</view>
          </view>
          <view class="weui-grid" data-code="120000" data-city="天津市" @tap="bindCity">
            <view class="weui-grid__label">天津市</view>
          </view>
          <view class="weui-grid" data-code="610100" data-city="西安市" @tap="bindCity">
            <view class="weui-grid__label">西安市</view>
          </view>
        </view>
      </view>
      <view v-for="(item, index) in cityList" :key="index" class="selection">
        <view class="item_letter" :id="item.initial">{{item.initial}}</view>
        <view v-for="(ct, index2) in item.cityInfo" :key="index2" class="item_city" :data-code="ct.code" :data-city="ct.city" @tap="bindCity">
          {{ct.city}}
        </view>
      </view>
    </scroll-view>

  </view>
</view>
</view>
</template>

<script>
var app=getApp()
const city = require("../../utils/city.js");
const cityObjs = require("../../utils/city.js");
const config = require("../../utils/config.js");
const appInstance = getApp();
export default {
  data() {
    return {
      searchLetter: [],
      showLetter: "",
      winHeight: 0,
      cityList: [],
      isShowLetter: false,
      scrollTop: 0,
	  oldScrollTop:0,
      //置顶高度
      scrollTopId: '',
      //置顶id
      city: "定位中...",
      currentCityCode: '',
      inputName: '',
      completeList: [],
      county: '',
	  //do
      condition: false,
	  
      itemH: "",
      toastShowLetter: "",
      countyList: ""
    };
  },

  components: {},
  props: {},
  onLoad: function () {
    // 生命周期函数--监听页面加载
    const searchLetter = city.searchLetter;
    const cityList = city.cityList();
    const sysInfo = uni.getSystemInfoSync();
    console.log(sysInfo);
    const winHeight = sysInfo.windowHeight;
    const itemH = winHeight / searchLetter.length;
    let tempArr = [];
    searchLetter.map((item, index) => {
      // console.log(item);
      // console.log(index);
      let temp = {};
      temp.name = item;
      temp.tHeight = index * itemH;
      temp.bHeight = (index + 1) * itemH;
      tempArr.push(temp);
    }); // console.log(tempArr);

    this.setData({
      winHeight: winHeight,
      itemH: itemH,
      searchLetter: tempArr,
      cityList: cityList,
      //兼容地图插件
      city: appInstance.globalData.city,
      currentCityCode: appInstance.globalData.currentCityCode,
      county: appInstance.globalData.county
    }); //this.getLocation();
  },
  methods: {
	  goTop (e) {
		  //视图会发生重新渲染
		  this.scrollTop = this.oldScrollTop
		  //当视图渲染结束 重新设置为0
		  this.$nextTick(() =>{
			  this.scrollTop = 0
		  });
	  },
    clickLetter: function (e) {
      // console.log(e);
      console.log(e.currentTarget.dataset.letter);
      const showLetter = e.currentTarget.dataset.letter;
      this.setData({
        toastShowLetter: showLetter,
        isShowLetter: true,
        scrollTopId: showLetter
      }); // const that = this;
      // wx.showToast({
      //   title: showLetter,
      //   disabled: true,
      //   duration: 500,
      //   complete: function() {
      //     that.setData({
      //       scrollTopId: showLetter,
      //     })
      //   }
      // })

      const that = this;
      setTimeout(function () {
        that.setData({
          isShowLetter: false
        });
      }, 500);
    },
    reGetLocation: function () {
      appInstance.globalData.defaultCity = this.city;
      appInstance.globalData.defaultCounty = this.county;
      console.log(appInstance.globalData.defaultCity); //返回首页

      uni.navigateTo({
        url: "/pages/choosePlot/choosePlot"
      });
    },
    //选择城市
    bindCity: function (e) {
	  this.goTop()
      this.setData({
        condition: true,
        city: e.currentTarget.dataset.city,
        currentCityCode: e.currentTarget.dataset.code,
        completeList: []
      });
      this.selectCounty();
      appInstance.globalData.defaultCity = this.city;
      appInstance.globalData.defaultCounty = '';
      this.setData({
        county: "",
        currentCityCode: ""
      });
      console.log(appInstance.globalData.defaultCity);
    },
    bindCounty: function (e) {
      console.log(e); //this.setData({ county: e.currentTarget.dataset.city })
      //appInstance.defaultCounty = this.data.county

      console.info("////" + this.city);
      let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息.

      let prevPage = pages[pages.length - 2].$vm; //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。
	  
	  if(!this.$isEmpty(this.city)){
	  	app.globalData.city=this.city
	  }
	  if(!this.$isEmpty(e.currentTarget.dataset.city)){
	  	app.globalData.county=e.currentTarget.dataset.city
	  }
	  if(!this.$isEmpty(e.currentTarget.dataset.code)){
	  	app.globalData.currentCityCode=e.currentTarget.dataset.code
	  }
      prevPage.setData({
        // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
        city: this.city,
        //广州市
        county: e.currentTarget.dataset.city,
        //页面标签定义的是city--天河区
        currentCityCode: e.currentTarget.dataset.code //天河区的code

      }); //从新获取楼栋信息

      prevPage.getCommunity(); //上一个页面内执行setData操作，将我们想要的信息保存住。当我们返回去的时候，页面已经处理完毕。
      //最后就是返回上一个页面。

      uni.navigateBack(); //console.log(appInstance.defaultCounty);
      // wx.navigateBack({
      //   url: "/pages/choosePlot/choosePlot",
      // })
    },
    //点击热门城市回到顶部
    hotCity: function () {
      console.log("hotCity");
      this.setData({
        scrollTop: 0
      });
    },
    bindScroll: function (e) {//  console.log(e.detail)
		this.oldScrollTop = e.detail.scrollTop
    },
    selectCounty: function () {
      console.log("正在定位区县");
      let code = this.currentCityCode; // console.log(code);

      const that = this;
      uni.request({
        url: `https://apis.map.qq.com/ws/district/v1/getchildren?&id=${code}&key=${config.key}`,
        success: function (res) {
          // console.log(res.data)
          // console.log(res.data.result[0]);
          that.setData({
            countyList: res.data.result[0]
          }); // console.log(that.data.countyList);

          console.log("请求区县成功" + `https://apis.map.qq.com/ws/district/v1/getchildren?&id=${code}&key=${config.key}`); // console.log(res)
        },
        fail: function () {
          console.log("请求区县失败，请重试");
        }
      });
    },
    getLocation: function () {
      console.log("正在定位城市");
      this.setData({
        county: ''
      });
      const that = this;
      uni.getLocation({
        type: 'wgs84',
        success: function (res) {
          let latitude = res.latitude;
          let longitude = res.longitude;
          uni.request({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${config.key}`,
            success: res => {
              // console.log(res)
              console.log(res.data.result.ad_info.city + res.data.result.ad_info.adcode);
              that.setData({
                city: res.data.result.ad_info.city,
                currentCityCode: res.data.result.ad_info.adcode,
                county: res.data.result.ad_info.district
              });
              that.selectCounty();
            }
          });
        }
      });
    },
    bindBlur: function (e) {
      this.setData({
        inputName: ''
      });
    },
    bindKeyInput: function (e) {
      this.setData({
        inputName: e.detail.value
      });
      this.auto();
	  
	  this.goTop()
    },
    auto: function () {
      let inputSd = this.inputName.trim();
      let sd = inputSd.toLowerCase();
      let num = sd.length;
      const cityList = cityObjs.cityObjs; // console.log(cityList.length)

      let finalCityList = [];
      let temp = cityList.filter(item => {
        let text = item.short.slice(0, num).toLowerCase();
        return text && text == sd;
      }); //在城市数据中，添加简拼到“shorter”属性，就可以实现简拼搜索

      let tempShorter = cityList.filter(itemShorter => {
        if (itemShorter.shorter) {
          let textShorter = itemShorter.shorter.slice(0, num).toLowerCase();
          return textShorter && textShorter == sd;
        }

        return;
      });
      let tempChinese = cityList.filter(itemChinese => {
        let textChinese = itemChinese.city.slice(0, num);
        return textChinese && textChinese == sd;
      });

      if (temp[0]) {
        temp.map(item => {
          let testObj = {};
          testObj.city = item.city;
          testObj.code = item.code;
          finalCityList.push(testObj);
        });
        this.setData({
          completeList: finalCityList
        });
      } else if (tempShorter[0]) {
        tempShorter.map(item => {
          let testObj = {};
          testObj.city = item.city;
          testObj.code = item.code;
          finalCityList.push(testObj);
        });
        this.setData({
          completeList: finalCityList
        });
      } else if (tempChinese[0]) {
        tempChinese.map(item => {
          let testObj = {};
          testObj.city = item.city;
          testObj.code = item.code;
          finalCityList.push(testObj);
        });
        this.setData({
          completeList: finalCityList
        });
      } else {
        return;
      }
    }
  }
};
</script>
<style lang="scss">
.container-inner {
  display: flex;
  flex-direction: row-reverse;
}

.container {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  padding: 0rpx;

}

input {
  text-align: center;
  font-size: 32rpx;
  padding: 5px;
}

.searchLetter {
  flex-shrink: 0;
  width: 80rpx;
  text-align: center;
  display: flex;
  flex-direction: column;
  color: #666;
}

.searchLetter view {
  margin-top: 20rpx;
}

.touchClass {
  background-color: #fff;
  color: #fff;
  padding-top: 16rpx;
  padding-bottom: 16rpx;
}

.showSlectedLetter {
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 50%;
  left: 50%;
  margin: -100rpx;
  width: 200rpx;
  height: 200rpx;
  border-radius: 20rpx;
  font-size: 52rpx;
  z-index: 1;
}

.selection {
  display: flex;
  width: 100%;
  flex-direction: column;
  margin-top: 10rpx;
}

.selectCity {
  padding: 16rpx;
  background-color: #FFFFFF;
  margin-bottom: -10rpx;
}

.item_letter {
  color: $base-btn-color;
  display: flex;
  background-color: #f5f5f5;
  height: 40rpx;
  padding-left: 34rpx;
  align-items: center;
  font-size: 24rpx;
}

.item_city {
  display: flex;
  background-color: #fff;
  height: 100rpx;
  padding-left: 34rpx;
  align-items: center;
  border-bottom: 1rpx solid #ededed;
  font-size: 24rpx;
}

.hotcity-common {
  font-size: 24rpx;
  color: #666;
  padding-bottom: 0;
  margin: 8rpx 0;
  margin-left: 16rpx;
}

.hotCity {
  padding-right: 50rpx;
  margin: auto;
}

.thisCityName {
  display: inline-block;
  border: 1rpx solid $base-btn-color;
  border-radius: 8rpx;
  padding: 16rpx 20rpx;
  font-size: 24rpx;
  color: $base-btn-color;
  text-align: center;
  min-width: 149.5rpx;
  margin: 16rpx 0;
}

.thishotText {
  color: $base-btn-color;
  font-size: 20rpx;
  margin: 0 !important;
}

.slectCity {
  border-color: $base-btn-color !important;
}

.slectCity view {
  color: $base-btn-color !important;
}

.weui-grid {
  padding: 18rpx 0;
  width: 200rpx;
  box-sizing: border-box;
  border: 1rpx solid #c8c8c8;
  border-radius: 8rpx;
  background-color: white;
  margin: 8rpx 0;
}

.weui-grids {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.weui-grid__label {
  display: block;
  text-align: center;
  color: #333;
  font-size: 24rpx;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.ul {
  display: block;
  color: grey;
  margin-left: 20rpx;
}

.li {
  display: block;
  font-weight: 100;
  font-size: 28rpx;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #efefef;
}

input {
  background-color: #fff;
}

.input {
  padding: 16rpx;
  border-bottom: 1rpx solid #f1f1f1;
}

.county {
  padding: 10rpx 0 0 20rpx;
  background-color: #FFFFFF;
  display: flex;
  flex-wrap: wrap;
}

</style>