<template>
	<div class="container" v-if="isShow" :style="{paddingTop:CustomBar +'px'}">
		<div class="detail-wrap">
			<div class="top_bgImg_container" :class="{'top_bgImg_container': true, 'blueBgImg': custTypeId === 1, 'greenBgImg': custTypeId === 2}">
				<div>*您的生日是会员权益非常重要的参考信息,</div>
				<div style="top: 48px;">且填写后不支持修改,请您填写准确真实的生日信息</div>
			</div>
			<div class="detail">
				<div class="detailName"><span></span><img src="../../static/images/personInfo/name.png"></img></div>
				<div class="detailValue">
					<input type="text" v-model="memberInfo.vipname" :class="{'placeholder_input': true, 'placeholder_input1': custTypeId === 1, 'placeholder_input1': custTypeId === 2}" :disabled="vipnameIsDisabled" placeholder="请输入姓名" />
				</div>
			</div>
			<div class="detail">
				<div class="detailName"><span></span><img style="height:35px;" src="../../static/images/personInfo/gender.png"></img></div>
				<div class="detailValue">
					<div class="uni-list-cell-db">
						<picker @change="bindGenderChange" :value="genderValue" :range="genderArray" range-key="label">
							<div class="uni-input"
								:class="{'placeholder_input':!genderArray[genderValue],'placeholder_input': true, 'placeholder_input1': custTypeId === 1, 'placeholder_input1': custTypeId === 2}">
								{{genderArray[genderValue].label || '请选择性别'}}
							</div>
						</picker>
					</div>
				</div>
			</div>
			<div class="detail">
				<div class="detailName"><span></span><img src="../../static/images/personInfo/birthday.png"></img></div>
				<div class="detailValue">
					<div class="uni-list-cell-db">
						<picker mode="date" :value="memberInfo.birthday" :start="startDate" :end="endDate" :disabled="birthdayIsDisabled"
							@change="bindDateChange">
                            <div class="uni-input" :class="{'placeholder_input1':!memberInfo.birthday}">{{memberInfo.birthday || '请选择您的生日'}}
                            </div>
						</picker>
					</div>
				</div>
			</div>
            <div class="detail">
                <div class="detailName"><span></span><img style="width: 32px;height: 46px;margin-left: 5px;margin-right: 21px;" src="../../static/images/personInfo/address.png"></img></div>
            	<div class="detailValue">
                    <input type="text" v-model="allAddress" placeholder-class="placeholder_input1" placeholder="请选择城市"
                        	@click="selectCity" disabled />
            	</div>
            </div>

            <div class="btn-wrap" >
            	<div class="btn" :class="{'btn--black': true, 'blueBtn': custTypeId === 1, 'greenBtn': custTypeId === 2}" @click="beComePromoter">保存并提交</div>
            </div>
		</div>
		<simple-address
			ref="simpleAddress"
			:pickerValueDefault="cityPickerValueDefault"
			@onConfirm="handleAddressConfirm"
			@onChange="handleAddressChange"
			themeColor='#007AFF'></simple-address>
	</div>
</template>

<script>
	// const app = getApp()
 const app = {}
	import simpleAddress from '@/components/simple-address/simple-address.vue';
  import { mapState } from 'vuex'
	import MemberCacheTool from '@/utils/member-cache-tool.js'
	import {
		kipGetUserDetail,
		kipCompleteUser,
	} from '@/utils/api-kip.js'
	import {
		crmUpdateMemberCompleted,
	} from '@/utils/api-crm-member.js'
	import KipCacheTool from '@/utils/kip-cache-tool.js'
	import {
		crmGetMemberByKipProfileId,
	} from '@/utils/api-crm-member.js'
	export default {
		components: {
			simpleAddress,
		},
		props: {
			// 是否显示页面
			isShow: {
				type: Boolean,
				default: false
			}
		},
        computed: {
            ...mapState({
                custTypeId: state => state.custTypeId
            }),
            startDate() {
            	return this.getDate('start');
            },
            endDate() {
            	return this.getDate('end');
            }
        },
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				memberInfo: {
					birthday: '',
					vipname: '',
					certificatenum: '',
					mailBox: '',
				},
				vipnameIsDisabled: false,
				birthdayIsDisabled: false,
				date: currentDate,
				// array: ['男', '女'],
				// genderIndex: '',
				marriageIndex: '',
				childIndex: '',
				cityPickerValueDefault: [0, 0, 0],
				pickerText: '',
				allAddress: '',
				shareVipcode: '',
				shareShopNo: '',
				vipcode: '',
				isSkip: '',//先跳过的值
				mobile: '',
				isPerfectInfo: false,
				genderArray: [
					{label:'男士', value: '1'},
					{label:'女士', value: '2'},
				],
				genderValue: '',
				CustomBar: '0',
				rotesName: '',
			}
		},
		onLoad: function(option) {

		},
		async created() {
			await this.$onLaunched;
			this.getUserDetail()
			let routes = getCurrentPages();
			this.rotesName = routes[routes.length - 1].route
			console.log(this.rotesName)
			uni.getSystemInfo({
				success: e => {
					// #ifdef MP-WEIXIN

					let custom = wx.getMenuButtonBoundingClientRect();
					if (this.rotesName == 'pages/automatic/automaticIndex') {
						this.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
					} else {
						this.CustomBar = 0
					}
					// #endif
				},
			})
			uni.setStorageSync('isSaveMember', false)
		},
		onHide() {
			this.cleanCacheAndBackIndex()
		},
		onUnload() {
			this.cleanCacheAndBackIndex()
		},
		destroyed() {
			this.closePerfectinfo()
		},
		watch: {
			isShow(val) {
				console.log(val,' 获取值')
			}
		},
		methods: {
			cleanCacheAndBackIndex () {
				// TODO 会员如果进入‘我的’页面能看到完善信息栏则此处处理不合适
				// 静安和浦东不完善信息不让进入小程序
				if (!this.isPerfectInfo) {
					console.info(`===> 没有完善信息，清空缓存并返回首页`)
					MemberCacheTool.cleanCurMemberCache(app)
					uni.switchTab({
						url: '/pages/automatic/automaticIndex'
					})
				}
			},
			getUserDetail: function() {
				const _this = this;
				kipGetUserDetail().then(resp => {
					const result = resp.data;
					if (result && result.code === '000000') {
						const userInfo = result.data;
						_this.handleKipUserToMemberInfo(userInfo)
					}else{
						uni.showToast({
							title: result.message,
							duration: 2000,
							icon: 'none'
						})
					}
				}).catch(err => {
					console.error(err);
				})
			},
			saveUserDetail: function() {
				const userInfo = this.handleMemberInfoToKipUser(this.memberInfo);
				if (userInfo) {
					uni.showLoading({
						title: '保存中'
					});
					const _this = this;
					kipCompleteUser(userInfo).then(resp => {
						uni.hideLoading();
						const result = resp.data;
						if (result && result.code === '000000' && result.data) {
							_this.checkIsCompleted(userInfo)
						} else {
							uni.showModal({
								content: result.message,
								showCancel: false,
							})
						}
					}).catch(err => {
						uni.hideLoading();
						console.error(err);
					})
				}
			},
			handleKipUserToMemberInfo(userInfo) {
				console.log(userInfo.extend, 'ooo')
				if (userInfo && userInfo.extend) {
					const userDetail = userInfo.extend;
					this.memberInfo.kipUserId = userInfo.id
					// 名称
					this.memberInfo.vipname = userInfo.realName  || userInfo.nickName
					if (userInfo.realName) {
						this.vipnameIsDisabled = true;
					}
					// 性别
					this.genderValue = userInfo.gender == '1' ? '0' : '1'
					this.memberInfo.sex = this.genderArray[this.genderValue].value

					// 生日
					this.memberInfo.birthday = userInfo.birthDate
					if (this.memberInfo.birthday) {
						this.birthdayIsDisabled = true;
					}

					// 所在地
					const { provinceAddress, cityAddress, districtAddress } = userDetail
					if (provinceAddress && cityAddress && districtAddress) {
						this.memberInfo.provinceAddress = provinceAddress;
						this.memberInfo.cityAddress = cityAddress;
						this.memberInfo.districtAddress = districtAddress;
						this.allAddress = provinceAddress + '-' + cityAddress + '-' +districtAddress
						this.cityPickerValueDefault = [provinceAddress, cityAddress, districtAddress];
					}
				}
			},
			handleMemberInfoToKipUser(memberInfo) {
				if (!memberInfo) {
					return
				}
				const obj = {
					"birthDate": this.memberInfo.birthday,
					"gender": this.memberInfo.sex,
					"realName": this.memberInfo.vipname,
					"provinceAddress": this.memberInfo.provinceAddress,
					"cityAddress": this.memberInfo.cityAddress,
					"districtAddress": this.memberInfo.districtAddress,
				}
				return obj;
			},
			checkMemberInfo() {
				const { vipname, birthday,  provinceAddress, cityAddress, districtAddress } = this.memberInfo || {};
				if (!vipname) {
					uni.showToast({
						title: '请输入姓名',
						duration: 2000,
						icon: 'none'
					})
					return false;
				}
				if (!birthday) {
					uni.showToast({
						title: '请选择生日',
						duration: 2000,
						icon: 'none'
					})
					return false;
				}
				if (!provinceAddress || !cityAddress ||!districtAddress) {
					uni.showToast({
						title: '请选择城市',
						duration: 2000,
						icon: 'none'
					})
					return false;
				}
				return true;
			},
			beComePromoter: function() {
				console.log(this.memberInfo)
				if (this.checkMemberInfo()) {
					this.saveUserDetail();
				}
			},
			checkIsCompleted (memberInfo) {
				if (!memberInfo) {
					console.warn("===>memberInfo is null")
					return;
				}
				const _this = this;
				const {gender, realName, birthDate,  provinceAddress, cityAddress, districtAddress} = memberInfo
				if (gender && realName && birthDate && provinceAddress && cityAddress && districtAddress ) {
					console.log('===>会员信息已完善，请求crm接口')
					const kipMember = uni.getStorageSync("kipMember")
					const params = {
						groupId: app.globalData.groupId,
						mallid: app.globalData.mallid,
						kipUserId: kipMember.id
					}
					uni.showLoading({
						title: '保存中'
					});
					crmUpdateMemberCompleted(_this.$baseURL, params).then(res => {
						uni.hideLoading();
						console.log(res)
						const result= res.data;
						if (result && result.code == '0') {
							console.log('===>改变crm会员信息完善成功')
							_this.isPerfectInfo = true;
							uni.showToast({
								title: '保存成功!',
								duration: 2000,
								icon: 'none'
							})
							uni.setStorageSync('isSaveMember', true)
							_this.getKipMemberInfoAfter()
							_this.gotoIndex()
						} else {
							console.log('===>改变crm会员信息完善失败')
							console.error(result.msg);
							_this.gotoIndex()
						}
					}).catch(err => {
						uni.hideLoading();
						console.log('===>改变crm会员信息完善错误')
						console.error(err);
						_this.gotoIndex()
					})
				} else {
					console.log('===>没有完善信息，直接跳转')
					_this.gotoIndex()
				}
			},
			//跳过
			gotoIndex: function() {
				// this.$router.push({
				// 	path: '/pages/automatic/automaticIndex'
				// })
				// 判断当前没有保存信息则清空会员信息

				this.$emit('closeBlueInfo')
			},
			/**
			 * 异常关闭页面触发的方法
			 */
			closePerfectinfo() {
				console.log(uni.getStorageSync('isSaveMember'), 'ooooooooooo')
				if (!uni.getStorageSync('isSaveMember')) {
					this.cleanCacheAndBackIndex()
					app.globalData.openId = null
					uni.removeStorageSync('openId')
				}
			},
			selectCity: function() {
				this.$refs.simpleAddress.open();
			},
			handleAddressChange (e) {
				this.memberInfo.provinceAddress = e.labelArr[0]
				this.memberInfo.cityAddress = e.labelArr[1]
				this.memberInfo.districtAddress = e.labelArr[2]
				this.allAddress = e.label
			},
			handleAddressConfirm: function(e) {
				if(!this.allAddress) {
					this.memberInfo.provinceAddress = e.labelArr[0]
					this.memberInfo.cityAddress = e.labelArr[1]
					this.memberInfo.districtAddress = e.labelArr[2]
					this.allAddress = e.label
				}
			},
			bindGenderChange: function(e) {
				this.genderValue = e.target.value
				this.memberInfo.sex = this.genderArray[this.genderValue].value;
			},
			bindDateChange: function(e) {
				this.memberInfo.birthday = e.target.value
			},
			//设置开始和结束时间
			getDate: function(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 120;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			/**
			 * 保存会员信息
			 */
			getKipMemberInfoAfter () {
				const kipMemberInfo = uni.getStorageSync('kipMember')
				// 获取到kip会员之后的操作
				MemberCacheTool.setKipMember(app, kipMemberInfo)
				// 将kipMember转成crmMember
				const newMember = MemberCacheTool.handleKipMemberToCrmMember(kipMemberInfo)
				if (!newMember) {
					console.error("===> 会员不存在")
					uni.showToast({
						title: "会员转换错误",
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				const newGroupId = uni.getStorageSync("groupId");
				const newMallId = uni.getStorageSync("mallid");
				const params = {
					groupId: newGroupId,
					kipUserId: newMember.kipUserId
				}
				const _this = this;
				// 查询 crm 会员
				uni.showLoading({
					title: '正在加载',
					mask: true,
				})
				crmGetMemberByKipProfileId(this.$baseURL, params).then(resp => {
					uni.hideLoading()
					const result = resp.data;
					if (result && result.code == '0') {
						const {member, wxMember} = result.data
						if (member && member.groupId && member.openid) {
							MemberCacheTool.setMemberCache(app, {member, wxMember})
						}
					}
				}).catch(err => {
					uni.hideLoading()
					console.error(err)
					uni.showToast({
						title: "登录注册失败",
						duration: 2000,
						icon: 'none'
					})
					KipCacheTool.cleanKipCache()
					MemberCacheTool.cleanMemberCache(app)
				})
			},
		},

	}
</script>

<style lang="less">
    @import '../../styles/common.less';
	.container {
		font-size: 24px;
		height: 100vh;
		background: #f5f5f5;
		position: fixed;
		z-index: 999;
		width: 100%;

		.detail-wrap {
			margin-top: 10px;
			background-color: #fff;
			.top_bgImg_container{
				position: relative;
				height: 110px;
				color: #FFFFFF;
				margin: 0 24px;
    		background-color: #fff;
				img {
					width: 95%;
					height: 100px;
					margin-left: 18px;
					text-align: center;
					background-size: cover;
					background-position: center;
				}
				div {
					width: 90%;
					position: absolute;
					top: 14px;
					left: 50px;
					font-size: 24px;
				}
			}
            .colorBgImg(@value) {
            	@color: 'color-@{value}';
                margin: 0 !important;
                color: #C69C6DFF !important;
                background-color: @@color !important;
                view{
                    font-size: 25px;
                }
            }
            .blueBgImg{
                .colorBgImg('blue')
            }
            .greenBgImg{
                .colorBgImg('green')
            }
			.detail {
				display: flex;
				height: 80px;
				padding: 0 30px;
				align-items: center;
				background: #fff;
				border-bottom: 1px solid #e6e6e6;

				.detailName {
					font-size: 24px;
					color: #000;
					// flex: 1;
					span {
						font-size: 30px;
						color: red;
						margin-right: 5px;
						width: 16px;
						display: inline-block;
					}
					img {
						width: 40px;
						height: 40px;
						line-height: 40px;
						vertical-align: text-bottom;
						margin-right: 18px;
					}
				}

				.detailValue {
					flex: 1;
					font-size: 28px;
					color: #808080;
				}
			}

			.detailBtn {
				width: 100%;
				display: flex;
				align-items: flex-end;
				justify-content: center;
				.btn1 {
					width: 300px;
					height: 71px;
					line-height: 71px;
					text-align: center;
					border-radius: 100px;
					font-size: 28px;
					margin-top: 30px;
					background-color:#fff;
					color: #696969;
					border: 0;
					position: absolute;
					bottom: 10%;
					left: 5%;
				}
				.btn2{
					width: 300px;
					border-radius: 100px;
					font-size: 28px;
					margin-top: 30px;
					background:linear-gradient(to right,#783ba6, #413a90);
					position: absolute;
					bottom: 10%;
					right: 5%;
				}
			}
            .btn-wrap {
            	width: 95%;
                position: fixed;
                bottom: 2%;
                left: 2%;
                padding: 10px 14px;
                box-sizing: border-box;
                background: #fff;
                height: 115px;
            }

            .btn {
            	width: 100%;
            	height: 100px;
                color: @color-gold;
            	line-height: 100px;
            	font-size: 28px;
            	text-align: center;
                border: 1px solid @color-gold;
            	font-family: PingFangHK-Regular, PingFangHK;
                margin-bottom: 27px;
            }
            .btn--black {
            	background-color: #333333;
            }
            .colorBtn(@value) {
            	@color: 'color-@{value}';
                background-color: @@color !important;
            }
            .blueBtn{
                .colorBtn('blue')
            }
            .greenBtn{
                .colorBtn('green')
            }
		}

		.reminder-con {
			padding: 20px;
			font-size: 24px;
			background: #fff;
			margin-top: 20px;

			.weixin_h3 {
				font-size: 24px;
				color: #f25454;
			}

			.cons {
				margin-top: 6px;
				color: #999;

				.weixin_p {
					line-height: 1.8;
				}
			}
		}
	}

.placeholder_input {
	color: #D3D3D3;
}
.placeholder_input1 {
	color: #808080;
    font-size: 28px;
}
	.uni-input-placeholder {
		font-size: 13px;
		color: #808080;
	}

	/deep/ .uni-input-input {
		font-size: 13px;
		color: #808080;
	}
</style>


