<template>
	<view class="mine-address-edit" v-if="isLoad">
		<view class="fill-base f-title">
			<view class="flex-between pd-lg b-1px-b">
				<view>联系人</view>
				<input v-model="subForm.user_name" type="text" class="flex-1 f-paragraph text-right"
					placeholder-class="c-placeholder" :placeholder="rule[0].errorMsg" />
			</view>
			<view class="flex-between pd-lg b-1px-b">
				<view>手机号</view>
				<input v-model="subForm.mobile" type="number" class="flex-1 f-paragraph text-right"
					placeholder-class="c-placeholder" :placeholder="rule[1].errorMsg" />
				<button open-type="getPhoneNumber" @getphonenumber="toAuthPhone" class="clear-btn"
					:style="{color:primaryColor,marginLeft:'15rpx',fontSize:'28rpx'}">授权</button>
			</view>
			<view class="flex-between pd-lg b-1px-b">
				<view class="flex-1">选择地区</view>
				<view @tap.stop="toChooseLocation" class="flex-y-center f-paragraph max-500 text-right">
					<view class="flex-1 text-right"
						:class="[{'c-placeholder':!subForm.address},{'c-title':subForm.address}]">
						{{subForm.address || `点击右边图标设置`}}
					</view><i class="iconfont icon-dingwei-fill ml-sm" :style="{color: primaryColor}"></i>
				</view>
			</view>
			<view class="pd-lg f-title">
				<view>详细地址</view>
				<textarea class="pt-lg textarea-item f-paragraph" v-model="subForm.address_info" maxlength="100"
					placeholder-class="c-placeholder" :placeholder="rule[3].errorMsg"></textarea>
			</view>
		</view>
		<view class="fill-base mt-md pt-sm pb-sm pl-lg pr-lg f-paragraph">
			<view class="flex-between">
				<view class="f-paragraph">设为默认地址</view>
				<view @tap.stop="toSetItem" class="flex-1 text-right">
					<i class="iconfont icon-switch ml-sm" :class="[{'icon-switch-on':subForm.status==1}]"
						:style="{color: subForm.status==1 ? primaryColor : '#999'}"></i>
				</view>
			</view>
		</view>
		<view class="f-caption c-title mt-md pl-lg"> 设置后，下单时优先展示该地址</view>

		<view class="space-max-footer"></view>

		<fix-bottom-button @cancel="$refs.del_item.open()" @confirm="confirmSubmit"
			:text="subForm.id?[{text: '删除',type: 'cancel'}, {text: '保存',type: 'confirm'}]:[{text: '提交',type: 'confirm'}]"
			bgColor="#fff"></fix-bottom-button>


		<common-popup @confirm="confirmDel" ref="del_item" type="DEL_ITEM" :info="popupInfo"></common-popup>

	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	export default {
		components: {},
		data() {
			return {
				isLoad: false,
				options: {},
				subForm: {
					id: 0,
					user_name: '',
					mobile: '',
					address: '',
					address_info: '',
					province:'',
					lng: '',
					lat: '',
					status: 0
				},
				rule: [{
						name: "user_name",
						checkType: "isNotNull",
						errorMsg: "请输入联系人姓名",
						regType: 2
					}, {
						name: "mobile",
						checkType: "isMobile",
						errorMsg: "请输入手机号"
					},
					{
						name: "address",
						checkType: "isNotNull",
						errorMsg: "设置地区"
					},
					{
						name: "address_info",
						checkType: "isNotNull",
						errorMsg: "请输入街道、楼牌号等",
						regType: 2
					},
				],
				lockTap: false,
				popupInfo: {}
			}
		},
		computed: mapState({
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			userInfo: state => state.user.userInfo,
		}),
		onLoad(options) {
			this.options = options
			this.initIndex()
		},
		methods: {
			...mapActions(['getAuthPhone']),
			...mapMutations(['updateOrderItem']),
			async initIndex() {
				let {
					id = 0
				} = this.options
				uni.setNavigationBarTitle({
					title: id ? `编辑地址` : `新增地址`
				})
				if (!id) {
					this.isLoad = true
					this.subForm.mobile = this.userInfo.phone
					return
				}
				this.$util.showLoading()
				let data = await this.$api.mine.addressInfo({
					id
				})
				for (let key in this.subForm) {
					this.subForm[key] = data[key]
				}
				this.isLoad = true
				this.$util.hideAll()
			},
			// 授权手机号
			async toAuthPhone(e) {
				let phone = await this.getAuthPhone({
					e,
				})
				if (!phone) return
				this.$nextTick(() => {
					this.subForm.mobile = phone
				})
			},
			// 选择地区
			async toChooseLocation(e) {
				await this.$util.checkAuth({
					type: 'userLocation'
				})
				let [, {
					address = '',
					longitude,
					latitude
				} = {}] = await uni.chooseLocation();
				if (!address) return
				let reg = /.+?(省|市|自治区|自治州|区)/g
				this.subForm.province = address.match(reg)[0]
				this.subForm.address = address
				this.subForm.lng = longitude
				this.subForm.lat = latitude
			},
			toSetItem() {
				this.subForm.status = this.subForm.status == 1 ? 0 : 1
			},
			// 确认：删除
			async confirmDel() {
				let {
					id
				} = this.subForm
				let {
					check_id
				} = this.$util.getPage(-1)
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					await this.$api.mine.addressDel({
						id
					})
					this.lockTap = false
					this.$util.hideAll()
					this.$util.showToast({
						title: `删除成功`
					})
					this.$refs.del_item.close()
					if (id == check_id) {
						this.updateOrderItem({
							key: 'haveOperItem',
							val: true
						})
					}
					setTimeout(() => {
						this.$util.back()
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			//表单验证
			validate(param) {
				let validate = new this.$util.Validate();
				this.rule.map(item => {
					let {
						name,
					} = item
					validate.add(param[name], item);
				})
				let message = validate.start();
				return message;
			},
			// 新增/编辑
			async confirmSubmit() {
				let param = this.$util.deepCopy(this.subForm)
				let msg = this.validate(param);
				if (msg) {
					this.$util.showToast({
						title: msg
					});
					return;
				}
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					let methodModel = param.id ? `addressUpdate` : `addressAdd`
					await this.$api.mine[methodModel](param)
					this.$util.hideAll()
					this.$util.showToast({
						title: `保存成功`,
					});
					this.lockTap = false;
					setTimeout(() => {
						this.$util.back()
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			}
		}
	}
</script>


<style lang="scss">
	.mine-address-edit {

		.icon-dingwei-fill {
			font-size: 40rpx;
		}

		.icon-switch,
		.icon-switch-on {
			font-size: 80rpx;
		}

		.textarea-item {
			width: 690rpx;
			height: 200rpx;
			overflow-y: auto;
		}
	}
</style>
