<template>
	<view :style="colorStyle">
		<form @submit="formSubmit">
			<view class='addAddress'>
				<view class='list'>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>主标题</view>
						<input type='text' placeholder='请填写主标题' name='mainTitle' :value="grouponReqData.mainTitle"
							placeholder-class='placeholder'></input>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>副标题</view>
						<input type='number' placeholder='请填写副标题' name="subTitle" :value='grouponReqData.subTitle'
							placeholder-class='placeholder' pattern="\d*" maxlength="11"></input>
					</view>
				</view>
				<view class="list" style="margin-top:50rpx;">
					<view class="title">
						团购商品
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>团购时间</view>
						<view @click="show1 = true">
							<input placeholder='请选择团购时间' name="phone" disabled :value='userAddress.date'
								placeholder-class='placeholder' maxlength="11"></input>
						</view>
						<u-datetime-picker @confirm="dateConfirm" :show="show1" v-model="value1" mode="datetimerange"></u-datetime-picker>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>提货时间</view>
						<view @click="show2 = true">
							<input placeholder='请选择提货时间' name="phone" disabled :value='userAddress.date2'
								placeholder-class='placeholder' maxlength="11"></input>
						</view>

						<u-datetime-picker @confirm="dateConfirmDate2()" :show="show2" v-model="value1"
							mode="datetimerange"></u-datetime-picker>
					</view>



					<view class='item acea-row row-between-wrapper'>
						<view class='name'>自提点</view>
						<view @click="openSelfTakeTable()">
							<input type='number' placeholder='请选择提自提点' name="phone" disabled :value='userAddress.ZTD'
								placeholder-class='placeholder' maxlength="11"></input>
						</view>
						<u-picker @confirm="dateConfirmZTD()" :show="showZTD" :columns="columns"></u-picker>
					</view>


				</view>

				<view class="list select-list" v-if="selectGoodList.length > 0">
					<view class="title">
						团购商品
					</view>
					<view class="list-item">
						<block v-for="(itemn, indexn) in selectGoodList" :key="indexn">
							<view hover-class='none' class='item acea-row-item row-column row-middle'>
								<view class='picture'>
									<image :src='itemn.logo' v-if="itemn.logo"></image>
									<image src="/static/images/sort-img.png" v-else></image>
								</view>
								<view class="p-r">
									<view class='name line1'>{{ $t(itemn.title) }}</view>
									<view class="acea-row-item-bArea">
										<view class='jiage line1'>￥48.00</view>
										<view @click="delItem(indexn)" :class="[itemn.selected ? 'selde' : 'noselde']">删除<text
												:class="[itemn.selected ? 'selde-q' : 'noselde-q']"></text></view>
									</view>
								</view>
							</view>
						</block>
					</view>
				</view>
				<button class="button_1 flex-col" @click="addGood">
					<text class="text_15">添加商品</text>
				</button>




				<button class='keepBnt' form-type="submit">保存并提交</button>
				<!-- #ifdef MP -->
				<!-- <view class="wechatAddress" v-if="!id" @click="getWxAddress">{{ $t(`导入微信地址`) }}</view> -->
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<view class="wechatAddress" v-if="this.$wechat.isWeixin() && !id" @click="getAddress">{{ $t(`导入微信地址`) }}
				</view>
				<!-- #endif -->
			</view>
		</form>
		<!-- #ifdef MP -->
		<!-- <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize> -->
		<!-- #endif -->
		<!-- #ifndef MP -->
		<home></home>
		<!-- #endif -->

		<u-popup :show="addGoodPopupShow" @close="close" @open="	">
			<view>
				<publish_good_list @getSelectData="getSelectData" v-if="addGoodPopupShow"></publish_good_list>
			</view>
		</u-popup>
	</view>
</template>

<script>
const city_res = require('@/mock/json/city_res.json')
import {publishGroupon, getAllSelfTake} from '@/api/groupon.js';
import {
	postUserAddressSave,
	postUserAddressUpdate,
	getUserAddressDetailById
} from '@/api/home.js';
import {
	editAddress,
	getAddressDetail
} from '@/api/user.js';
import {
	getCity
} from '@/api/api.js';
import {
	toLogin
} from '@/libs/login.js';
import {
	mapGetters
} from "vuex";

// #ifdef MP
import authorize from '@/components/Authorize';
// #endif
import home from '@/components/home';
import publish_good_list from '../publish_good_list/index.vue';
import colors from '@/mixins/color.js';
export default {
	components: {
		// #ifdef MP
		authorize,
		// #endif
		home,
		publish_good_list
	},
	mixins: [colors],
	data () {
		return {
			grouponReqData: {
				mainTitle: '',
				subTitle: '',
				grouponStartTime:'2023-06-09 00:00:00',
				grouponEndTime:'2023-06-11 00:00:00',
				takeStartTime:'2023-06-13 00:00:00',
				takeEndTime:'2023-06-16 00:00:00',
				selfTakeIds: ['1664554394738343938'],
				goodsIds: ['1666726817158090753']
			},
			grouponTimeRange: [],
			takeTimeRange: [],
			columns: [
				['中国', '美国', '日本']
			],
			array: [],
			show1: false,
			show2: false,
			showZTD: false,
			addGoodPopupShow: false,
			value1: Number(new Date()),
			regionDval: [this.$t(`浙江省`), this.$t(`杭州市`), this.$t(`滨江区`)],
			cartId: '', //购物车id
			pinkId: 0, //拼团id
			couponId: 0, //优惠券id
			id: 0, //地址id
			userAddress: {
				date: '',
				date2: '',
				userAddress: '',
				defaultState: true
			}, //地址详情
			region: [this.$t(`省`), this.$t(`市`), this.$t(`区`)],
			valueRegion: [0, 0, 0],
			isAuto: false, //没有授权的不会自动授权
			isShowAuth: false, //是否隐藏授权
			district: [],
			multiArray: [],
			multiIndex: [0, 0, 0],
			cityId: 0,
			defaultRegion: [this.$t(`广东省`), this.$t(`广州市`), this.$t(`番禺区`)],
			defaultRegionCode: '110101',
			news: '',
			noCoupon: 0,
			selectGoodList: [],
			selfTakeList: []
		};
	},
	computed: mapGetters(['isLogin']),
	watch: {
		isLogin: {
			handler: function (newV, oldV) {
				if (newV) {
					this.getUserAddress();
				}
			},
			deep: true
		}
	},
	onLoad (options) {
		if (this.isLogin) {
			this.cartId = options.cartId || '';
			this.pinkId = options.pinkId || 0;
			this.couponId = options.couponId || 0;
			this.id = options.id || 0;
			this.noCoupon = options.noCoupon || 0;
			this.news = options.new || '';
			uni.setNavigationBarTitle({
				title: options.id ? this.$t(`修改地址`) : this.$t(`添加地址`)
			})
			this.getUserAddress();
			this.getCityList();
		} else {
			toLogin();
		}
	},
	methods: {
		openSelfTakeTable() {
			this.showZTD = true;
			getAllSelfTake({
				current: 1,
				size: 20
			}).then(res => {
				this.selfTakeList = res.data.recoreds;
			})
		},
		delItem (index) {
			this.selectGoodList.splice(index, 1)
		},
		getSelectData (data) {
			this.selectGoodList = data
			console.log(this.selectGoodList);
		},
		open () {
			// console.log('open');
		},
		close () {
			this.addGoodPopupShow = false
			// console.log('close');
		},
		addGood () {
			this.addGoodPopupShow = true
		},
		bindPickerChange: function (e) {
			this.index = e.detail.value;
		},
		dateConfirm (value) {
			console.log('dateConfirm! ', value)
			this.userAddress.date = value.value
			this.show1 = false
		},
		dateConfirmDate2 (value) {
			this.userAddress.date2 = value.value
			this.show2 = false
		},
		dateConfirmZTD (value) {
			this.userAddress.ZTD = value.value
			this.showZTD = false
		},
		// #ifdef APP-PLUS
		// 获取选择的地区
		handleGetRegion (region) {
			this.region = region
		},
		// #endif
		// 回去地址数据
		getCityList: function () {
			let that = this;
			// getCity().then(res => {
			this.district = city_res
			that.initialize();
			// })
		},
		initialize () {
			let that = this,
				province = [],
				city = [],
				area = [];
			let cityChildren = that.district[0].c || [];
			let areaChildren = cityChildren.length ? (cityChildren[0].c || []) : [];
			that.district.forEach((item, i) => {
				province.push(item.n);
				if (item.n === this.region[0]) {
					this.valueRegion[0] = i
					this.multiIndex[0] = i
				}
			});
			that.district[this.valueRegion[0]].c.forEach((item, i) => {
				if (this.region[1] == item.c) {
					this.valueRegio[1] = i
					this.multiIndex[1] = i
				}
				city.push(item.n);
			});
			that.district[this.valueRegion[0]].c[this.valueRegion[1]].c.forEach((item, i) => {
				if (this.region[2] == item.c) {
					this.valueRegio[2] = i
					this.multiIndex[2] = i
				}
				area.push(item.n);
			});
			this.multiArray = [province, city, area]

		},
		bindRegionChange: function (e) {
			let multiIndex = this.multiIndex,
				province = this.district[multiIndex[0]] || {
					c: []
				},
				city = province.c[multiIndex[1]] || {
					v: 0
				},
				multiArray = this.multiArray,
				value = e.detail.value;

			this.region = [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]]]
			// this.$set(this.region,0,multiArray[0][value[0]]);
			// this.$set(this.region,1,multiArray[1][value[1]]);
			// this.$set(this.region,2,multiArray[2][value[2]]);
			this.cityId = city.v
			this.valueRegion = [0, 0, 0]
			this.initialize();
		},
		bindMultiPickerColumnChange: function (e) {
			let that = this,
				column = e.detail.column,
				value = e.detail.value,
				currentCity = this.district[value] || {
					c: []
				},
				multiArray = that.multiArray,
				multiIndex = that.multiIndex;
			multiIndex[column] = value;
			switch (column) {
				case 0:
					let areaList = currentCity.c[0] || {
						c: []
					};
					multiArray[1] = currentCity.c.map((item) => {
						return item.n;
					});
					multiArray[2] = areaList.c.map((item) => {
						return item.n;
					});
					break;
				case 1:
					let cityList = that.district[multiIndex[0]].c[multiIndex[1]].c || [];
					multiArray[2] = cityList.map((item) => {
						return item.n;
					});
					break;
				case 2:

					break;
			}
			// #ifdef MP || APP-PLUS
			this.$set(this.multiArray, 0, multiArray[0]);
			this.$set(this.multiArray, 1, multiArray[1]);
			this.$set(this.multiArray, 2, multiArray[2]);
			// #endif
			// #ifdef H5
			this.multiArray = multiArray;
			// #endif



			this.multiIndex = multiIndex
			// this.setData({ multiArray: multiArray, multiIndex: multiIndex});
		},
		// 授权回调
		onLoadFun: function () {
			this.getUserAddress();
		},
		// 授权关闭
		authColse: function (e) {
			this.isShowAuth = e
		},
		toggleTab (str) {
			this.$refs[str].show();
		},
		// bindRegionChange: function(e) {
		// 	this.$set(this, 'region', e.detail.value);
		// },
		onConfirm (val) {
			this.region = val.checkArr[0] + '-' + val.checkArr[1] + '-' + val.checkArr[2];
		},
		getUserAddress: function () {
			if (!this.id) return false;
			let that = this;
			getUserAddressDetailById({ id: this.id, type: 0 }).then(res => {
				// let region = [res.data.province, res.data.city, res.data.district];
				let region = [res.data.province, res.data.city, res.data.district];
				that.$set(that, 'userAddress', res.data);
				that.userAddress.defaultState = that.userAddress.defaultState == 2 ? true : false
				that.$set(that, 'region', region);
				that.cityId = res.data.city
			});
		},
		// 导入共享地址（小程序）
		getWxAddress: function () {
			let that = this;
			uni.authorize({
				scope: 'scope.address',
				success: function (res) {
					uni.chooseAddress({
						success: function (res) {
							let addressP = {};
							addressP.province = res.provinceName;
							addressP.city = res.cityName;
							addressP.district = res.countyName;
							editAddress({
								address: addressP,
								defaultState: 1,
								realName: res.userName,
								post_code: res.postalCode,
								phone: res.telNumber,
								detail: res.detailInfo,
								id: 0,
								type: 1,
							}).then(res => {
								setTimeout(function () {
									if (that.cartId) {
										let cartId = that.cartId;
										let pinkId = that.pinkId;
										let couponId = that.couponId;
										that.cartId = '';
										that.pinkId = '';
										that.couponId = '';
										uni.navigateTo({
											url: '/pages/goods/order_confirm/index?cartId=' +
												cartId +
												'&addressId=' + (
													that.id ? that
														.id :
														res.data
															.id) +
												'&pinkId=' +
												pinkId +
												'&couponId=' +
												couponId +
												'&new=' + that
													.news +
												'&noCoupon=' + that
													.noCoupon
										});
									} else {
										uni.navigateBack({
											delta: 1
										});
									}
								}, 1000);
								return that.$util.Tips({
									title: this.$t(`添加成功`),
									icon: 'success'
								});
							}).catch(err => {
								return that.$util.Tips({
									title: err
								});
							});
						},
						fail: function (res) {
							if (res.errMsg == 'chooseAddress:cancel') return that.$util
								.Tips({
									title: this.$t(`取消选择`)
								});
						},
					})
				},
				fail: function (res) {
					uni.showModal({
						title: this.$t(`您已拒绝导入微信地址权限`),
						content: this.$t(`是否进入权限管理，调整授权？`),
						success (res) {
							if (res.confirm) {
								uni.openSetting({
									success: function (res) { }
								});
							} else if (res.cancel) {
								return that.$util.Tips({
									title: that.$t(`已取消！`)
								});
							}
						}
					})
				},
			})
		},
		// 导入共享地址（微信）；
		getAddress () {
			let that = this;
			that.$wechat.openAddress().then(userInfo => {
				editAddress({
					id: this.id,
					realName: userInfo.userName,
					phone: userInfo.telNumber,
					address: {
						province: userInfo.provinceName,
						city: userInfo.cityName,
						district: userInfo.countryName
					},
					detail: userInfo.detailInfo,
					defaultState: 1,
					post_code: userInfo.postalCode,
					type: 1,
				})
					.then(() => {
						setTimeout(function () {
							if (that.cartId) {
								let cartId = that.cartId;
								let pinkId = that.pinkId;
								let couponId = that.couponId;
								that.cartId = '';
								that.pinkId = '';
								that.couponId = '';
								uni.navigateTo({
									url: '/pages/goods/order_confirm/index?cartId=' +
										cartId + '&addressId=' + (that.id ? that.id :
											res.data
												.id) + '&pinkId=' + pinkId + '&couponId=' +
										couponId + '&new=' + that.news +
										'&noCoupon=' + that
											.noCoupon
								});
							} else {
								uni.navigateTo({
									url: '/pages/users/user_address_list/index'
								})
								// history.back();
							}
						}, 1000);
						// close();
						that.$util.Tips({
							title: that.$t(`添加成功`),
							icon: 'success'
						});
					})
					.catch(err => {
						// close();
						return that.$util.Tips({
							title: err || that.$t(`添加失败`)
						});
					});
			}).catch(err => { });
		},
		/**
		 * 发布团购
		 */
		formSubmit: function (e) {
			let that = this,
			value = e.detail.value;
			console.log(value);
			console.log(that.grouponReqData);

			if (!value.mainTitle.trim()) return that.$util.Tips({
				title: that.$t(`请填写主标题`)
			});
			if (!value.subTitle.trim()) return that.$util.Tips({
				title: that.$t(`请填写副标题`)
			});

			uni.showLoading({
				title: that.$t(`发布中`),
				mask: true
			})
			let resSuccess = false;
			publishGroupon(that.grouponReqData).then(res => {
				that.$util.Tips({
					title: that.$t(`提交成功`),
					icon: 'success'
				});
				resSuccess = true
			}).catch(err => {
				return that.$util.Tips({
					title: err
				});
			})

			if (resSuccess) {
				// setTimeout(function () {
				// 	if (that.cartId) {
				// 		let cartId = that.cartId;
				// 		let pinkId = that.pinkId;
				// 		let couponId = that.couponId;
				// 		that.cartId = '';
				// 		that.pinkId = '';
				// 		that.couponId = '';
				// 		uni.navigateTo({
				// 			url: '/pages/goods/order_confirm/index?new=' + that.news +
				// 				'&cartId=' + cartId + '&addressId=' + (that.id ? that.id :
				// 					res.data.id) + '&pinkId=' + pinkId + '&couponId=' +
				// 				couponId +
				// 				'&noCoupon=' + that
				// 					.noCoupon
				// 		});
				// 	} else {
				// 		// #ifdef H5
				// 		return history.back();
				// 		// #endif
				// 		// #ifndef H5
				// 		return uni.navigateBack({
				// 			delta: 1,
				// 		})
				// 		// #endif
				// 	}
				// }, 1000);
			}
		},
		ChangeIsDefault: function (e) {
			this.$set(this.userAddress, 'defaultState', !this.userAddress.defaultState);
		}
	}
}
</script>

<style scoped lang="scss">
.fontcolor {
	color: var(--view-theme);
}

.addAddress .list {
	background-color: #fff;
	padding-top: 10rpx;
	.title {
		margin: 30rpx;
		height: 44rpx;
		font-size: 32rpx;
		font-weight: bolder;
		color: #111111;
		line-height: 44rpx;
	}
}

.addAddress .list .item {
	padding: 30rpx;
	border-top: 1rpx solid #eee;
}

.addAddress .list .item .name {
	width: 195rpx;
	font-size: 30rpx;
	color: #333;
}

.addAddress .list .item .address {
	// width: 412rpx;
	flex: 1;
	margin-left: 20rpx;
}

.addAddress .list .item input {
	width: 475rpx;
	font-size: 30rpx;
}

.addAddress .list .item .placeholder {
	color: #ccc;
}

.addAddress .list .item picker {
	width: 475rpx;
}

.addAddress .list .item picker .picker {
	width: 410rpx;
	font-size: 30rpx;
}

.addAddress .list .item picker .iconfont {
	font-size: 43rpx;
}

.addAddress .default {
	padding: 0 30rpx;
	height: 90rpx;
	background-color: #fff;
	margin-top: 23rpx;
}

.addAddress .default checkbox {
	margin-right: 15rpx;
}

.addAddress .keepBnt {
	width: 90%;
	height: 84rpx;
	background: #B42A3E;
	border-radius: 8rpx;
	margin: 30rpx auto;
	font-size: 28rpx;
	font-weight: 400;
	color: #FFFFFF;
	line-height: 84rpx;
}

.addAddress .wechatAddress {
	width: 690rpx;
	height: 86rpx;
	border-radius: 50rpx;
	text-align: center;
	line-height: 86rpx;
	margin: 0 auto;
	font-size: 32rpx;
	color: var(--view-theme);
	border: 1px solid var(--view-theme);
}


.button_1 {
	width: 90%;
	height: 84rpx;
	background: #FFFFFF;
	border-radius: 8rpx;
	border: 2rpx solid #B42A3E;
	margin: 30rpx auto;
	font-size: 28rpx;
	font-weight: 400;
	color: #B42A3E;
	line-height: 84rpx;
}

.text_15 {
	overflow-wrap: break-word;
	color: rgba(180, 42, 62, 1);
	font-size: 14px;
	font-weight: NaN;
	text-align: center;
	white-space: nowrap;
	line-height: 20px;
}



.acea-row-item {
	display: flex;
	width: 100% !important;
	flex-direction: row;


	.picture {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;

		image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}

	.p-r {
		flex-direction: column;
		width: 100%;
		display: flex;
		justify-content: space-between;

		.name {}

		.acea-row-item-bArea {
			display: flex;
			justify-content: space-between;
		}
	}
}
</style>
