<template>
  <view class="facade">
    <navbar
      :config="config"
      @searchConfirm="searchConfirm"
      @searchBlur="searchBlur"
    >
      <view class="map" slot="left">
        <picker
          class="pickerList"
          mode="multiSelector"
          :range="newProvinceDataList"
          range-key="label"
          :value="multiIndex"
          @change="pickerChange"
          @columnchange="pickerColumnchange"
        >
          <text>{{ city }}</text>
          <text class="iconfont down">&#xe645;</text>
        </picker>
      </view>
    </navbar>
    <view class="top">
      <view
        class="item"
		:class="activeIndex==index?'active':''"
        v-for="(item ,index) in cates"
        :key="item.id"
        @click="changeCateId(item,index)"
      >
        {{ item.name }}
      </view>
    </view>
    <view class="content" v-if="shops.length > 0">
      <view class="item" v-for="(item,key) in shops" :key="key">
       <view class="item-top" @click="goShop(item.shop_id)">
          <view class="top-name">{{ item.shop_name }} </view>
          <view class="score-and-distance">
           <view class="score">
              <!-- <text class="iconfont" v-for="star in item.average" :key="star.id"
                >&#xe624;</text
              > -->

              	<uni-rate :max="5" :value="item.average" size="17" readonly="true" color="#B3B3B3" allowHalf='true' margin="4"  activeColor="#FF5112"  />
              <view class="five-stars"> {{ item.average }}分 </view>
            </view>
            <view class="distance"
              >{{ item.area_name }}
              <text v-if="item.distance > 1000"
                >{{ (item.distance / 1000).toFixed(1) }}KM</text
              >
              <text v-else>{{ item.distance.toFixed(1) }}m</text>
            </view>
          </view>
        </view>
       <view class="middle">
          <view
            class="middle-item"
            v-for="good in item.list"
            :key="good.id"
            @click="goProductDetails(good.id)"
          >
            <view class="img">
              <image :src="good.cover" mode="aspectFill"></image>
            </view>
            <view class="introduce">
              <view class="name"> {{ good.title }} </view>
              <view class="title">
                
                <view class="title-item"> 消费{{ good.result_sale_num }} </view>
              </view>
              <view class="bottom">
                <view class="large">
                  <rich-text
                    :nodes="$mUtil.priceBigSmall(good.sale_price)"
                  ></rich-text
                ></view>
                <view class="small"> ¥ {{ good.market_price }} </view>
              </view>
            </view>
          </view>
        </view>
       <view class="see-more" v-if="item.service_goods_total > 2" @click="goShop(item.shop_id)">
          查看其他{{ item.service_goods_total - 2 }}个商品
          <text class="iconfont">&#xe645;</text>
        </view>
      </view>
    </view>
    <nodata v-else :config="{ top: 1, content: '暂无数据~' }"></nodata>
  </view>
</template>

<script>
import permision from "@/js_sdk/wa-permission/permission.js";
export default {
  data() {
    return {
      cates: [],
      config: {
        back: true, //false是tolbar页面 是则不写
        title: "店铺",
        color: "#1A1A1A",
        //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
        backgroundColor: [1, "#ffffff"],
        
        search: {
          value: "",
          placeholder: "",
          disabled: false,
        },
        leftSlot: true,
      },
      city: '',
      newProvinceDataList: [[], [], []],
      multiIndex: [0, 0, 0],
      oldpProvinceDataList: [],
      params: {},
      shops: [],
	  activeIndex:null
    };
  },
  method(){

  },
  onShow() {

    this.getCate();

    this.getLocalAddress();
  },
   onPullDownRefresh() {
  
 
    this.getShop();
    uni.stopPullDownRefresh();
  },
  methods: {
    async requestAndroidPermission(permisionID) {
    var result = await permision.requestAndroidPermission(permisionID)
    var strStatus
    if (result == 1) {
        uni.getLocation({
            type: "gcj02",
            geocode: true,
            success: (res) => {
              this.city = res.address.city;
              this.params.city = this.city;
              this.params.lon = res.longitude;

              this.params.lat = res.latitude;
              this.setStorage(
                res.address.city,
                res.longitude,
                res.latitude
              );
              this.$http
                .get(
                  "/cnarea/get-address/" + res.latitude + "," + res.longitude
                )
                .then((res) => {
                  console.log(res + JSON.stringify(res));
                  if (res && res.code == 200) {
                  }
                });

              this.getShop();

              console.log("当前位置的经度：" + res.longitude);
              console.log("当前位置的纬度：" + res.latitude);
              console.log(
                "res" + res.address.city,
               
                JSON.stringify(res.address)
              );
            },
          });
    } else if (result == 0) {
        strStatus = "未获得授权"
    } else {
        strStatus = "被永久拒绝权限"
    }
    // uni.showModal({
    //     content:"定位" + strStatus,
    //     showCancel: false
    // });
     this.$mUtil.toast(strStatus);
},
	// 小程序获取位置
	wxGetLocal() {
		uni.getLocation({
		    type: "gcj02",
		    geocode: true,
		    success: (res) => {
				console.log(res)
				this.$http
				  .get(
				    "/cnarea/get-address/" + res.latitude + "," + res.longitude
				  )
				  .then((res2) => {
				    console.log(res + JSON.stringify(res));
				    if (res2 && res2.code == 200) {
						this.params.city = res2.date.address_component.city;
						this.params.lon = res.longitude;
						this.params.lat = res.latitude;
						this.city = res2.date.address_component.city
						this.setStorage(
						  res2.date.address_component.city,
						  res.longitude,
						  res.latitude
						);
						this.getShop();
				    }
				  });
		//       this.city = res.address.city;
		//       this.params.city = this.city;
		//       this.params.lon = res.longitude;
		
		//       this.params.lat = res.latitude;
		//       this.setStorage(
		//         res.address.city,
		//         res.longitude,
		//         res.latitude
		//       );
		//       this.$http
		//         .get(
		//           "/cnarea/get-address/" + res.latitude + "," + res.longitude
		//         )
		//         .then((res) => {
		//           console.log(res + JSON.stringify(res));
		//           if (res && res.code == 200) {
		//           }
		//         });
		
		//       this.getShop();
		
		      // console.log("当前位置的经度：" + res.longitude);
		      // console.log("当前位置的纬度：" + res.latitude);
		      // console.log(
		      //   "res" + res.address.city,
		       
		      //   JSON.stringify(res.address)
		      // );
		    },
		  });
	},
    goProductDetails(id) {
      uni.navigateTo({
        url: "/pages/product/goods/serviceGood?id=" + id,
      });
    },
    goShop(shopid) {
		console.log('dsddsdssds454545454554')
		// uni.navigateTo({
		// 	url: "/pages/user/merchant/registerAndAudit",
		// });
      uni.navigateTo({
        url: "/pages/research/homepage/shopHomepage?shopId=" + shopid,
		fail(err) {
			console.log(err)
		}
      });
    },
    searchBlur(e) {
      if (e.value == "") {
        delete this.params.title;
      }
      this.getShop();
    },
    searchConfirm(e) {
      // if (e.value) {
        
      // }
	  if (e.value.length > 50) {
	    this.$mUtil.toast("搜索最多50个字符");
	    return false;
	  }
	  this.params.title = e.value;
	  
	  if (e.value == "") {
	    delete this.params.title;
	  }
	  this.getShop();
    },
    /**获取数据 */
    getShop() {
      console.log("数据 " + JSON.stringify(this.params));
      this.$http.get("/service/goods/nearby", this.params).then((res) => {
        if (res && res.code == 200) {
          this.shops = res.list;
        }
      });
    },
    /**得到分类 */
    getCate() {
      this.$http.get("/classify/all").then((res) => {
        if (res && res.code == 200) {
          this.cates = res.list;
        }
      });
    },
    /**获取当前位置 */
    getLocalAddress() {
       
      this.$http.get("/cnarea/tree-lbs/city").then(async (res) => {
        let provincesList = res.tree.children;
        for (let i = 0; i < provincesList.length; i++) {
          this.newProvinceDataList[0].push(provincesList[i]);
        }

        this.oldpProvinceDataList = provincesList;
      });

      if (uni.getStorageSync("localAddress")) {
        let local = JSON.parse(uni.getStorageSync("localAddress"));
        this.city = local.city;
        this.params.city = this.city;
        this.params.lon = local.lon;

        this.params.lat = local.lat;
        this.getShop();
      } else {
				console.log(1)
    // this.requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION")
      this.wxGetLocal()
         
     
      }
    },
    /**点击分类切换数据 */
    changeCateId(item,index) {
      if(index==this.activeIndex){
this.activeIndex=null
delete this.params.category_id
      }else{
this.activeIndex=index
      this.params.category_id = item.id;
       let local = JSON.parse(uni.getStorageSync("localAddress"));
     
        this.params.city = local.city;
        this.params.lon = local.lon;

        this.params.lat = local.lat;
      }
		
      this.getShop();
    },
    /**缓存城市code  */
    setStorage(city, lon, lat) {
      uni.setStorageSync(
        "localAddress",
        JSON.stringify({ city: city, lon: lon, lat: lat })
      );
    },
    // 省市区确认事件
    pickerChange(e) {
      this.multiIndex = e.detail.value;
   
      if (this.newProvinceDataList[1].length > 0) {
        // this.params.lat = this.newProvinceDataList[1][
        //       this.multiIndex[1]
        //     ].latitude;
        //     this.params.lon = this.newProvinceDataList[1][
        //       this.multiIndex[1]
        //     ].longitude;
        this.city = this.newProvinceDataList[1][this.multiIndex[1]].label;
        this.params.city = this.city;
      } else {
        // this.params.lat = this.newProvinceDataList[0][
        //   this.multiIndex[0]
        // ].latitude;
        // this.params.lon = this.newProvinceDataList[0][
        //   this.multiIndex[0]
        // ].longitude;
        this.city = this.newProvinceDataList[0][this.multiIndex[0]].label;
        this.params.city = this.city;
      }

      this.setStorage(
        this.city,

        this.params.lon,
        this.params.lat
      );
      this.getShop();
    },
    pickerColumnchange(e) {
      // 第几列滑动
      // console.log(e.detail.column);
      // 第几列滑动的下标
      // console.log(e.detail.value)
      // 第一列滑动

      if (e.detail.column === 0) {
        this.multiIndex = [0, 0, 0];
        this.multiIndex[0] = e.detail.value;
        this.newProvinceDataList[1] = this.oldpProvinceDataList[
          this.multiIndex[0]
        ].children.map((item, index) => {
          return item;
        });
        //当三级存在
        if (
          this.oldpProvinceDataList[this.multiIndex[0]].children.length > 0 &&
          this.oldpProvinceDataList[this.multiIndex[0]].children[0].children
        ) {
          if (
            this.oldpProvinceDataList[this.multiIndex[0]].children[
              this.multiIndex[1]
            ]
          ) {
            this.newProvinceDataList[2] = this.oldpProvinceDataList[
              this.multiIndex[0]
            ].children[this.multiIndex[1]].children.map((item, index) => {
              return item;
            });
          }
        } else {
          this.newProvinceDataList[2] = [];
        }
        // 第一列滑动  第二列 和第三列 都变为第一个
        // this.multiIndex.splice(1, 1, 0);
        // this.multiIndex.splice(2, 1, 0);
      }
      // 第二列滑动
      if (e.detail.column === 1) {
        this.multiIndex[1] = e.detail.value;
        if (
          this.oldpProvinceDataList[this.multiIndex[0]].children[0].children
        ) {
          this.newProvinceDataList[2] = this.oldpProvinceDataList[
            this.multiIndex[0]
          ].children[this.multiIndex[1]].children.map((item, index) => {
            return item;
          });
        } else {
          this.newProvinceDataList[2] = [];
        }
        // 第二列 滑动 第三列 变成第一个
        this.multiIndex.splice(2, 1, 0);
      }
      // 第三列滑动
      if (e.detail.column === 2) {
        this.multiIndex[2] = e.detail.value;
      }
    },
  },
};
</script>
<style>

	</style>


<style lang="scss" scoped>
	/deep/.hx-navbar__content__main_search_hxicon {
		span {
			font-size: 30rpx;
		}
	}
	
	/deep/.uni-input-placeholder {
		background-color: #fafafa;
		color: #b3b3b3 !important;
		font-size: 22rpx;
	}
	
	
	/deep/.hx-navbar__content__main_search_input {
		background-color: #fafafa;
		font-size: 30rpx;
	}
	.down {
		font-size: 25rpx;
		margin-left: 10rpx;
	}
.content {
  padding: 40rpx 30rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  .item {
    background-color: #ffffff;
    margin-bottom: 30rpx;
    border-radius: 26rpx;
    .item-top {
      border-bottom: 1rpx solid #e6e6e6;
      padding: 44rpx 22rpx 30rpx 22rpx;
      padding-bottom: 40rpx;
      .top-name {
        font-size: 32rpx;
        font-weight: 700;
        color: #333333;
      }
      .score-and-distance {
        display: flex;
        justify-content: space-between;
        margin-top: 13rpx;
        .score {
          display: flex;
          align-items: center;
          .iconfont {
            color: #ff4e15;
            padding-right: 10rpx;
          }
          .five-stars {
            font-size: 28rpx;
            color: #ff4e15;
            font-weight: 500;
            margin-left: 6rpx;
          }
        }
        .distance {
          font-size: 24rpx;
          color: #666666;
          font-weight: 500;
          margin-right: 24rpx;
        }
      }
    }

    .see-more {
      color: #999999;
      font-size: 22rpx;
      font-weight: 400;
      text-align: center;
      padding-bottom: 45rpx;
      margin-top: 30rpx;
    }
    .middle {
      padding: 0rpx 30rpx 0rpx 22rpx;
      .middle-item {
        padding: 40rpx 0 30rpx 0;
        display: flex;
        border-bottom: 1rpx solid #e6e6e6;
        padding-bottom: 30rpx;
        .img {
          border-radius: 14rpx;
          overflow: hidden;
		
          image {
            width: 214rpx;
            height: 144rpx;
          }
        }
        .introduce {
			flex: 1;
			
          margin-left: 16rpx;
          .name {
			  
            font-size: 26rpx;
            color: #333333;
			width: 400rpx;
            font-weight: 500;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
            margin-bottom: 6rpx;
          }
          .title {
            display: flex;
            .title-item {
              color: #a27714;
              font-size: 22rpx;
              font-weight: 400;
              margin-right: 16rpx;
              background-color: #dac6a1;
              padding: 1rpx 6rpx;
              border-radius: 16rpx 16rpx 16rpx 0;
            }
          }
          .bottom {
            display: flex;
            align-items: flex-end;
            margin-top: 26rpx;
            .large {
              font-size: 36rpx;
              color: #ff0000;
              font-weight: Bold;
              text {
                margin-left: 16rpx;
                font-size: 36rpx;
              }
            }
            .small {
              font-size: 22rpx;
              font-weight: 500;
              color: #cccccc;
              text-decoration: line-through;
              margin-left: 16rpx;
            }
          }
        }
      }
    }
  }
}
.top {
  display: flex;
  overflow: scroll;
  white-space: nowrap;
  .item {
    padding: 30rpx   0rpx;
    margin:  0 30rpx;
    font-size: 28rpx;
    color: #999999;
    font-weight: 500;
  }
  .active{
	  color:  #0B844A;
    font-weight: 600;
        border-bottom: 4rpx solid #0B844A;
  }
}
.map {
  font-size: 36rpx;
  color: #1a1a1a;
  font-weight: 500;
  text {
  }
}
</style>
