<template>
  <div class="container store-page" >
    <div v-if="selectVal" @click="selectVal=''" class='modal-page'></div>
    <div class="store-toolbar">
      <div class="toolbar">
        <div class="item item1" @click="selectItem()">
          服务项目
          <van-icon class="icon" :name="selectVal==='item' ? 'arrow-up': 'arrow-down' " />
        </div>
        <div class="item" :class="areaTitle != '所在区域'? 'red-text': ''" @click="selectArea()">
          {{areaTitle}}
          <van-icon class="icon" :name="selectVal==='area' ? 'arrow-up': 'arrow-down' " />
        </div>
        <div>
          <van-icon name="search" @click="openSearch" style="font-size: 26px; font-weight: 600;" />
        </div>
      </div>
      <div class="toolbar-detail" :class="{'show': showBar}" v-show="selectVal !== ''">
        <div class="service-panel" v-show="selectVal === 'item'">
          <van-checkbox-group class="checkbox-group" :value="queryStoreBizList" @change="itemChangeHandle">
            <van-checkbox class="checkbox-item" :name="item.code" v-for="item in itemList" :key="item.id">{{item.dispName}}</van-checkbox>
          </van-checkbox-group>
        </div>
        <div class="area-panel" v-show="selectVal === 'area'">
          <van-button class="select-button" @click="openCitySelect" size="small" plain hairline type="info">选择其它城市</van-button>
          <van-radio-group class="checkbox-group radio-group" :value="selectKey" @change="areaChangeHandle">
            <van-radio class="radiobox-item" checked-color="red" :name="area.addrDistrict" v-for="area in areaList" :key="area.addrDistrict">
             <van-icon v-if="currentCode && currentCode== area.addrDistrict" name="location" style="color: #ff8811; font-size: 16px;" />
             {{area.addrDistrictName}}({{area.storeSum}})
            </van-radio>
          </van-radio-group>
        </div>
        <div class="toolbar-detail-control" v-show="selectVal === 'item'">
          <van-button block class="btn" @click="cancelSearchHandle">重置</van-button>
          <van-button block class="btn" type="danger" @click="searchHandle">确定</van-button>
        </div>
      </div>
    </div>
    <scroll-view scroll-y class="store-content">
      <v-card style="height:auto" :thumb="item.icon" v-for="(item, index) in storeList" :key="item.id">
        <div class="store-info">
          <div class="title txt-clip">{{item.name}}</div>
          <div class="content">
            <div class="left">
              <div class="desc">
                <van-rate :value="item.star" size="10" color="#ff8811" allow-half void-color="#eee" void-icon="star" />
                <span class="rate-num">{{item.star}}</span>
              </div>
              <div class="phone">
                <van-icon name="phone" class="phone-icon" />
                <div @click="callPhone(item.managerMobile)"> {{item.managerMobile}} </div>
              </div>
            </div>
            <div class="right" v-if="item.distance&&item.distance>=0" @click="openLocation(item)">
              <div class="navigation">
                <van-icon name="location" />
                导航
              </div>
              <div>
                距您{{item.distance}}KM
              </div>
            </div>
          </div>
          <div>
            <div>
              {{item.addrProvinceName + item.addrCityName + item.addrDistrictName + item.addrDetail}}
            </div>
            <div class="tags">
              <div class="tag" v-for="(tag, index2) in item.storeBizList" :key="tag.id">{{tag.bizTypeName}}</div>
            </div>
          </div>
        </div>
      </v-card>
      <no-data :options="storeList" name="此地区还未开通门店"/>
    </scroll-view>
  </div>
</template>

<script>
import { getLookUpData } from '@/api/api';
import { getListStore, getListArea, getCurrentArea } from '@/api/store.js'
import NoData from '@/components/NoData';
import storage from '@/utils/storage.js'
import { province, city, area } from '@/api/address.js'
export default {
  name: 'packageDetail',
  components: { 'no-data': NoData },
  data() {
    return {
      storeList: [],
      gpsCompletion: false,
      showBar: false,
      selectVal: '',
      currenCity: '', // 定位城市信息对象
      showCoupons: false,
      areaTitle: "所在区域", // 区域名称
      isLastPage: false,
      pageNo: 1,
      pageSize: 10,
      isloaded: false, // 判断是否请求接口完成
      queryWord: '',
      currentCode: '', // 当前定位所在区域
      currentPosition: {
        lat: '',
        lng: ''
      },
      itemList: [],
      selectKey: '', // 所选区域code
      queryAddrDistrictList: '',
      queryStoreBizList: [],
      areaList: [],
      areaListTotal: [], // 从area的json中获取的城市的所有区
      optionCode: '' // 选择其他城市编码
    };
  },
  computed: {

  },
  methods: {
    // 页面初始化
    pageInit () {
      this.selectVal = '';
      this.pageNo = 1;
      this.storeList = [];
      this.isLastPage = false
      this.isloaded = false
    },
    // 打开搜索页面
    openSearch () {
      console.log(this.queryAddrDistrictList,'选择的城市')
      wx.navigateTo({
        url: `/pages/storeSearch/main?lat=${this.currentPosition.lat}&lng=${this.currentPosition.lng}&areaCode=${this.queryAddrDistrictList}`
      })
    },
    // 打开选择城市页面
    openCitySelect () {
      wx.navigateTo({
        url: `/pages/selectCity/main?code=${this.currenCity.code}&name=${this.currenCity.name}`

      })
    },

    callPhone(phone) {
      wx.makePhoneCall({
        phoneNumber: phone
      });
    },

    // 根据市的code获取该市所有的区  参数code：城市编码
    getAreaList (code) {
      console.log(code,'getAreaList--code')
      console.log(area,'area')
      console.log(city,'city')
      // 获取定位城市数据
       let currenArea = area.find(item=>{
         return item.code == this.currentCode
       })
       console.log(currenArea)
       this.currenCity = city.find(item=>{
         return item.code == code
       })

      this.areaTitle = currenArea ? currenArea.name : this.currenCity.name
      // 获取定位或选择城市的所有区
      let arr = []
       area.map( item =>{
           if (item.cityCode == code ){
             arr.push(item)
           }
       })
       this.areaListTotal = arr
    },

    // 获取当前定位所在区域的区域编码
    getAreaCode () {
      getCurrentArea({ lng: this.currentPosition.lng ,lat:this.currentPosition.lat }).then( res =>{
        console.log(res, 'res----code')
        if (res.status == 200) {
          this.queryWord = res.data.adcode
          this.currentCode = res.data.adcode // 区
          let cityCode = res.data.cityCode.slice(0,4) // 城市
          this.getAreaList(cityCode) // 获取定位城市的所有区
          this.queryAddrDistrictList = res.data.adcode
          this.getStoreList()
          let _this = this
           setTimeout(function() {
             _this.getAreaStore()
           }, 100);
        }
      })
    },

    // 选择城市获取各区门店数量
    getAreaStore () {
      let _this = this
      let query = ""
      let hotCityList =[
        {name:"西安市",code:"6101"},
        {name:"咸阳市",code:"6104"},
        {name:"渭南市",code:"6105"},
        {name:"商洛市",code:"6110"},
        {name:"铜川市",code:"6102"},
        {name:"兰州市",code:"6201"},
        ]
        let has= hotCityList.find(item=>{
          item.code == this.currenCity.code
        })
      if (!has && !this.optionCode){ // 定位城市不是热门城市
        // wx.showToast({
        // 	title: '您所在区域暂未开通服务，将为您默认展示西安区域门店'
        // })
        query = "6101"
      }else if (!this.queryWord ) {
        query = "6101"  // 没有定位 默认西安市
      } else {
        query = this.queryWord
      }
      getListArea({ queryWord:query, enableFlag:1 }).then( res =>{
        console.log(res, 'res----store')
        if (res.status == 200) {
          let temp = []
            let arr = _this.areaListTotal
            //console.log(arr,"arr")
            for(let i=0;i<arr.length;i++){
              let has = res.data.find(item => { return item.addrDistrict == arr[i].code })
              if(!has){
                temp.push({
                  addrDistrict: arr[i].code,
                  addrDistrictName: arr[i].name,
                  storeSum: 0
                  })
              }
            }

          this.areaList = res.data.concat(temp)
          //console.log(this.areaList, "this.areaList")
        }
      })
    },
    getStarNum(level) {
      const star = (5 - 0.5 * (level - 1)).toString();
      return star.indexOf('.') > -1 ? star : star + '.0';
    },
    searchHandle() {
      this.pageInit()
      this.getStoreList();
    },
    itemChangeHandle(val) {
      this.queryStoreBizList = val.mp.detail;
    },
    areaChangeHandle(val) {
      //console.log(val, 'val')
      this.queryAddrDistrictList = val.mp.detail;
      this.selectKey = val.mp.detail
      let selectArea = this.areaList.find( item =>{
        return item.addrDistrict == val.mp.detail
      })
      this.areaTitle = selectArea.addrDistrictName
      this.searchHandle()
    },
    selectItem() {
      if (this.selectVal !== 'item') {
        this.selectVal = 'item';
      } else {
        this.selectVal = '';
      }
    },
    // 选择区域
    selectArea() {
      if (this.selectVal !== 'area') {
        this.selectVal = 'area';
      } else {
        this.selectVal = '';
      }
    },
    openLocation(item) {
      wx.openLocation({
        latitude: item.lat - 0,
        longitude: item.lng - 0,
        name: item.name,
        address: item.addrProvinceName + item.addrCityName + item.addrDistrictName + item.addrDetail
      });
    },
    // 格式化数据
    formatList(list) {
      const _this = this;
      if (_this.gpsCompletion && list.length) {
        list.forEach(item => {
          item.distance = item.distance ? (item.distance/1000).toFixed(2) : '';
          item.star = this.getStarNum(item.level);
        });
        return list;
      } else if( _this.isloaded && !list.length){
        return []
      }
      return [];
    },
    // 获取门店列表
    getStoreList() {
      const {queryAddrDistrictList, queryStoreBizList} = this
      const _this = this;
      wx.showLoading({
        mask: true,
        title: '加载中'
      });
      let params={
        queryStoreBizList,
        enableFlag: 1,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        lat: this.currentPosition.lat,
        lng: this.currentPosition.lng
      }
      if (queryAddrDistrictList.length == 4){ // 查询市的门店
        params.addrCity = queryAddrDistrictList
      } else {  // 查询区的门店
        params.addrDistrict = queryAddrDistrictList
      }
      if (!params.lat && !params.lng){
        delete params.lat
        delete params.lng
      }

    getListStore(params).then(res => {
      setTimeout(function(){
        wx.hideLoading();
      },500)
      console.log(res, 'res')
      if(res.status == "200"){
        _this.isloaded = true
        if ( _this.pageNo == 1) {
          _this.storeList = _this.formatList(res.data.list)
        } else {
          _this.storeList = _this.storeList.concat(_this.formatList(res.data.list))
        }
        let len = _this.storeList.length
        if(len>=res.data.count){
          if(_this.pageNo!=1){
            wx.showToast({
              title: '已经是最后一页'
            })
          }
          _this.isLastPage = true
        }
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2500
        });
      }
    });
    },
    cancelSearchHandle() {
      if (this.selectVal === 'item') {
        this.queryStoreBizList = [];
      } else {
        this.queryAddrDistrictList = '';
      }
      wx.showLoading({
        mask: true,
        title: '加载中'
      });
      this.selectVal = '';
      this.getStoreList();
    },
    // 默认西安的门店
    getDefaultStore () {
      // 没有定位 默认西安市'
      this.queryAddrDistrictList = this.queryAddrDistrictList ? this.queryAddrDistrictList : "6101"
      this.areaTitle = this.areaTitle ? this.areaTitle : "西安市"
      this.currentCode = this.queryAddrDistrictList
      this.getAreaList(this.queryAddrDistrictList.slice(0,4))
      let _this = this
      setTimeout(function() {
        _this.getAreaStore()
      }, 100);
      this.getStoreList()
      this.showBar = false
    }
  },
  // 监听用户上拉触底事件
  onReachBottom() {
  	if(!this.isLastPage){
  		this.pageNo = this.pageNo + 1
  		this.getStoreList()
  	}
  },
  onShow() {
    wx.showLoading({
      mask: true,
      title: '加载中'
    });

    const _this = this;
    this.showBar = false;
    // this.queryAddrDistrictList = '';
    // this.queryStoreBizList = [];
    this.pageInit()

    // 选择其他城市
    if (this.optionCode&&this.optionCode!='null'){
      console.log(this.optionCode,'选择其他城市')
      this.areaListTotal = []
      this.queryWord = this.optionCode
      this.queryAddrDistrictList = this.optionCode
      this.currentCode = this.optionCode
      this.getAreaList(this.optionCode)
      let _this = this
      setTimeout(function() {
        _this.getAreaStore()
      }, 100);
      this.getStoreList();
      this.showBar = true;
    }else{
      // 根据定位获取城市
      wx.getLocation({
        type: 'wgs84', // 默认wgs84
        success: function(res) {
          console.log('getLocation success')
          _this.currentPosition.lat = res.latitude;
          _this.currentPosition.lng = res.longitude;
          _this.getAreaCode();
        },
        fail: function(res) {
          console.log(res,'getLocation fail')
          // 没有定位 默认西安市'
          _this.getDefaultStore()
          _this.gpsCompletion = false;
        },
        complete: function(){
          console.log('getLocation complete')
          _this.gpsCompletion = true;
          _this.showBar = true;
        }
      });
    }
  },
  onLoad(options) {
    console.log(options,"sotore index options")
    if (options.code&&options.code!='null'){ // 选择其他城市
      this.optionCode = options.code
      this.areaTitle = options.name
      this.selectKey = options.code
    }
    const _this = this;
    getLookUpData({ type: 'SERVICE_TYPE' }).then(res => {
      if (res.status === '200') {
        _this.itemList = res.data;
      }
    });
  }
};
</script>

<style lang="stylus">
._v-card .v-card{
  border-bottom: 1px solid #eee;
  height:auto;
}
.vcard .van-card__img{
  border-radius:5px;
}
.container {
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  padding-top: 70rpx;
}
.modal-page {
  width :100%;
  height :100%;
  z-index :2;
  background-color :black;
  opacity :0.6;
  position: fixed;
  top: 0;
  left: 0;
}
.store-content {
  height: 100%;
  box-sizing: border-box;
}

.store-toolbar {
  position: fixed;
  top: 0;
  width: 100%;
  box-sizing: border-box;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
  background-color: #fff;
  z-index: 9;
  .toolbar {
    display: flex;
    justify-content: space-around;
    height: 70rpx;
    align-items: center;
    .item {
      width: 35%;
    }

    .item1 {
      text-align: right;
    }
  }
  .red-text {
    color : #ff8811;
  }
  .toolbar-detail {
    background-color: #fff;
    position: absolute;
    // top: 73rpx;
    left: 0;
    right: 0;
    opacity: 0;
    z-index :99;
    &.show {
      opacity: 1;
    }
  }
}

.icon {
  position: relative;
  top: 4rpx;
}

.store-info {
  box-sizing: border-box;
  font-size: 25rpx;
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .content {
    display: flex;
    flex: 1;

    .left {
      flex: 1;
    }

    .navigation {
      font-size: 1em;
      text-align: right;
    }
  }

  .title {
    font-size: 1em;
    padding: 10rpx 0;
    font-weight:bold;
  }

  .desc {
    color: #80848f;
    display: flex;
  }

  .rate-num {
    padding: 0 15rpx;
  }

  .phone {
    display: flex;
    align-items: center;
    padding: 12rpx 0;
    color:#57a3f3;
  }

  .tags {
    margin-top: 5rpx;
    display: flex;
    font-size: 0.8em;

    .tag {
      color: #808695;
      border: 1rpx solid #ff5500;
      padding: 5rpx 10rpx;
    }

    .tag + .tag {
      margin-left: 10rpx;
    }
  }
}
.select-button {
  border-radius :5px;
  position: absolute;
  right: 20px;
  top: 10px;
}
.checkbox-group {
  padding: 5px 20px 5px 40px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.radio-group {
  max-height: 280px;
  overflow: auto;
}
.checkbox-item {
  width: 40vw;
  padding: 15rpx 0;
}
.radiobox-item {
  width :100%;
  padding :10px 0;
  display : flex;
  align-items : center;
  border-bottom :1px solid #9999;
  .van-radio__label{
    flex-grow : 1;
  }
}
.toolbar-detail-control {
  display: flex;
  .btn {
    flex: 1;
  }
}
</style>
