<template>
	<div class="innerMargin">
    <el-card class="box-card">
			<el-form
				class="form"
				ref="userMsgRef"
				:model="userMsg"
				label-width="90px"
				:rules="editUserMsgRules"
			>
				<el-form-item label="用户头像:" prop="newPass">
					<el-upload
						class="avatar-uploader"
						action
						:auto-upload="false"
						:show-file-list="false"
						:on-change="changeUpload"
					>
						<img v-if="userMsg.image" :src="userMsg.image" class="avatar" />
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
					<div class="hint">仅支持jpg、gif、jpeg、bmp格式，文件小于4M</div>
				</el-form-item>
				<el-form-item label="用户名:" prop="">
					<el-input
						type="text"
						disabled="disabled"
						v-model="userMsg.username"
					></el-input>
				</el-form-item>
				<el-form-item label="联系方式: " prop="mobile">
					<el-input
						type="mobile"
						v-model="userMsg.mobile"
						maxlength="11"
					></el-input>
				</el-form-item>
				<el-form-item label="地址:">
					<div class="block">
						<el-cascader
							placeholder="搜索：河南"
							v-model="cityValue"
							:options="options"
							:props="props"
							@change="handleChange"
							filterable
						>
						</el-cascader>
					</div>
				</el-form-item>
				<el-form-item label="邮箱:" prop="email">
					<el-input type="email" v-model="userMsg.email"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="saveUserMsg">保存</el-button>
					<el-button @click="resetForm">取消</el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<!-- vueCropper 剪裁图片实现-->
		<el-dialog title="图片剪裁" :visible.sync="cropperVisible" append-to-body>
			<div class="cropper-content">
				<div style="width: 100%; height: 500px">
					<vueCropper
						ref="cropper"
						:img="photo.img"
						autoCrop
						centerBox
						fixed
						:fixedNumber="photo.fixedNumber"
						:outputSize="photo.size"
						:outputType="photo.outputType"
					></vueCropper>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cropperVisible = false">取 消</el-button>
				<el-button type="primary" @click="finish">确认</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import cityArr from './citydata.js'
export default {
	data() {
		var telRexEx = (rule, value, callback) => {
			if (value) {
				if (!/^1[3456789]\d{9}$/.test(value)) {
					callback(new Error('手机号码有误，请重填'))
					return false
				} else {
					callback()
				}
			} else {
				// callback(new Error('请输入联系方式'));
				callback()
			}
		}
		var emailRexEx = (rule, value, callback) => {
			if (value) {
				// if(!(/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value))){
				if (!/^[0-9|A-z|]{6,18}[@][0-9|A-z]{1,3}.(com)$/.test(value)) {
					callback(new Error('邮箱有误，请重填'))
					return false
				} else {
					callback()
				}
			} else {
				callback()
			}
		}
		return {
			userMsg: {
				ret: '',
				mobile: '',
				province: '',
				city: '',
				district: '',
				image: '',
				email: '',
				username: ''
			},
			cityValue: [],
			options: cityArr,
			props: {
				expandTrigger: 'hover',
				value: 'value'
			},
			cropperVisible: false,
			// 裁剪组件的基础配置option
			photo: {
				img: '', // 裁剪图片的地址
				info: true, // 裁剪框的大小信息
				outputSize: 0.8, // 裁剪生成图片的质量
				outputType: 'jpeg', // 裁剪生成图片的格式
				// canScale: false, // 图片是否允许滚轮缩放
				// autoCrop: true, // 是否默认生成截图框
				// autoCropWidth: 300, // 默认生成截图框宽度
				// autoCropHeight: 200, // 默认生成截图框高度
				// fixedBox: true, // 固定截图框大小 不允许改变
				fixed: true, // 是否开启截图框宽高固定比例
				fixedNumber: [1, 1], // 截图框的宽高比例
				full: true, // 是否输出原图比例的截图
				canMoveBox: false, // 截图框能否拖动
				original: false, // 上传图片按照原始比例渲染
				centerBox: false, // 截图框是否被限制在图片里面
				infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
			},
			// 表单验证
			editUserMsgRules: {
				mobile: [{ validator: telRexEx, trigger: 'blur' }],
				email: [{ validator: emailRexEx, trigger: 'blur' }]
			}
		}
	},
	created() {
		this.getRoleList()
	},
	mounted() {
		// this.getRoleList()
	},
	methods: {
		resetForm() {
			this.$refs.userMsgRef.resetFields()
		},
		getRoleList() {
			let that = this
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=home.homes.personal_center',
				data: this.qs.stringify({ username: localStorage.getItem('cUsername') })
			}).then((res) => {
				if (res.data.message == '') {
               var obj = res.data.data
               var a = res.data.data.image
               var b = a.replace('/api/', '')
               obj['image'] = b

					that.userMsg = res.data.data
					// console.log(that.userMsg.image)
					that.cityValue = [
						res.data.data.province,
						res.data.data.city,
						res.data.data.district
					]
				}
			})
		},
		saveUserMsg() {
			this.$refs.userMsgRef.validate((valid) => {
				console.log(11111)
				if (valid) {
					this.userMsg.ret = 'change'
					this.$axios({
						method: 'POST',
						url: '/api/api_gateway?method=home.homes.personal_center',
						data: this.qs.stringify(this.userMsg)
					}).then((res) => {
						if (res.data.message == '') {
							this.$message.success('修改成功!')
						} else {
							this.$message.error('修改失败!')
						}
					})
				} else {
					return false
				}
			})
		},
		// 上传按钮   限制图片大小
		changeUpload(file, fileList) {
			const isLt4M = file.size / 1024 / 1024 < 4
			if (!isLt4M) {
				this.$message.error('上传文件大小不能超过 4MB!')
				return false
			}
			// 上传成功后将图片地址赋值给裁剪框显示图片
			this.$nextTick(() => {
				this.photo.img = URL.createObjectURL(file.raw)
				this.cropperVisible = true
			})
		},
		// 点击裁剪，这一步是可以拿到处理后的地址
		finish() {
			// 获取截图的base64 数据
			this.$refs.cropper.getCropBlob((data) => {
				var form = new FormData()
				let resFile = this.blobToFile(data, 'filename.jpg')
				console.log(resFile)
				form.append('image', resFile)
				form.append('username', localStorage.getItem('cUsername'))

				this.cropperVisible = false
				this.$axios({
					method: 'POST',
					url: '/api/api_gateway?method=home.homes.personal_photo',
					data: form
				}).then((res) => {
					if (res.data.data.src != 0 && res.data.message == '') {
						// this.userMsg.image = `/api/${res.data.data.src}`
						this.userMsg.image = res.data.data.src
					} else {
						this.$message({
							message: '上传失败',
							type: 'error'
						})
					}
				})
			})
		},
		//转成file
		blobToFile(Blob, fileName) {
			Blob.lastModifiedDate = new Date()
			Blob.name = fileName
			return Blob
		},
		handleChange(value) {
			console.log(value)
			console.log(this.cityValue)
			this.userMsg.province = value[0]
			this.userMsg.city = value[1]
			this.userMsg.district = value[2]
		}
	}
}
</script>

<style lang='less' scoped>

.form {
	// 头像上传
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
	.avatar-uploader .el-upload:hover {
		border-color: #409eff;
	}
	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 150px;
		height: 150px;
		line-height: 150px !important;
		text-align: center;
	}
	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
	.hint {
		font-size: 12px;
		color: #707070;
	}
}

/deep/.el-input {
	width: 220px ;
}
</style>