<template>
	<view v-if="!loading">
		<view class="form">
			<view class="li ddflex">
				<view class="label">名片页背景</view>
				<view class="photo ddflex flex" @tap="uploadImgsCopper()">
					<image :src="avatar ? avatar : '../../static/images/userimg.png'" mode="aspectFill" class="userimg"></image>
					<image src="../../static/images/rico.png" class="rico"></image>
				</view>
			</view>
			<view class="li ddflex">
				<view class="label">姓名</view>
				<input v-model="realName" :disabled="true" placeholder="请填写你的真实姓名" placeholder-class="placeholder" class="ipt flex" />
			</view>
			
			<view class="li ddflex">
				<view class="label">工号</view>
				<input v-model="jobNumber" :disabled="true" placeholder="请输入工号" placeholder-class="placeholder" class="ipt flex" />
			</view>
			
			<view class="li ddflex">
				<view class="label">个人简介</view>
				<input v-if="!brief" @tap="jumpUrl('/card/editDesc/editDesc')" maxlength="11" type="number" placeholder="请作简单自我介绍" placeholder-class="placeholder" class="ipt flex" />
				<view class="fflex" v-else style="color: #47C776;" @tap="jumpUrl('/card/editDesc/editDesc')">已完善</view>
				<image src="../../static/images/rico.png" class="rico"></image>
			</view>
			
			<view class="li ddflex">
				<view class="label">执业证书</view>
				<input v-model="certificateNo" :disabled="true" placeholder="请输入执业证书编号" placeholder-class="placeholder" class="ipt flex" />
			</view>
		</view>
		
		<view class="form">
			<view class="tit ddflex"><view class="flex">联系信息</view></view>
			<view class="li ddflex">
				<view class="label">手机</view>
				<input v-model="phone" maxlength="11" type="number" placeholder="请填写手机号" placeholder-class="placeholder" class="ipt flex" />
				<!-- <view class="tong ddflex" @click="intWechatNumber"><image src="../static/images/wxth.png"></image>微信同号</view> -->
			</view>
			<view class="li ddflex">
				<view class="label">微信号</view>
				<input v-model="wechat" placeholder="请填写微信号" placeholder-class="placeholder" class="ipt flex" />
			</view>
			<!-- <view class="li ddflex">
				<view class="label">邮箱</view>
				<input v-model="email" placeholder="请填写邮箱地址" placeholder-class="placeholder" class="ipt flex" />
			</view> -->
			<view class="li dflex">
				<view class="label">微信二维码</view>
				<view v-if="!wechatCode" class="upload-box ddflex" @tap="uploadWechat()">
					<image src="../static/images/pic.png"></image>
					<view>点击上传</view>
				</view>
				<view v-else class="upload-box-image ddflex" @tap="uploadWechat()">
					<image class="upload-image" :src="wechatCode"></image>
					<image class="upload-close" src="../../static/pages/images/close3.png" @click.stop="wechatCode=''"></image>
				</view>
			</view>
			<view class="li dflex">
				<view class="label">企微二维码</view>
				<view v-if="!wechatCompanyCode" class="upload-box ddflex" @tap="uploadWechatCompanyCode()">
					<image src="../static/images/pic.png"></image>
					<view>点击上传</view>
				</view>
				<view v-else class="upload-box-image ddflex" @tap="uploadWechatCompanyCode()">
					<image class="upload-image" :src="wechatCompanyCode"></image>
					<image class="upload-close" src="../../static/pages/images/close3.png" @click.stop="wechatCompanyCode=''"></image>
				</view>
			</view>
		</view>
		
		<view class="form">
			<!-- <view class="li dflex">
				<view class="label">所获荣誉</view>
				<view class="ddflex upload-group flex">
					<view class="upload-box-image ddflex" v-for="item,index in honorImgUrls" @click="uploadHonor('change',index)">
						<image class="upload-image" :src="item"></image>
						<image class="upload-close" src="../../static/pages/images/close3.png" @click.stop="deleteHonor(index)"></image>
					</view>
					<view class="upload-box ddflex" @tap="uploadHonor()" v-if="honorImgUrls.length<9">
						<image src="../static/images/pic.png"></image>
						<view>点击上传</view>
					</view>
				</view>
			</view> -->
			<view class="li dflex">
				<view class="label">个人风采</view>
				<view class="ddflex upload-group flex">
					<view class="upload-box-image ddflex" v-for="item,index in styleImgUrls" @click="uploadStyle('change',index)">
						<image class="upload-image" :src="item"></image>
						<image class="upload-close" src="../../static/pages/images/close3.png" @click.stop="deleteStyle(index)"></image>
					</view>
					<view class="upload-box ddflex" @tap="uploadStyle()" v-if="styleImgUrls.length<9">
						<image src="../static/images/pic.png"></image>
						<view>点击上传</view>
					</view>
				</view>
			</view>
		</view>

		<view class="form">
			<view class="tit ddflex"><view class="flex">公司信息</view></view>
			<view class="li ddflex">
				<view class="label">公司</view>
				<input v-model="companyName" :disabled="true" placeholder="请填写公司名称" placeholder-class="placeholder" class="ipt flex" />
			</view>
			<!-- <view class="li ddflex">
				<view class="label">公司简介</view>
				<input v-if="!companyIntroduction" @tap="jumpUrl('/card/editDesc/editDesc?isCompanyIntroduction=true')" :disabled="true"  maxlength="11" type="number" placeholder="请填写公司简介" placeholder-class="placeholder" class="ipt flex" />
				<view class="fflex" v-else style="color: #47C776;"  @tap="jumpUrl('/card/editDesc/editDesc?isCompanyIntroduction=true')">已完善</view>
				<image src="../../static/images/rico.png" class="rico"></image>
			</view> -->
			<view class="li ddflex">
				<view class="label">入司时间</view>
				<picker mode="date" v-model="inDate" :disabled="true" @change="inDateChange">
					{{inDate?inDate:'请填写入司时间'}}
				</picker>
				<!-- <input v-model="companyName" :disabled="true" placeholder="请填写公司名称" placeholder-class="placeholder" class="ipt flex" /> -->
			</view>
			<view class="li ddflex">
				<view class="label">职位</view>
				<input v-model="job" :disabled="true" placeholder="请填写职位" placeholder-class="placeholder" class="ipt flex" />
			</view>
			<!-- <view class="li ddflex" @click="jumpUrl('/card/industry/industry?isPoistion=true')">
				<view class="label">行业</view>
				<view :class="'flex' + (industryName ? '' :' placeholder')">{{industryName ? industryName : '请填写行业'}}</view>
				<image src="../../static/images/rico.png" class="rico"></image>
			</view> -->
			<view class="li ddflex">
				<view class="label">所在地区</view>
				<view :class="['item flex', city ? 'active' : '']">
					<pickerAddress class="picker flex" @change="bindAddressChange">
						<view :class="city?'':'placeholder'">{{ city ? city : '请选择地区' }}</view>
					</pickerAddress>
				</view>
				<image src="../../static/images/rico.png" class="rico"></image>
				<!-- <picker class="picker flex">
					<view class="placeholder">请选择省份城市</view>
					<image src="../../static/images/rico.png" class="rico"></image>
				</picker> -->
			</view>
			<view class="li ddflex" @click="chooseLocation()">
				<view class="label">地址</view>
				<input :disabled="true" v-model="address" placeholder="填写街道地址" placeholder-class="placeholder" class="ipt flex" />
			</view>
		</view>
		<view class="bot">
			<view class="btn" @click="submitCard()">{{ isEdit ? '保存' : '确认创建' }}</view>
		</view>
		
		<yqAvatar v-if="copperShow" @upload="copperSuccess" ref="avatar"></yqAvatar>
	</view>
</template>

<script>
const req = require('../../utils/request.js');
const util = require('../../utils/util.js');
var QQMapWX = require('../../utils/qqmap.js');
var app = getApp();
import pickerAddress from '../../components/wangding-pickerAddress/wangding-pickerAddress.vue';
import yqAvatar from '../../card/components/yq-avatar/yq-avatar.vue';
export default {
	components: { pickerAddress,yqAvatar },
	data() {
		return {
			avatar: '',
			realName: '',
			phone: '',
			jobNumber:'',
			wechat: '',
			wechatCode:'',
			wechatCompanyCode:'',
			email: '',
			companyName: '',
			job:'',//职业
			industryName: '',//行业
			tradeId: '',//行业id
			message: '',
			isEdit: false,
			id: '' ,//名片id
			nums: 0,
			brief:'',//简介
			address:'',//详细地址
			inDate:'',//入司时间
			companyIntroduction:'',//公司简介
			
			honorImgUrls:[],//荣誉
			
			styleImgUrls:[],//风采
			
			city: '',
			areaCode: '',
			morCity: [],
			companyCode:'',
			location:{},
			longitude:'',
			latitude:'',
			
			userCard:null,//用户IP名片
			employmentInfo:'',
			saleNo:null,
			certificateNo:null,
			loading:true,
			copperShow:false,
			copperUrl:''
		};
	},
	async onLoad(opt) {
		this.isEdit = opt.isEdit?true:false;
		this.id = opt.id;
		
		await req.silenceLogin(opt.saleNo)
		console.log('getUserCard')
		await this.getUserInfo()
		this.getUserCard()
	},

	methods: {
		getUserInfo(){
			return new Promise((resolve,reject)=>{
				req.getRequest('/api/user/info',{},res=>{
					// this.avatar = res.avatar;
					this.phone = res.mobile;
					this.saleNo = res.saleNo
					req.setStorage('saleNo',this.saleNo)
					// this.getEmploymentInfo()
					resolve();
				})
			})
		},
		getEmploymentInfo(){
			return new Promise((resolve,reject)=>{
				req.getRequest('/api/visiting/card/employmentInfo',{jobNumber:this.saleNo},res=>{
					if(res.name){
						this.employmentInfo = res;
						this.realName = this.employmentInfo.name;
						this.certificateNo = this.employmentInfo.professionalCertificateNo
						this.jobNumber = this.employmentInfo.salesNo
						this.companyName = this.employmentInfo.branchName
						this.job = this.employmentInfo.actrankName
						this.inDate = this.employmentInfo.inDate
						this.companyCode = this.employmentInfo.branchNo
					}
					else return req.msg("员工信息不存在")
					resolve();
				})
			})
		},
		// 用户名片信息
		getUserCard(){
			req.getRequest('/api/visiting/card/userInfo', {}, res => {
				console.log('getUserCard',res)
				this.userCard = res
				if(!res){
					this.isEdit = true
					// this.getUserInfo()
				}else{
					if(!this.isEdit){
						if(res.auditState==0){
							// 待审核
							uni.redirectTo({
								url:'/card/success/success?state=0'
							})
							return false
						}else if(res.auditState==1){
							// 审核成功
							uni.redirectTo({
								url:'/card/success/success?state=1'
							})
							return false
						}else if(res.auditState==2){
							// 审核失败
							uni.redirectTo({
								url:'/card/success/success?state=2&&msg='+res.auditFailReason
							})
						}
					}
					this.id = res.id
					this.avatar = res.avatar;
					this.realName = res.realName;
					this.jobNumber = res.jobNumber;
					this.brief = res.brief;
					this.phone = res.phone;
					this.wechat = res.wechat;
					this.wechatCode = res.wechatCode;
					this.wechatCompanyCode = res.wechatCompanyCode;
					this.email = res.email;
					this.honorImgUrls = res.honorImgUrls?res.honorImgUrls:[];
					this.styleImgUrls = res.styleImgUrls?res.styleImgUrls:[];
					this.companyName = res.companyName;
					// this.companyIntroduction = res.companyIntroduction
					this.industryName = res.industryName;
					this.tradeId = res.tradeId;
					this.address = res.address;
					this.job = res.job;
					this.morCity = [res.areaCode.substring(0,2)+'0000',res.areaCode.substring(0,4)+'00',res.areaCode]
					this.city = res.areaCodeName
					this.areaCode = this.morCity[2];
					this.latitude = res.latitude
					this.longitude = res.longitude
				}
				this.loading = false
				this.getEmploymentInfo()
			});
		},
		jumpUrl(url) {
			uni.navigateTo({
				url: url
			});
		},
		uploadImgsCopper() {
			this.copperShow = true
			let that = this
			this.$nextTick(()=>{
				that.$refs.avatar.fChooseImg(0,{
				    selWidth: "690upx", selHeight: "500upx"
				});
			})
		},
		// 裁剪完成时,返回截取图片的临时路径
        copperSuccess(tempFilePathObj) {
			let that = this
			let tempFilePath = tempFilePathObj.base64
			tempFilePath = tempFilePath.replace('data:image/png;base64,','')
			tempFilePath = tempFilePath.replace('data:image/jpeg;base64,','')
			console.log(tempFilePath)
            uni.showLoading({
            	title:'上传中'
            })
            req.postRequest('/api/nocheck/uploadBase64', {fileString:tempFilePath}, res => {
            	that.avatar = res.src;
            	uni.hideLoading()
				this.copperShow = false
            });
        },
		uploadImgs() {
			let that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: function({ tempFilePaths }) {
					uni.showLoading({
						title:'上传中'
					})
					var promise = Promise.all(
						tempFilePaths.map(tempFilePath => {
							return new Promise(function(resolve, reject) {
								req.uploadFile('/api/nocheck/upload', tempFilePath, res => {
									that.avatar = res.src;
									resolve()
								});
							});
						})
					);
					promise
						.then(function(results) {
							uni.hideLoading()
							console.log(results);
						})
						.catch(function(err) {
							uni.hideLoading()
							console.log(err);
						});
				}
			});
		},
		uploadWechat() {
			let that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: function({ tempFilePaths }) {
					uni.showLoading({
						title:'上传中'
					})
					var promise = Promise.all(
						tempFilePaths.map(tempFilePath => {
							return new Promise(function(resolve, reject) {
								console.log(tempFilePath)
								req.uploadFile('/api/nocheck/upload', tempFilePath, res => {
									that.wechatCode = res.src;
									resolve()
								});
							});
						})
					);
					promise
						.then(function(results) {
							uni.hideLoading()
							console.log(results);
						})
						.catch(function(err) {
							uni.hideLoading()
							console.log(err);
						});
				}
			});
		},
		uploadWechatCompanyCode() {
			let that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: function({ tempFilePaths }) {
					uni.showLoading({
						title:'上传中'
					})
					var promise = Promise.all(
						tempFilePaths.map(tempFilePath => {
							return new Promise(function(resolve, reject) {
								req.uploadFile('/api/nocheck/upload', tempFilePath, res => {
									that.wechatCompanyCode = res.src;
									resolve()
								});
							});
						})
					);
					promise
						.then(function(results) {
							uni.hideLoading()
							console.log(results);
						})
						.catch(function(err) {
							uni.hideLoading()
							console.log(err);
						});
				}
			});
		},
		
		uploadHonor(type,index){
			let that = this;
			uni.chooseImage({
				count: type=='change'?1:(9-that.honorImgUrls.length),
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: function({ tempFilePaths }) {
					uni.showLoading({
						title:'上传中'
					})
					var promise = Promise.all(
						tempFilePaths.map(tempFilePath => {
							return new Promise(function(resolve, reject) {
								req.uploadFile('/api/nocheck/upload', tempFilePath, res => {
									if(type=='change'){
										that.honorImgUrls[index] = res.src
										that.honorImgUrls = JSON.parse(JSON.stringify(that.honorImgUrls))
									}else{
										that.honorImgUrls = that.honorImgUrls.concat(res.src)
									}
									resolve()
								});
							});
						})
					);
					promise
						.then(function(results) {
							uni.hideLoading()
							console.log(results);
						})
						.catch(function(err) {
							uni.hideLoading()
							console.log(err);
						});
				}
			});
		},
		deleteHonor(index){
			this.honorImgUrls.splice(index,1)
		},
		
		// 个人风采
		uploadStyle(type,index){
			let that = this;
			uni.chooseImage({
				count: type=='change'?1:(9-that.styleImgUrls.length),
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: function({ tempFilePaths }) {
					uni.showLoading({
						title:'上传中'
					})
					var promise = Promise.all(
						tempFilePaths.map(tempFilePath => {
							return new Promise(function(resolve, reject) {
								req.uploadFile('/api/nocheck/upload', tempFilePath, res => {
									if(type=='change'){
										that.styleImgUrls[index] = res.src
										that.styleImgUrls = JSON.parse(JSON.stringify(that.styleImgUrls))
									}else{
										that.styleImgUrls = that.styleImgUrls.concat(res.src)
									}
									resolve()
								});
							});
						})
					);
					promise
						.then(function(results) {
							uni.hideLoading()
							console.log(results);
						})
						.catch(function(err) {
							uni.hideLoading()
							console.log(err);
						});
				}
			});
		},
		deleteStyle(index){
			this.styleImgUrls.splice(index,1)
		},
		
		intMessage(e){
			this.nums = e.detail.value.length
		},
		intWechatNumber(){
			this.wechat = this.phone
		},
		
		bindCity: function(e) {
			this.morCity = e.detail.code;
			this.city = e.detail.value.join().replace(/[,]/g, '');
			this.areaCode = e.detail.code[2];
		},
		
		bindAddressChange(data) {
			this.morCity = data.ids;
			this.city = data.data[0] + data.data[1] + data.data[2];
			this.city = this.city.replace(/\s/g,'')
			this.areaCode = data.ids[2];
		},
		chooseLocation() {
			var tha = this;
			uni.chooseLocation({
				success: function(res) {
					if (res.name) {
						tha.address = res.name;
						this.longitude = res.longitude
						this.latitude = res.latitude
						tha.reverseGeocoder(res);
						console.log('地址数据》》》：', res);
					}
				}
			});
		},
		reverseGeocoder(location) {
			// #ifdef H5
				location = location.latitude + ',' + location.longitude
				let url = 'https://apis.map.qq.com/ws/geocoder/v1/?address=';
				this.$jsonp(url, {
					key: req.public.mapLBSKEY,
					location: location,
					output: 'jsonp'
				}).then(data => {
					console.log('解析后的地址地址数据：', data);
					if(data){
						data = data.result
						this.city = data.ad_info.province+data.ad_info.city+data.ad_info.district
						this.areaCode = data.ad_info.adcode;
						this.morCity = [this.areaCode.substring(0,2)+'0000',this.areaCode.substring(0,4)+'00',this.areaCode]
						this.longitude = data.location.lng
						this.latitude = data.location.lat
					}
				}).catch(err => {
					console.log(err);
				});
			// #endif
			// #ifndef H5
				QQMapWX.initMap();
				QQMapWX.reverseGeocoder(location, data => {
					console.log('解析后的地址地址数据：', data);
					
					if(data){
						this.city = data.ad_info.province+data.ad_info.city+data.ad_info.district
						this.areaCode = data.ad_info.adcode;
						this.morCity = [this.areaCode.substring(0,2)+'0000',this.areaCode.substring(0,4)+'00',this.areaCode]
						this.longitude = data.location.lng
						this.latitude = data.location.lat
					}
				});
			//#endif
		},
		inDateChange(e){
			console.log(e.detail.value)
			this.inDate = e.detail.value
		},
		/**
		 * 提交名片
		 */
		submitCard() {
			let that = this;
			if (!this.avatar) return req.msg('请上传名片页背景');
			if (!this.realName) return req.msg('请填写你的真实姓名');
			if (!this.jobNumber) return req.msg('请填写你的工号');
			if (!this.brief) return req.msg('请填写个人简介');
			if (!this.phone) return req.msg('请填写手机号');
			// if (!this.wechat) return req.msg('请填写微信号');
			// if (!this.wechatCode) return req.msg('请上传微信二维码');
			if (!this.companyName) return req.msg('请填写公司名称');
			// if (!this.companyIntroduction) return req.msg('请填写公司简介');
			if (!this.job) return req.msg('请填写职位')
			if (!this.areaCode) return req.msg('请选择所在地区');
			if (!this.address) return req.msg('请填写详细地址');
			if (!this.inDate) return req.msg("请选择入司时间")
			var dataP = {};
			dataP.avatar = this.avatar;
			dataP.realName = this.realName;
			dataP.brief = this.brief;
			dataP.phone = this.phone;
			dataP.wechat = this.wechat;
			dataP.wechatCode = this.wechatCode;
			dataP.wechatCompanyCode = this.wechatCompanyCode;
			dataP.companyName = this.companyName;
			// dataP.companyIntroduction = this.companyIntroduction;
			dataP.job = this.employmentInfo.actrank;
			dataP.inDate = this.inDate;
			// dataP.areaCode = {
			// 	id:this.areaCode,
			// 	name :this.city
			// };
			dataP.areaCode = this.areaCode
			dataP.areaCodeName = this.city
			dataP.address = this.address;
			dataP.longitude = this.longitude;
			dataP.latitude = this.latitude;
			dataP.jobNumber = this.jobNumber;
			dataP.honorImg = this.honorImgUrls.join(',');
			dataP.styleImg = this.styleImgUrls.join(',');
			dataP.companyCode = this.companyCode
			var url = '';
			console.log(dataP)
			if (this.id) {
				dataP.id = this.id;
				uni.showModal({
					title:'提示',
					content:'重新提交将会重新审核信息，确定提交？',
					success: (con) => {
						if(con.confirm){
							req.postRequest(
								'/api/visiting/card/saveOrUpdate',
								dataP,
								json => {
									if (that.id) {
										uni.reLaunch({
											url:'/card/success/success'
										})
										// req.msg('修改成功');
										// setTimeout(function() {
										// 	uni.navigateBack({
										// 		delta: 1
										// 	});
										// }, 1500);
									} else {
										uni.reLaunch({
											url:'/card/success/success'
										})
										// req.msg('名片创建成功');
										// setTimeout(function() {
										// 	that.jumpUrl('/card/index/index');
										// }, 1500);
									}
								},
								true
							);
						}
					}
				})
			} else{
				req.postRequest(
					'/api/visiting/card/saveOrUpdate',
					dataP,
					json => {
						if (that.id) {
							uni.reLaunch({
								url:'/card/success/success'
							})
							// req.msg('修改成功');
							// setTimeout(function() {
							// 	uni.navigateBack({
							// 		delta: 1
							// 	});
							// }, 1500);
						} else {
							uni.reLaunch({
								url:'/card/success/success'
							})
							// req.msg('名片创建成功');
							// setTimeout(function() {
							// 	that.jumpUrl('/card/index/index');
							// }, 1500);
						}
					},
					true
				);
			}

			
		}
	}
};
</script>

<style>
@import './create.css';
</style>
