<template>
	<view>
		<zj-page-layout
			:isScroll="true"
			:refresherTriggered="refresherTriggered"
			@refresherrefresh="refresherrefresh">
			<u-cell-group
				:customStyle="{'background': '#FFFFFF', 'margin-top': '20rpx'}"
				v-for="(item, index) in mineList"
				:key="index">
				<u-cell
					size="large"
					:title="it.label"
					v-for="(it, idx) in item.filter(o => o.value || o.image)"
					:key="idx"
					:isLink="it.link || it.isLink"
					@tap="it.link ? navToPage(it.link) : actionFn(it.fn)">
					<view slot="value">
						<text style="color: #999999;" v-if="it.value" class="value-text">{{it.value}}</text>
						<text style="color: #999999;" v-else-if="it.icon" class="iconfont value-icon" :class="it.icon"></text>
						<image :src="it.image" class="img" v-else-if="it.image"></image>
					</view>
				</u-cell>
			</u-cell-group>
		</zj-page-layout>

		<u-popup :round="10" :show="isShowInfoDialog">
			<view class="info-dialog">
				<view class="content">
					<view class="title">获取您的头像和昵称</view>
					<view class="text">为了方便识别您的身份，请授权您的头像和昵称</view>
				</view>
				<view class="form">
					<view class="item">
						<view class="label">头像</view>
						<view class="value" @tap="chooseAvatar">
              <image :src="infoForm.avatar" v-if="infoForm.avatar && infoForm.avatar.indexOf('http') >= 0"></image>
              <image :src="imageUrl + infoForm.avatar" v-else-if="infoForm.avatar"></image>
              <view class="empty" v-else>请选择</view>
						</view>
					</view>
					<view class="item">
						<view class="label">昵称<text>({{userInfo.type == 'WORKER' ? '工程师不可更改' : ''}})</text></view>
						<view class="value">
							<input
                :disabled="userInfo.type == 'WORKER'"
								type="nickname"
								placeholder="请输入昵称"
								border="none"
								v-model="infoForm.nickname"
								@change="getNickname"
							></input>
						</view>
					</view>
				</view>
				<view class="btn">
					<button @tap="isShowInfoDialog = false">取消</button>
					<button type="primary" @tap="saveUserInfo()">提交</button>
				</view>
			</view>
		</u-popup>

		<u-picker :show="isShowSexPicker" :columns="[['男', '女']]" @confirm="confirmSex" @cancel="isShowSexPicker = false"></u-picker>

	</view>
</template>

<script>
	import { uploadImgFull } from '@/common/utils/util.js';

	export default {
		data() {
			return {
				refresherTriggered: false,
				imageUrl: this.$imageUrl,
				mineList: [],
        userInfo: {},
				isShowInfoDialog: false, // 是否显示获取用户信息弹窗
				infoForm: {
					avatar: '',
					nickname: '',
				},

				isShowSexPicker: false,
			}
		},

		onLoad() {
			this.initData();
		},

		methods: {
			// 触发下拉刷新
			async refresherrefresh(e) {
				this.refresherTriggered = true;
				this.initData();
			},

			async initData() {
				const userInfo = await this.$getUserInfo();
				const address = await this.getAddressList();
        this.userInfo = userInfo;
				this.infoForm = {
					avatar: userInfo.avatar || '',
					nickname: userInfo.nickName || '',
				}
				this.mineList = [
					[{
						label: '头像',
						image: userInfo.avatar ? (userInfo.avatar.indexOf('http') >= 0 ? userInfo.avatar : this.$imageUrl + userInfo.avatar) : require('@/static/images/logo.png'),
						className: 'head',
						isLink: true,
						fn: 'changeInfo'
					}, {
						label: '昵称',
						value: userInfo.nickName || '',
						isLink: true,
						fn: 'changeInfo'
					}, {
						label: '姓名',
						value: userInfo.serviceWorkerBean && userInfo.serviceWorkerBean.workerRealName ? userInfo.serviceWorkerBean.workerRealName : '',
						isLink: false,
					}, {
						label: '手机号',
						value: userInfo.mobile || '',
						isLink: false,
					}, {
						label: '性别',
						value: userInfo.sex || '',
						isLink: true,
						fn: 'changeSex'
					}, {
						label: '默认地址',
						value: address ? `${address.province}${address.city}${address.area}${address.street}${address.address}${address.houseNo}` : '请添加',
						link: '/packageMine/pages/address/list',
					}]
				]
				this.refresherTriggered = false;
			},

			async getAddressList() {
				return new Promise((resolve, reject) => {
					this.$api.get('/user/address/list', {
            pageNum: 1,
            pageSize: -1,
            userId: this.$store.state.user.userId
					}).then(res => {
						let data = res.data.records.find(o => o.defaultAddr);
						resolve(data);
					})
				})
			},

			// 跳转链接
			navToPage(url) {
				this.$navToPage({
          url
        });
			},

			// 执行方法
			actionFn(fn) {
				if(!fn) return false;
				this[fn]();
			},

			changeInfo() {
				this.isShowInfoDialog = true;
			},

			// 选择头像
			chooseAvatar() {
        uni.chooseImage({
        	count: 1,
        	success: res => {
        		uni.showLoading();
        		res.tempFilePaths.forEach(async item => {
        			let data = await uploadImgFull(item);
              this.infoForm.avatar = data.url;
        		});
        		uni.hideLoading();
        	},
        	fail: err => {}
        })
			},

			// 用户昵称审核完毕
			getNickname(e) {
				this.infoForm.nickname = e.detail.value;
			},

			// 保存用户信息
			saveUserInfo() {
				if(!this.infoForm.avatar) {
					return this.$toast('请先上传头像');
				}
				if(!this.infoForm.nickname) {
					return this.$toast('请先输入昵称');
				}

				this.$api.post('/user/userinfo/save', {
          userId: this.$store.state.user.userId,
          avatarUrl: this.infoForm.avatar,
          nickName: this.infoForm.nickname,
				}).then(res => {
					this.isShowInfoDialog = false;
					this.initData();
				})
			},

			changeSex() {
				this.isShowSexPicker = true;
			},

			confirmSex(e) {
				this.$api.post('/user/userinfo/save', {
          userId: this.$store.state.user.userId,
          sex: e.value[0],
				}).then(res => {
					this.isShowSexPicker = false;
					this.initData();
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.value-text {
		max-width: 500rpx;
		display: inline-block;
		text-align: right;
		line-height: 40rpx;
	}
	.img {
		width: 96rpx;
		height: 96rpx;
		border-radius: 50%;
	}

	.info-dialog {
		padding: 40rpx 40rpx 80rpx;
		box-sizing: border-box;
		.content {
			.title {
				font-size: 32rpx;
				font-weight: 500;
			}
			.text {
				font-size: 24rpx;
				color: #999999;
				margin-top: 20rpx;
			}
		}
		.form {
			.item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 30rpx;
				.label {
          flex-shrink: 0;
          text {
            font-size: 24rpx;
            color: $sec-font;
            margin-left: 8rpx;
          }
				}
				.value {
					input {
						height: 68rpx;
						text-align: right !important;
					}
					image {
						width: 88rpx;
						height: 88rpx;
						border-radius: 88rpx;
						display: block;
					}
					.empty {
						width: 88rpx;
						height: 88rpx;
						border-radius: 88rpx;
						background: #f5f5f5;
						text-align: center;
						line-height: 88rpx;
						font-size: 24rpx;
						color: #999999;
					}
				}
			}
		}
		.btn {
			display: flex;
			justify-content: center;
			margin-top: 60rpx;
			button::after {
				border: none;
			}
			button {
				width: 180rpx;
				height: 70rpx;
				line-height: 70rpx;
				margin: 0;
				font-size: 28rpx;
				margin: 0 30rpx;
				&:first-child {
					background: #f5f5f5;
					color: $theme-color;
				}
				&:last-child {
					background: $theme-color;
					color: #FFFFFF;
				}
			}
		}
	}
</style>
