<template>
  <view class="address-management" ref="container" >
		<!-- :class="addressList.length < 1 && page > 1 ? 'on' : ''" -->
    <!-- <view class="line" v-if="addressList.length > 0">
      <image :src="`${$VUE_APP_RESOURCES_URL}/images/line.jpg`" />
    </view> -->
		<view class="header" :style="'height: ' + CustomBar + 'px'">
			<view class="top-nav-box acea-row row-between-wrapper" :style="'width:' + CustomBarLeft + 'px;padding-top:' + StatusBar + 'px;height:' + CustomBar + 'px'">
				<image @click="back" class="backImg" src="@/static/images/back-btn.png" mode=""></image>
				<view class="tab-title">地址管理</view>
				<image class="addAddress" src="@/static/images/add-addr.png"  @click="addAddress" v-if="addressList.length"></image>
			</view>
		</view>
		<view :style="[{height:CustomBar + 'px'}]"></view>
		
		<view class="" style="padding-top: 10rpx;">
			<view class="item" v-for="(item, addressListIndex) in addressList" :key="addressListIndex" :data-index="addressListIndex" @touchstart="drawStart" @touchmove="drawMove" @touchend="drawEnd" :style="{ right: item.right + 'rpx' || '0rpx' }">
				<view class="info-box acea-row row-between-wrapper">
					<view class="">
						<view class="">{{ item.province }}{{ item.city }}{{ item.district}}</view>
						<view class="detail">{{ item.detail }}</view>
						<view class="user-info acea-row row-middle">
							<view class="">{{ item.realName }}</view>
							<view class="phone">{{ item.phone }}</view>
							<view v-if="item.isDefault == 1" class="default-tip">默认</view>
						</view>
					</view>
					<image class="edit" src="../../../../static/images/edit-icon.png" @click.stop="editAddress(addressListIndex)" mode=""></image>
				</view>
				<view class="btn-box acea-row" :style="item.right?'right: -428rpx;':''">
					<view class="default-btn" @click="radioChange(item.id)">{{item.isDefault != 1?'设为':'取消'}}默认</view>
					<view class="del-btn">删除</view>
				</view>
				
				<!-- <view class="address">
					<view class="consignee">
						收货人：{{ item.realName }}
						<text class="phone">{{ item.phone }}</text>
					</view>
					<view>
						收货地址：{{ item.province }}{{ item.city }}{{ item.district
						}}{{ item.detail }}
					</view>
				</view>
				<view class="operation acea-row row-between-wrapper">
					<view class="select-btn">
						<view class="checkbox-wrapper">
							<checkbox-group @change="radioChange(item.id)">
								<label class="well-check">
									<checkbox :value="item.isDefault==1?'checked':''" :checked="item.isDefault||item.isDefault=='1' ? true : false"></checkbox>
									<text class="default">设为默认</text>
								</label>
							</checkbox-group>
						</view>
					</view>
					<view class="acea-row row-middle">
						<view @click="editAddress(addressListIndex)">
							<text class="iconfont icon-bianji"></text>编辑
						</view>
						<view @click="delAddress(addressListIndex)">
							<text class="iconfont icon-shanchu"></text>删除
						</view>
					</view>
				</view> -->
			</view>
		</view>
    
    <Loading :loaded="loadend" :loading="loading"></Loading>
    <view class="no-address" v-if="addressList.length < 1 && page > 1">
    <!-- <view class="noCommodity"> -->
      <view class="no-address">
				<image class="image" src="../../../../static/images/no-address.png" mode="widthFix"></image>
				<view class="">等我们也造火箭或许能寄到火星</view>
				<view class="tip">赶快添加收货地址吧</view>
				<view class="add-icon" @click="addAddress">＋</view>
        <!-- <image :src="`${$VUE_APP_RESOURCES_URL}/images/noAddress.png`" class="image" /> -->
      </view>
    </view>
		
    <!-- <view style="height:100rpx;"></view> -->
    <!-- <view class="footer acea-row row-between-wrapper">
      <view class="addressBnt bg-color-red" v-if="isWechat" @click="addAddress">
        <text class="iconfont icon-tianjiadizhi"></text>添加新地址
      </view>
      <view class="addressBnt on bg-color-red" v-else @click="addAddress">
        <text class="iconfont icon-tianjiadizhi"></text>添加新地址
      </view>
      <view class="addressBnt wxbnt" v-if="isWechat" @click="getAddress">
      <text class="iconfont icon-weixin2"></text>导入微信地址
      </view>
    </view> -->
  </view>
</template>
<script type="text/babel">
import {
  getAddressList,
  getAddressRemove,
  getAddressDefaultSet,
  postAddress
} from "@/api/user";
import Loading from "@/components/Loading";
import { isWeixin } from "@/utils";
// import { openAddress } from "@/libs/wechat";

export default {
  components: {
    Loading
  },
  data() {
    return {
			StatusBar: this.StatusBar,
			CustomBar: this.CustomBar,
			CustomBarLeft: this.CustomBarLeft,
			// addBottom: this.addBottom,
      page: 1,
      limit: 20,
      addressList: [],
      loadTitle: "",
      loading: false,
      loadend: false,
      isWechat: isWeixin(),
			right : 0,
			delBtnWidth: 462,
			startX : 0
    };
  },
  mounted: function() {
    this.AddressList();
  },
  onReachBottom() {
    !this.loading && this.AddressList();
  },
  onShow: function() {
    this.refresh();
  },
	watch:{
	},
  methods: {
		back() {
			uni.navigateBack({
				delta: 1,
				fail: (err) => {
					uni.switchTab({
						url: '/pages/home/index',
					})
				}
			})
		},
		drawStart(e) {
				var touch = e.touches[0];
				console.log(touch, "drawStart")
				for (var index in this.addressList) {
						this.addressList[index].right = 0;
				}
				this.startX = touch.clientX;
		},
		drawMove(e) {
				let touch = e.touches[0];
				let index = e.currentTarget.dataset.index;
				let disX = this.startX - touch.clientX;
				if (disX >= 20) {
						if (disX > this.delBtnWidth) {
								disX = this.delBtnWidth;
						}
						this.addressList[index].right = disX;
				} else {
						this.addressList[index].right = 0;
				}
				// console.log(index, this.addressList[index].right, "drawMove")
		},
		drawEnd(e) {
				let index = e.currentTarget.dataset.index;
				console.log(index, this.addressList[e.currentTarget.dataset.index].right, "drawMove")
				let item = this.addressList[index];
				if (item.right >= 120) {
						this.addressList[index].right = this.delBtnWidth;
				} else {
						this.addressList[index].right = 0;
				}
		},
    refresh: function() {
      this.addressList = [];
      this.page = 1;
      this.loadend = false;
      this.AddressList();
    },
    /**
     * 获取地址列表
     *
     */
    AddressList: function() {
      let that = this;
      if (that.loading) return; //阻止下次请求（false可以进行请求）；
      if (that.loadend) return; //阻止结束当前请求（false可以进行请求）；
      that.loading = true;
      getAddressList({ page: that.page, limit: that.limit }).then(res => {
        that.loading = false;
				var arr = [];
				for(var i in res.data){
					res.data[i].right = 0;
					arr.push(res.data[i])
				};
        //apply();js将一个数组插入另一个数组;
        that.addressList.push.apply(that.addressList, arr);
        that.loadend = res.data.length < that.limit; //判断所有数据是否加载完成；
        that.page = that.page + 1;
      });
    },
    /**
     * 编辑地址
     */
    editAddress: function(index) {
      this.$yrouter.push({
        path: "/pages/user/address/AddAddress/index",
        query: { id: this.addressList[index].id }
      });
    },
    /**
     * 删除地址
     */
    delAddress: function(index) {
      let that = this;
      let address = this.addressList[index];
      let id = address.id;
      getAddressRemove(id).then(function() {
        uni.showToast({
          title: "删除成功!",
          icon:"success",
          duration: 2000,
          complete: () => {
            that.addressList.splice(index, 1);
            that.$set(that, "addressList", that.addressList);
          }
        });
      });
    },
    /**
     * 设置默认地址
     */
    radioChange: function(id) {
      getAddressDefaultSet(id).then(res => {
        this.refresh();
        uni.showToast({ title: res.msg, icon: "none", duration: 2000 });
      });
    },
    /**
     * 新增地址
     */
    addAddress: function() {
      this.$yrouter.push({
        path: "/pages/user/address/AddAddress/index"
      });
    },
    // getAddress() {
    //   openAddress().then(userInfo => {
    //     uni.showLoading({ title: "加载中" });
    //     postAddress({
    //       real_name: userInfo.userName,
    //       phone: userInfo.telNumber,
    //       address: {
    //         province: userInfo.provinceName,
    //         city: userInfo.cityName,
    //         district: userInfo.countryName
    //       },
    //       detail: userInfo.detailInfo,
    //       post_code: userInfo.postalCode,
    //       wx_export: 1
    //     })
    //       .then(() => {
    //         this.page = 1;
    //         this.loading = false;
    //         this.loadend = false;
    //         this.addressList = [];
    //         this.AddressList();
    //         uni.hideLoading();
    //   uni.showToast({
    //   											title: "添加成功",
    //   											icon: 'success',
    //   											duration: 2000
    //   										});
    //       })
    //       .catch(err => {
    //         uni.hideLoading();
    //   uni.showToast({
    //   	title: err.msg || err.response.data.msg|| err.response.data.message,
    //   	icon: 'none',
    //   	duration: 2000
    //   });
    //       });
    //   });
    // }
  }
};
</script>
<style lang="less" scoped>
	// .address-management.on {
	//   background-color: #fff;
	//   height: 100vh;
	// }
	// .address-management {
	// 	width: 100%;
	// 	padding-top: 20rpx;
	// }
	
	.header {
		position: fixed;
		left: 0;
		top: 0;
		z-index: 100;
		background: #F1F1F1;
		width: 750rpx;
		.backImg {
			height: 62rpx;
			width: 62rpx;
			margin-left: 26rpx;
		}
		.tab-title {
			font-size: 32rpx;
			font-family: PingFang SC;
			font-weight: 600;
			color: #2DB5AE;
			line-height: 42rpx;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
		}
		.addAddress {
			height: 62rpx;
			width: 62rpx;
			margin-right: 14rpx;
		}
	}
	
	.info-box {
		width: 686rpx;
		height: 156rpx;
		background: #F5F6F8;
		box-shadow: 0rpx 10rpx 16rpx 0rpx rgba(0, 0, 0, 0.06);
		border-radius: 16rpx;
		padding: 24rpx;
		font-size: 20rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #3A3A3C;
		line-height: 26rpx;
		.detail {
			font-size: 26rpx;
			font-weight: 600;
			line-height: 38rpx;
			padding: 6rpx 0rpx;
		}
		.user-info {
			font-size: 24rpx;
			line-height: 32rpx;
			.phone {
				padding-left: 20rpx;
				padding-right: 24rpx;
			}
			.default-tip {
				width: 58rpx;
				height: 26rpx;
				border-radius: 16rpx;
				border: 2rpx solid #2EB5AE;
				font-size: 18rpx;
				color: #2DB5AE;
				line-height: 22rpx;
				text-align: center;
			}
		}
		.edit {
			width: 46rpx;
			height: 46rpx;
		}
	}
	.btn-box {
		position: absolute;
		top: 0;
		right: -472rpx;
		font-size: 26rpx;
		font-family: PingFang SC;
		font-weight: 600;
		color: #FFFFFF;
		line-height: 156rpx;
		text-shadow: 0rpx 10rpx 16rpx rgba(0,0,0,0.15);
		text-align: center;
		.default-btn {
			width: 308rpx;
			height: 156rpx;
			background: #2DB5AE;
			box-shadow: 0rpx 10rpx 16rpx 0rpx rgba(0, 0, 0, 0.06);
			border-radius: 16rpx;
		}
		.del-btn {
			width: 154rpx;
			height: 156rpx;
			background: #EC3A5B;
			box-shadow: 0rpx 10rpx 16rpx 0rpx rgba(0, 0, 0, 0.06);
			border-radius: 16rpx;
		}
	}
	
	.no-address {
		padding-top: 168rpx;
		font-size: 34rpx;
		font-weight: 600;
		color: #3A3A3C;
		line-height: 48rpx;
		text-align: center;
		.image {
			width: 430rpx;
			margin: 0rpx auto 74rpx;
		}
		.tip {
			font-size: 13px;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #3A3A3C;
			line-height: 19px;
			margin-bottom: 76rpx;
		}
		.add-icon {
			width: 108rpx;
			height: 108rpx;
			border: 4rpx solid #2DB5AE;
			border-radius: 50%;
			margin: 0rpx auto;
			font-size: 64rpx;
			color: #2DB5AE;
			line-height: 100rpx;
			text-align: center;
			font-weight: 400;
		}
	}
	
</style>
