<template>
	<view class="page">
		<view class="form">
			<u-form :model="form" ref="uForm">
				<u-form-item label-width="150" label="成交楼盘" prop="deal_item" required>
					<u-input placeholder="请输入成交楼盘" v-model="form.deal_item" type="text"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="成交房号" prop="house_no" required>
					<u-input placeholder="请输入成交房号" v-model="form.house_no" type="text"></u-input>
				</u-form-item>
				
				<u-form-item label-width="150" label="房屋类型" prop="house_type" required>
					<u-radio-group v-model="form.house_type" active-color="#2979ff">
						<u-radio :name="HT.val" v-for="HT in houseTypeList" :key="HT.val">{{HT.key}}</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label-width="150" label="成交店员" prop="deal_clerk" required>
					<u-input placeholder="请输入成交店员" v-model="form.deal_clerk" type="text"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="成交类型" prop="deal_type" required>
					<u-radio-group v-model="form.deal_type" active-color="#2979ff">
						<u-radio :name="DT.val" v-for="DT in dealTypeList" :key="DT.val">{{DT.key}}</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label-width="150" label="成交日期" prop="deal_at" @click.native="openDealAtPopoup" required>
					<view class="scoped-input-floor" @click.native="openDealAtPopoup"></view>
					<u-input placeholder="请选择成交日期" v-model="form.deal_at" disabled type="text"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="客户姓名" prop="customer_name" required>
					<u-input placeholder="请输入客户姓名" v-model="form.customer_name" type="text"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="手机号" prop="customer_phone" required>
					<u-input placeholder="请输入手机号" v-model="form.customer_phone" type="number"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="面积" prop="area" required>
					<u-input placeholder="请输入面积" v-model="form.area" type="text"></u-input>
					<template v-slot:right>
						㎡
					</template>
				</u-form-item>
				<u-form-item label-width="150" label="总价" prop="price" required>
					<u-input placeholder="请输入总价" v-model="form.price" type="text"></u-input>
					<template v-slot:right>
						元
					</template>
				</u-form-item>
				<u-form-item label-width="150" label="报备渠道" prop="report_dept" required>
					<u-input placeholder="请输入报备渠道" v-model="form.report_dept" type="text"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="折扣体系" prop="discount">
					<u-input placeholder="请输入折扣体系" v-model="form.discount" type="text"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="佣金" prop="brokerage">
					<u-input placeholder="请输入佣金" v-model="form.brokerage" type="text"></u-input>
				</u-form-item>
				<u-form-item label-position="top" label-width="150" label="佣金凭证" prop="brokerage_img">
					<view class="id_card" @click="uploadbrokerageImgImage">
						<u-icon v-if="form.brokerage_img == null" name="plus" size="32" color="#606266"></u-icon>
						<text v-if="form.brokerage_img == null">请先上传佣金凭证照片</text>
						<image v-if="form.brokerage_img != null" :src="brokerage_img" mode="aspectFill"></image>
					</view>
				</u-form-item>
				<u-form-item label-width="150" label="返佣" prop="rebate">
					<u-input placeholder="请输入返佣" v-model="form.rebate" type="text"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="备注信息" prop="remark" label-position="top">
					<u-input placeholder="备注信息" v-model="form.remark" type="textarea"></u-input>
				</u-form-item>
			</u-form>
			<u-gap height="60"></u-gap>
			<u-button type="primary" :diabled="submitButtonDisabled" @click="submitHandle">提交</u-button>
		</view>
		<!-- 列表选择 -->
		<u-select mode="single-column" :list="propertySelectList" v-model="propertySelectShow" @confirm="propertySelectConfirm"></u-select>
		<u-select mode="single-column" :list="salerSelectList" v-model="salerSelectShow" @confirm="salerSelectConfirm"></u-select>
		<!-- modal -->
		<u-modal v-model="submitModalShow" content="请务必仔细确认各项信息是否正确" :show-cancel-button="true" @confirm="submit()"></u-modal>
		<u-modal v-model="modalShow" :content="modalContent" :show-cancel-button="true" @cancel="modalCancel()" @confirm="modalConfirm()"></u-modal>
		<u-calendar v-model="dealAtShow" :mode="calendarMode" @change="dealAtChange"></u-calendar>
		<!-- utoast -->
		<u-toast ref="uToast" />
	</view>
</template>
<script>
export default {
	data() {
		const userInfo = uni.getStorageSync('MD_userInfo2')
		return {
			brokerage_img: '',
			dealAtShow: false,
			calendarMode: 'date',
			isEdit: false,
			form: {
				deal_item: '',
				house_no: '',
				house_type: '1',
				deal_clerk: userInfo.nickname,
				deal_type: '1',
				deal_at: '',
				customer_name: '',
				customer_phone: '',
				area: '',
				price: '',
				report_dept: '',
				discount: '',
				brokerage: '',
				rebate: '',
				brokerage_img: null,
				remark: null
			},
			submitButtonDisabled: true,
			rules: {
				deal_item: [
					{
						required: true,
						message: '成交楼盘不得为空',
						trigger: ['change', 'blur']
					},
				],
				house_no: [
					{
						required: true,
						message: '成交房号不得为空',
						trigger: ['change', 'blur']
					},
				],
				
				house_type: [
					{
						required: true,
						message: '房屋类型不得为空',
						trigger: ['change', 'blur']
					},
				],
				deal_clerk: [
					{
						required: true,
						message: '成交店员不得为空',
						trigger: ['change', 'blur']
					},
				],
				deal_type: [
					{
						required: true,
						message: '成交类型不得为空',
						trigger: ['change', 'blur']
					},
				],
				deal_at: [
					{
						required: true,
						message: '成交日期不得为空',
						trigger: ['change', 'blur']
					},
				],
				customer_name: [
					{
						required: true,
						message: '客户姓名不得为空',
						trigger: ['change', 'blur']
					},
				],
				customer_phone: [
					{
						required: true,
						message: '客户手机号不得为空',
						trigger: ['change', 'blur']
					},
					// 11个字符判断
					{
						len: 11,
						message: '手机号格式不正确',
						trigger: ['change', 'blur']
					},
				],
				area: [
					{
						required: true,
						message: '面积不得为空',
						trigger: ['change', 'blur']
					},
				],
				price: [
					{
						required: true,
						message: '总价不得为空',
						trigger: ['change', 'blur']
					},
				],
				report_dept: [
					{
						required: true,
						message: '报备渠道不得为空',
						trigger: ['change', 'blur']
					},
				],
			},
			recordLevelList: [],

			propertySelectShow: false,
			propertySelectList: [],

			salerSelectShow: false,
			salerSelectList: [],
			submitModalShow: false,
			modalShow: false,
			modalContent: '',


			houseTypeList: [],
			dealTypeList: [],
		};
	},
	onLoad(data) {
		const that = this
		const eventChannel = that.getOpenerEventChannel(); // that 需指向 this
		// 监听data事件，获取上一页面通过eventChannel.emit传送到当前页面的数据
		if (eventChannel.on) {
			eventChannel.on('data', data => {
				if (data) {
					that.form.deal_item = data.info.deal_item;
					that.form.house_no = data.info.house_no;
					that.form.house_type = data.info.house_type;
					that.form.deal_clerk = data.info.deal_clerk;
					that.form.deal_type = data.info.deal_type;
					that.form.deal_at = data.info.deal_at;
					that.form.customer_name = data.info.customer_name;
					that.form.customer_phone = data.info.customer_phone;
					that.form.area = String(data.info.area);
					that.form.price = String(data.info.price);
					that.form.report_dept = data.info.report_dept;
					that.form.discount = data.info.discount;
					that.form.brokerage = data.info.brokerage;
					that.form.rebate = data.info.rebate;
					that.brokerage_img = that.form.brokerage_img = data.info.brokerage_img;
					that.form.remark = data.info.remark;
					that.form.id = data.info.id;
					that.isEdit = true
					wx.setNavigationBarTitle({
						title: `编辑成交单-${data.info.deal_item}(${data.info.house_no})`
					})
				}
			})
		}
	},
	created () {
		const dictObj = uni.getStorageSync('MD_dict')
		this.houseTypeList = dictObj.trade_house_type || []
		this.dealTypeList = dictObj.trade_deal_type || []
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	methods: {
		uploadImgHandle (bc) {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				success: function(res) {
					const filePath = res.tempFilePaths[0];
					let token = uni.getStorageSync('MD_token') || ''
					uni.uploadFile({
						url: uni.baseUrl + 'api/upload/cloud',
						filePath,
						name: 'upload',
						formData: {
							'token': token
						},
						success: (f) => {
							const cData = JSON.parse(f.data)
							if (cData.errno === 0) {
								if (bc && typeof(bc) === 'function') bc(cData.data)
							} else {
								uni.$msg(cData.errmsg || `未知错误-${cData.errno}`)
							}
						}
					})
				}
			})
		},
		// 选择、验证、上传正面照片
		uploadbrokerageImgImage() {
			this.uploadImgHandle((d) => {
				this.form.brokerage_img = d.url
				// this.brokerage_img = d.pub_url
				this.brokerage_img = d.url
			})
		},
		openDealAtPopoup () {
			console.log('成交日期成交日期')
			this.dealAtShow = true
		},
		dealAtChange (e) {
			this.form.deal_at = e.result || ''
		},
		// 选择所属项目回调
		propertySelectConfirm(e) {
			e.map((val, index) => {
				this.form.estate_id = val.value;
				this.form.estate_name = val.label;
			});
		},
		submitHandle() {
			const that = this
			this.$refs.uForm.validate(valid => {
				if (valid) {
					// 验证成功
					let apiStr = 'apitradeadd'
					let params = {
						deal_item: that.form.deal_item,
						house_no: that.form.house_no,
						house_type: that.form.house_type,
						deal_clerk: that.form.deal_clerk,
						deal_type: that.form.deal_type,
						deal_at: that.form.deal_at,
						customer_name: that.form.customer_name,
						customer_phone: that.form.customer_phone,
						price: that.form.price,
						area: that.form.area,
						report_dept: that.form.report_dept,
						discount: that.form.discount,
						brokerage: that.form.brokerage,
						rebate: that.form.rebate,
						brokerage_img: that.form.brokerage_img,
						remark: that.form.remark
					}
					if(that.isEdit) {
						apiStr = 'apitradeedit'
						params.id = that.form.id
					}
					uni.api.cust[apiStr](params).then(res => {
						if (that.isEdit) {
							uni.$msgConfirm('编辑成功', () => {
								uni.reLaunch({
									url: '/pages/trade/list'
								})
							}, () => {
								uni.reLaunch({
									url: '/pages/trade/list'
								})
							})
						} else {
							uni.$msgConfirm('添加成功,是否前往成交单列表？', () => {
								uni.reLaunch({
									url: '/pages/trade/list'
								})
							}, () => {
								const userInfo = uni.getStorageSync('MD_userInfo2')
								this.form = {
									deal_item: '',
									house_no: '',
									house_type: '1',
									deal_clerk: userInfo.nickname,
									deal_type: '1',
									deal_at: '',
									customer_name: '',
									customer_phone: '',
									area: '',
									price: '',
									report_dept: '',
									discount: '',
									brokerage: '',
									rebate: '',
									brokerage_img: null,
									remark: null
								}
							})
						}
					})
				} else {
					console.log('验证失败');
				}
			});
		},

		// 获取手机号
		getPhoneNumber: function(e) {
			// 点击获取手机号码按钮
			let _that = this;
			if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
				_that.$refs.uToast.show({
					title: '您可以在个人设置中再次绑定',
					type: 'warning'
				});
				setTimeout(() => {
					_that.reLunchUser();
				}, 1500);
				return; // 即用户拒绝授权
			}
			console.log(e.detail.errMsg);
			console.log(e.detail.iv);
			console.log(e.detail.encryptedData);
			let iv = e.detail.iv;
			let encryptedData = e.detail.encryptedData;
			// 不是登陆完第一时间授权
			wx.login({
				success(res) {
					if (res.code) {
						// 设置用户手机号
						_that.setUserPhoneNumber(encryptedData, iv, res.code);
					} else {
						this.$refs.uToast.show({
							title: res.errMsg,
							type: 'warning'
						});
						console.log('登录失败！' + res.errMsg);
					}
				}
			});
		},
		// 以下是工具函数
		// 关闭键盘
		hideKeyboard() {
			uni.hideKeyboard();
		},
		// 格式化日期的月份或天数的显示（小于10，在前面增加0）
		getFormatDate(value) {
			if (value == undefined || value == '') {
				return '';
			}
			var str = value;
			if (parseInt(value) < 10) {
				str = '0' + value;
			}
			return str;
		}
	}
};
</script>
<style lang="scss">
.page {
	padding: 20rpx;
	background-color: #ffffff;
}

.form {
	border-radius: 10rpx;
	padding: 0 40rpx;
}

.popup-body {
	.tips-title {
		font-size: $u-p;
		margin-bottom: 20rpx;
	}

	.tips-content {
		font-size: $u-p2;
		color: $u-tips-color;
		margin-bottom: 60rpx;
	}
}

.id_card {
	color: #606266;
	width: 100%;
	height: 350rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #f4f5f6;
	font-size: $u-p2;
}

.footer {
	position: absolute;
	text-align: center;
	bottom: 40rpx;
	font-size: $u-p2;

	.agreement {
		color: $u-type-error;
	}
}

.slot-content {
	font-size: 28rpx;
	color: $u-content-color;
	padding: 20rpx;
}

.scoped-input-floor {
	position: absolute;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	background: transparent;
	z-index: 9;
}
</style>
