<template>
	<zj-page-layout :hasFooter="true">
		<view class="all-container">
			<view class="address-container card" @tap="chooseAddress">
				<view class="main">
					<view class="left">
						<view class="icon"><text class="iconfont icon-dingwei1"></text></view>
						<view class="nodata" v-if="!addressInfo">选择联系人地址</view>
						<view class="hasdata" v-else>
							<view class="name">{{addressInfo.name}}<text>{{addressInfo.phone}}</text></view>
							<view class="address ellipsis-2">
								{{addressInfo.province}}{{addressInfo.city}}{{addressInfo.area}}{{addressInfo.street}}{{addressInfo.address}}{{addressInfo.houseNo}}
							</view>
						</view>
					</view>
					<text class="right iconfont icon-jinru"></text>
				</view>
			</view>

			<view class="card goods">
				<view class="common-title">商品信息</view>
				<view class="item">
					<image :src="detail.categoryUrl" mode="aspectFill"></image>
					<view class="right">
						<view class="name">{{detail.name}}</view>
						<view class="name remark">{{detail.repairRemark}}</view>
						<view class="qty">
							<u-number-box v-model="qty" @change="valChange"></u-number-box>
						</view>
					</view>
				</view>
			</view>

			<view class="card">
				<view class="title flex_asb">
					<view class="common-title" style="margin-bottom: 0;"><text>*</text>支付方式</view>
					<u-radio-group v-model="payType" placement="row" style="justify-content: flex-end;">
						<u-radio label="在线支付" name="WECHAT"></u-radio>
					</u-radio-group>
				</view>
			</view>

			<view class="card service-container">
				<view class="item">
				  <view class="label">租赁订金金额</view>
				  <view class="value">￥{{detail.depositPrice*100 * qty/100}}</view>
				</view>
				<view class="item">
				  <view class="label"><text>*</text>租赁开始日期</view>
				  <view class="picker" @tap="isShowDate = true">
				    <text class="value" v-if="startDate">{{startDate}}</text>
				    <text class="placeholder" v-else>请选择</text>
				    <text class="iconfont icon-jinru"></text>
				  </view>
				</view>
				<view class="item">
				  <view class="label"><text>*</text>租赁结束日期</view>
				  <view class="picker" @tap="isShowDate = true">
				    <text class="value" v-if="endDate">{{endDate}}</text>
				    <text class="placeholder" v-else>请选择</text>
				    <text class="iconfont icon-jinru"></text>
				  </view>
				</view>
				<view class="common-title">备注</view>
				<u--textarea v-model="remark" placeholder="请输入内容" border="none" height="120"></u--textarea>
			</view>
		</view>

    <template slot="footer">
      <view class="footer">
      	<view class="tip">实际费用以具体租赁期限为准，不包括安装及辅材费用</view>
      	<view class="flex_asb footer_c">
      		<view class="left flex_asb">
      			<text style="color: #666666;font-size: 28rpx;">订金</text>
      			<text style="color: #ff5300;">￥{{detail.depositPrice*100 * qty/100}}</text>
      		</view>
      		<u-button text="提交订单" shape="circle" color="#428dff" type="primary" @click="submitData"></u-button>
      	</view>
      </view>
    </template>

		<zjDialogDateRangePicker v-model="isShowDate" :canBefore="false" @cancel="cancelDate" @confirm="confirmDate"></zjDialogDateRangePicker>

	</zj-page-layout>
</template>

<script>
	import { weixinPay, mini_env } from '@/common/utils/util.js';
	import zjDialogDateRangePicker from '@/components/zj-dialog/zj-dialog-dateRangePicker.vue';
	export default {
		components: {
			zjDialogDateRangePicker
		},
		data() {
			return {
				detail: {},
				addressInfo: null,
				isShowDate: false,
				is_confirm: true,
				userInfo: {},
				startDate: '',
				endDate: '',
				qty: 1,
				payType: 'WECHAT',
				remark: '',
			}
		},

		computed: {

		},

		async onLoad({id}) {
			this.id = id
			this.getDetail(id)
			// 进入页面先获取默认地址
			await this.getAddress();
			// 接收地址信息
			this.crossPage.$on('chooseAddress', result => {
				this.addressInfo = result;
			})
			this.crossPage.$on('confirm', result => {
				this.startDate = result[0]
				this.endDate = result[1]
				this.isShowDate = false
			})
		},

		onUnload() {
			this.crossPage.$off('chooseAddress');
		},

		methods: {
			// 获取品牌列表
			getDetail(id) {
				this.$api.post('/goods/lease/detail',{
					id
				}).then(res => {
					this.detail = res.data;
				})
			},

			cancelDate(){
				this.isShowDate = false
			},

      confirmDate(item) {
        let [start, end] = item;
        if (start == '' || end == '') {
        	this.startDate = '';
        	this.endDate = '';
        	return;
        }
        this.startDate = start;
        this.endDate = end;
      },

			// 去选择地址
			chooseAddress() {
				this.$navToPage({
					url: '/packageMine/pages/address/list?isChoose=' + true
				})
			},
			findElem(array, attr, val) {
			  for (var i = 0; i < array.length; i++) {
			    if (array[i][attr] == val) {
			      return i; //返回当前索引值
			    }
			  }
			  return -1;
			},
			// 获取地址信息
			async getAddress() {
			  return new Promise((resolve, reject) => {
			    this.$api.get('/user/address/list', {
			      pageNum: 1,
			      pageSize: 100,
			      userId: this.$store.state.user.userId
			    }).then(res => {
			      let hasDefault = this.findElem(res.data.records, 'defaultAddr', true);
			      if (hasDefault >= 0) {
			        this.hasAddress = true;
			        this.addressInfo = res.data.records[hasDefault];
			      } else {
			        this.hasAddress = false;
			      }
			      resolve();
			    })
			  })
			},
			
			submitData() {
				if (!this.addressInfo) return this.$toast('请选择收货地址');
				if (!this.startDate) return this.$toast('请选择租赁日期');
				if (!this.is_confirm) { return this.$toast('请勿频繁点击！') }
				this.is_confirm = false
				setTimeout(() => {
				  this.is_confirm = true
				}, 3000)
				this.$api.postJson('/lease/order/add', {
					payType: this.payType,
					userAddressId: this.addressInfo.userAddressId,
					items: [{
						goodsLeaseId: this.id,
						qty: this.qty,
						startDate: this.startDate + ' 00:00:00',
						endDate: this.endDate + ' 00:00:00'
					}],
					remark: this.remark,
				}).then(res => {
					this.$successToast();
					if(res.code == 200){
						this.workerPay(res.data)
					}
				})
			},

			//代客支付
			workerPay(id) {
				const that = this
			  mini_env((bool) => {
			    this.$api.post('/lease/order/pay', {
			      id,
			      ...(() => {
			        if (bool) {
			          return {
			            miniPay: true,
			            openId: this.$store.state.user.miniOpenId
			          }
			        }
			        return {}
			      })()
			    }).then((res) => {
			      if (!res.data) return false;
				  //定金为0元时
				  if(!res.data.isPay){
					  that.$successToast('提交成功');
						setTimeout(() => {
						  that.$navToPage({
						  	url: `/packageWorkorder/pages/tenancyOrderList`
						  }, 'redirectTo')
						}, 1000)
						return false
				  }
			      if (bool) {
			        uniWebview.navigateTo({
			          url: `/pages/pay/zhupin?${Object.entries({
			            ...res.data,
			            payPackage: res.data.payPackage.split("=")[0] || "",
			            payPackageVal: res.data.payPackage.split("=")[1] || ""
			          }).map(item => item.join("=")).join("&")}`
			        })
			      } else {
			        weixinPay(res.data, function (res) {
			          that.$successToast('支付成功');
					  setTimeout(() => {
					    that.$navToPage({
					    	url: `/packageWorkorder/pages/tenancyOrderList`
					    }, 'redirectTo')
					  }, 1000)
			        })
			      }
			    })
			  })
			},
		},
	}
</script>

<style lang="scss" scoped>
	.all-container{
    padding: 0 20rpx 20rpx;
		box-sizing: border-box;
	}
	.card {
		@include zj-card;
		margin-top: 20rpx;
		padding: 30rpx;
	}

	.flex{
		display: flex;
	}

	.flex_asb{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.common-title {
		font-size: 32rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
		text {
			color: $error-color;
			font-weight: normal;
		}
	}

	.service-container {
	  .item {
	    display: flex;
	    align-items: center;
	    justify-content: space-between;
	    height: 50rpx;
	    margin-bottom: 30rpx;
	    .label {
	      margin-right: 30rpx;
	      text {
	        color: $error-color;
	      }
	    }
	    .picker {
	      .placeholder {
	        color: $sec-font;
	      }
	      .iconfont {
	        margin-left: 12rpx;
	        color: $sec-font;
	      }
	    }
	  }
	}

	.address-container {
		.main {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 30rpx;
		}

		.right {
			font-size: 32rpx;
			color: $sec-font;
			flex-shrink: 0;
		}

		.left {
			display: flex;
			align-items: center;
			margin-right: 20rpx;

			.icon {
				width: 52rpx;
				height: 52rpx;
				border-radius: 50%;
				background: $theme-color;
				display: flex;
				flex-shrink: 0;
				justify-content: center;
				align-items: center;
				margin-right: 20rpx;

				.iconfont {
					font-size: 36rpx;
					color: #ffffff;
				}
			}

			.nodata {
				font-size: 28rpx;
				color: #999999;
			}

			.hasdata {
				.name {
					font-size: 32rpx;
					color: #333333;

					text {
						color: #999999;
						font-size: 28rpx;
						margin-left: 16rpx;
					}
				}

				.address {
					font-size: 28rpx;
					color: #666666;
					line-height: 34rpx;
					margin-top: 10rpx;
				}
			}
		}
	}
	.goods{
		.item{
			display: flex;
			align-items: center;
			box-sizing: border-box;
			image {
				width: 140rpx;
				height: 140rpx;
				margin-right: 20rpx;
			}
			.right{
				flex: 1;
				.name{
					font-weight: bold;
					color: #000000;
					font-size: 32rpx;
					line-height: 40rpx;
					margin-bottom: 20rpx;
				}
				.remark{
					font-size: 26rpx;
					color: #59a7ff;
				}
				.qty{
					display: flex;
					justify-content: flex-end;
				}
			}
		}
	}
	.footer{
		width: 100%;
		background-color: #ffffff;
		box-sizing: border-box;
		.tip{
			background-color: #fffdef;
			color: #ff5300;
			font-size: 28rpx;
			padding: 20rpx;
		}
    .footer_c {
      padding: 20rpx;
    }
		.left{
			width: 260rpx;
			margin-right: 60rpx;
		}
	}
</style>
