<!-- 新增供应商和客户 -->
<template>
	<view class="page1">
		<view class="formBox">
			<uni-forms ref="form" :modelValue="formData" :rules="rules" labelWidth="170rpx">
				<uni-forms-item label="名称" name="consigneeName">
					<uni-easyinput type="text" @blur="selectRepeat" v-model="formData.consigneeName" placeholder="请输入名称" />
					<button @tap="getUserPhone">通讯录导入</button>
				</uni-forms-item>
				<uni-forms-item label="手机号码" name="consigneeMobile">
					<uni-easyinput type="number" v-model="formData.consigneeMobile" placeholder="请输入手机号码" />
				</uni-forms-item>
				<uni-forms-item label="排序" name="orderByField">
					<uni-easyinput type="number"  v-model="formData.orderByField" placeholder="可设置排序" />
				</uni-forms-item>
				<uni-forms-item v-if="popleType == 'khName'" label="客户分类" name="consigneeMobile">
					<uni-data-select class="uni-data-select" :localdata="categoryList" v-model="formData.fenlei"
						placeholder="请选择分类" @change="categoryChange" style="width: 60%;"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item class="qichu" label="期初欠款" name="consigneeMobile" v-if="popleType == 'khName' && type!='edit'">
					<input type="number" @tap="showPrice = true" disabled v-model="formData.noEarn" placeholder="请输入客户已有欠款" style="width: 100%;height: 100%;border: 1px solid #eee;padding-left: 20rpx;"/>
				</uni-forms-item>
				<view v-if="popleType == 'khName' && type!='edit'" style="color: red;font-size:22rpx;text-align:right;margin-bottom: 20rpx;">
					*客户欠款输入正数，如有余额则此处输入负数
				</view>
				<uni-forms-item class="qichu" label="期初欠款" name="consigneeMobile" v-if="popleType == 'gysName' && type!='edit'">
					<input type="number" @tap="showPrice = true" disabled v-model="formData.noEarn" placeholder="请输入已有供应商欠款" style="width: 100%;height: 100%;border: 1px solid #eee;padding-left: 20rpx;"/>
				</uni-forms-item>
				<view v-if="popleType == 'gysName' && type!='edit'" style="color: red;font-size:22rpx;text-align:right;margin-bottom: 20rpx;">
					*供应商的欠款需输入正数，如有余额则此处输入负数
				</view>
				<uni-forms-item label="地址" name="address1">
					<view class="input selectcity" @tap="openPicker">
						<input placeholder="请选择省市区" disabled type="text" v-model="formData.address1"></input>
					</view>
				</uni-forms-item>
				<uni-forms-item label="详细地址" name="address">
					<uni-easyinput type="textarea" v-model="formData.address" />
				</uni-forms-item>
			</uni-forms>
			<view class="tui-tabbar">
				<view class="tui-btn-mr" v-if="type=='edit'" @tap.stop="del()">删除人员</view>
				<view class="tui-btn-mr" @tap.stop="submit()">提交</view>
			</view>
			<cc-selectDity :show="show" @sureSelectArea="onsetCity" @hideShow="onhideShow"></cc-selectDity>
		</view>
		<u-modal :show="delShow" :title="'删除'" :content="'是否确认删除此用户？'" showCancelButton="true" @cancel="delShow = false"
			@confirm="delItemModal"></u-modal>
		<u-keyboard ref="uKeyboard" @confirm='keyboardConfirm' @cancel="keyCancel" :defaultText="keyboardNum" @change="valChange" @backspace="backspace" :overlay='false' :closeOnClickOverlay='true' mode="price" :show="showPrice"></u-keyboard>
	</view>
</template>

<script>
	import {
		getArea
	} from '@/utils/global.js'
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				showPrice:false,
				keyboardNum:'',
				userInfo: '',
				show: false,
				categoryList:[],
				goodsNum:'',
				delShow: false,
				addressObj: {},
				type: '',
				popleType: '',
				formData: {
					consigneeMobile: '',
					consigneeName: '',
					orderByField: '',
					address1: '',
					address: '',
					province: '',
					city: '',
					area: '',
					noEarn:"",
					fenlei:'',
					fenleiName:''
				},
				// 单选数据源
				sexs: [{
					text: '男',
					value: '男'
				}, {
					text: '女',
					value: '女'
				}],
				rules: {
					consigneeName: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名',
						}]
					},
					// consigneeMobile: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入手机号',
					// 	}, {
					// 		minLength: 11,
					// 		maxLength: 11,
					// 		errorMessage: '手机号为11个字符',
					// 	}]
					// },
					// address1: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请选择地址',
					// 	}]
					// },
					// address: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入详细地址',
					// 	}]
					// },
				},
			};
		},
		computed: {
			...mapState(['shopName', 'shopIndex'])
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
		},
		onLoad(option) {
			this.popleType = option.popleType
			this.type = option.type
			this.getCategoryList()
			let data = ''
			if(option.data != undefined){
				data = option.data
			}
			data = JSON.parse(data)
			if (option.type = "edit") {
				this.formData.address1 = data.province + data.city + data.area
				this.formData.address = data.address
				this.formData.area = data.area
				this.formData.city = data.city
				this.formData.province = data.province
				this.formData.id = data.id
				this.formData.fenlei = data.categoryId
				this.formData.orderByField = data.orderByField == null ? '' : data.orderByField
				this.formData.fenleiName = data.categoryName
				this.formData.consigneeMobile = (data.consigneeMobile !='' && data.consigneeMobile !=undefined) ? data.consigneeMobile : (data.phone !='' && data.phone !=undefined)?data.phone :""
				this.formData.consigneeName = data.consigneeName || data.name || ""
			}
			
		},
		onShow(){
			uni.authorize({
			    scope: 'scope.userLocation',
			    success() {
			        
			    },fail(){
					this.tui.toast("您未授权，AI入库功能可能会出现错误")
				}
			})
		},
		methods: {
			//获取客户分类
			getCategoryList(){
				this.tui.request("/app/customerCategory/getCustomerCategoryListByShopId", "POST", {
					shopId:uni.getStorageSync('shopId')
				}, false, true).then((res) => {
					if (res.code == 200) {
						for(let i=0;i<res.result.length;i++){
							res.result[i].text = res.result[i].categoryName
							res.result[i].value = res.result[i].id
						}
						setTimeout(res1=>{
							this.categoryList = res.result
						},200)
						
					} else {
						this.tui.toast(res.message)
					}
				}).catch((res) => {})
			},
			//切换分类
			categoryChange(e) {
				if(e == ''){
					this.formData.fenlei = "";
					this.formData.fenleiName = ""
					return
				}
				for (let i = 0; i < this.categoryList.length; i++) {
					if (this.categoryList[i].value == e) {
						this.formData.fenlei = e;
						this.formData.fenleiName = this.categoryList[i].text
					}
				}
			},
			//获取手机通讯录
			getUserPhone() {
				let that = this;
				wx.chooseContact({
					success: function(res) {
						that.formData.consigneeMobile = res.phoneNumber
						that.formData.consigneeName = res.displayName
					},
					fail(res) {}
				})
			},
			keyboardConfirm(){
				if(this.keyboardNum != ''){
					this.formData.noEarn = this.keyboardNum
				}
				this.showPrice = false
				this.keyboardNum = ''
			},
			selectRepeat(e){
				var that = this;
				let url,data 
				if(this.popleType == 'khName'){
					url = '/app/customer/findByUserName'
					data = {
						userName: e.detail.value,
					}
				}else if(this.popleType == 'gysName'){
					url = '/app/supplier/getbySupplierName'
					data = {
						supplierName: e.detail.value
					}
				}
				this.tui.request(url, "post", data, false, true).then((res) => {
					if (res.code == 200) {
						if(res.result.length > 0){
							uni.showModal({
								title: "提示",
								content: "已经存在相同名称，是否继续添加？",
								success: function(res) {
									if (res.cancel) {
										that.formData.consigneeName = ""
										that.$forceUpdate()
									}
								}
							})
						}
					} else {
						
					}
				})
			},
			del() {
				this.delShow = true;
			},
			delItemModal() {
				this.delShow = false;
				if (this.popleType == "khName") {
					this.tui.request("/app/customer/delById", "post", {
						id: this.formData.id,
					}, false, true).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: "删除成功",
								icon: 'none'
							})
							uni.navigateBack()
						} else {
							uni.showToast({
								title: "删除失败",
								icon: 'none'
							})
						}
					})
				} else {
					this.tui.request("/app/supplier/delByIds", "post", {
						ids: this.formData.id,
					}, false, true).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: "删除成功",
								icon: 'none'
							})
							uni.navigateBack()
						} else {
							uni.showToast({
								title: "删除失败",
								icon: 'none'
							})
						}
					})
				}

			},
			nameBlur() {
				this.formData.username = this.formData.phone;
			},
			keyCancel(){
				this.showFu = false
				this.showPrice = false
				this.keyboardNum = ''
			},
			// 按键被点击(点击退格键不会触发此事件)
			valChange(val) {
				// 将每次按键的值拼接到value变量中，注意+=写法
				this.keyboardNum += val
			},
			// 退格键被点击
			backspace(val) {
				this.keyboardNum = val
			},
			authVerification() {
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.userLocation']) {
							/* 用户授权成功时走这里 */
							this.openPicker()
						} else if (res.authSetting['scope.userLocation'] === undefined) {
							/* 用户未授权时走这里 */
							
							this.handleOpenSetting()
						} else {
							/* 用户拒绝了授权后走这里 */
							
							this.handleOpenSetting()
						}
					},
				})
			},
			handleOpenSetting() {
				wx.openSetting({
					success: (res) => {
						
						if (res.authSetting["scope.userLocation"]) {
							this.openPicker()
						}
					}
				})
			},
			openPicker() {
				let that = this;
				uni.chooseLocation({
					latitude:'38.335974',
					longitude:'116.805783',
					success: function(res) {
						if (res.name != '') {
							let aaa = getArea(res.address)
							that.formData.province = aaa.province
							that.formData.city = aaa.city
							that.formData.area = aaa.country
							that.formData.address = aaa.address + '-' + res.name
							that.formData.address1 = aaa.province + aaa.city + aaa.country
						} else {
							that.tui.toast("微信地址选择器调用失败，请重新选择！")
						}
					},
					fail: function(res) {
						
					}
				});
			},
			// 触发提交表单
			submit() {
				let that = this;
				this.$refs.form.validate().then(res => {
					if (this.popleType == 'khName') {
						if (that.type == 'edit') {
							that.tui.request("/app/customer/edit", "post", {
								name: this.formData.consigneeName,
								phone: this.formData.consigneeMobile,
								shopId:uni.getStorageSync('shopId'),
								orderByField: Number((this.formData.orderByField == '' || this.formData.orderByField == null) ? 0 : this.formData.orderByField),
								address: this.formData.address,
								province: this.formData.province,
								city: this.formData.city,
								area: this.formData.area,
								id: this.formData.id,
								categoryId:this.formData.fenlei,
								categoryName:this.formData.fenleiName,
								userName: this.formData.consigneeMobile
							}, false, true).then((res) => {
								if (res.code == 200) {
									uni.showToast({
										title: "添加成功",
										icon: 'none'
									})
									let pages = getCurrentPages();
									let prevPage = pages[pages.length - 2];
									prevPage.$vm.popleType = 'khName'
									uni.navigateBack({
										delta: 1
									})
								} else {
									uni.showToast({
										title: "添加失败",
										icon: 'none'
									})
								}
							})
						} else {
							that.tui.request("/app/customer/save", "post", {
								name: this.formData.consigneeName,
								phone: this.formData.consigneeMobile,
								address: this.formData.address,
								orderByField: Number((this.formData.orderByField == '' || this.formData.orderByField == null) ? 0 : this.formData.orderByField),
								province: this.formData.province,
								city: this.formData.city,
								area: this.formData.area,
								categoryId:this.formData.fenlei,
								categoryName:this.formData.fenleiName,
								userName: this.formData.consigneeMobile,
								amountOwed:this.formData.noEarn
							}, false, true).then((res) => {
								if (res.code == 200) {
									uni.showToast({
										title: "添加成功",
										icon: 'none'
									})
									if(uni.getStorageSync('kaidanBack')){
										uni.removeStorageSync('kaidanBack')
										let pages = getCurrentPages();
										let prevPage = pages[pages.length - 3];
										res.result.noEarn = this.formData.noEarn == ''?'0': this.formData.noEarn
										prevPage.$vm.khName = res.result
										uni.navigateBack({
											delta: 2
										})
									}else{
										let pages = getCurrentPages();
										let prevPage = pages[pages.length - 2];
										prevPage.$vm.popleType = 'khName'
										uni.navigateBack({
											delta: 1
										})
									}
								} else {
									uni.showToast({
										title: "添加失败",
										icon: 'none'
									})
								}
							})
						}

					} else {
						if (that.type == 'edit') {
							this.formData.orderByField = Number((this.formData.orderByField == null || this.formData.orderByField == '') ? 0 : this.formData.orderByField)
							that.tui.request("/app/supplier/edit", "post", this.formData, false,
								true).then((res) => {
								if (res.code == 200) {
									uni.showToast({
										title: "修改成功",
										icon: 'none'
									})
									uni.navigateBack()
								} else {
									uni.showToast({
										title: "修改失败",
										icon: 'none'
									})
								}
							})
						} else {
							this.formData.orderByField = Number((this.formData.orderByField == null || this.formData.orderByField == '') ? 0 : this.formData.orderByField)
							that.tui.request("/app/supplier/save", "post", this.formData, false,
								true).then((res) => {
								if (res.code == 200) {
									uni.showToast({
										title: "添加成功",
										icon: 'none'
									})
									if(uni.getStorageSync('kaidanBack')){
										uni.removeStorageSync('kaidanBack')
										let pages = getCurrentPages();
										let prevPage = pages[pages.length - 3];
										res.result.noEarn = this.formData.noEarn == ''?'0':this.formData.noEarn
										prevPage.$vm.khName = res.result
										uni.navigateBack({
											delta: 2
										})
									}else{
										let pages = getCurrentPages();
										let prevPage = pages[pages.length - 2];
										prevPage.$vm.popleType = 'gysName'
										uni.navigateBack({
											delta: 1
										})
									}
								} else {
									uni.showToast({
										title: "添加失败",
										icon: 'none'
									})
								}
							})
						}
					}
				}).catch(err => {})
			}
		}
	}
</script>

<style lang="scss">
	page,.page1{
		font-size: 28rpx;
	}
	.cc_area_view {
		z-index: 997 !important;
	}

	.formBox {
		margin: 20rpx;
		padding: 20rpx;
		background-color: #fff;
	}

	.tui-tabbar {
		width: 100%;
		height: 98rpx;
		background: #fff;
		position: fixed;
		left: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		font-size: 26rpx;
		box-shadow: 0 0 1px rgba(0, 0, 0, .3);
		padding-bottom: env(safe-area-inset-bottom);
		z-index: 996;
		padding: 0 20rpx;

		.tui-btn-mr {
			width: 130rpx;
			height: 60rpx;
			background: #088FEB;
			color: #fff;
			border-radius: 10px;
			line-height: 60rpx;
			text-align: center;
			margin-right: 30rpx;
		}
	}
	button{
		height: 73rpx;
		line-height: 73rpx;
		width: 130rpx;
		font-size: 22rpx;
		padding: 0;
		margin: 0;
		background: #088FEB;
		color: #fff;
		border-radius: 0;
	}
	.qichu{
		margin-bottom: 0;
	}
</style>