<template>
	<view class="addCustomer-content">
		<view class="content-customerName">
			<view class="flex justify_between align_center customerName">
			<text>{{customerData?customerData.customerName:''}}</text>
				<u-button size="mini" :hair-line="false" plain type="primary" hover-class="none" @click="goBack" :custom-style="customBtnStyle">重新选择</u-button>
			</view>
		</view>
		<view class="flex_1 content-box">
			<view class="content-form">
				<u-form :model="form" ref="uForm"  label-width="180" :error-type="['toast']">
					<u-form-item label="客户地址" required >
						<u-input v-model="areaInfo.label" :disabled="true" input-align="right" placeholder="请选择客户地址" @click="openAddress"/>
						<u-icon name="arrow-right" color="#C0C4CC" slot="right"  @click="openAddress"></u-icon>
					</u-form-item>
					<u-form-item label="详细地址">
						<textarea :auto-height="true" input-align="right" placeholder="请输入详细地址(最多60个字符)" :maxlength="60" v-model="form.shippingAddress" class="receiveAddress" placeholder-style="color:#C0C4CC;font-size:28upx;"/>
					</u-form-item>
					<u-form-item label="联系人">
						<u-input v-model="form.consigneeName" input-align="right" placeholder="请输入联系人(最多30个字符)" :maxlength="11"/>
					</u-form-item>
					<u-form-item label="联系电话">
						<u-input v-model.trim="form.consigneeTel" placeholder="请输入联系电话(最多15个字符)" input-align="right" :maxlength="15"/>
					</u-form-item>
					<u-form-item label="联系手机"><u-input v-model.trim="form.contactMobile" placeholder="请输入联系手机(最多11位字符)" input-align="right" :maxlength="11"/>
					</u-form-item>
					<u-form-item label="价格类型" required >
						<v-select ref="priceType" :disabled="true" placeholder="请选择价格类型" @itemChange="chooseType" code="PRICE_TYPE" style="width: 100%"></v-select>
					</u-form-item>
					<u-form-item label="收款方式" required prop="settleStyleSn">
						<u-input v-model="settleStyleName" input-align="right" :disabled="true" placeholder="请选择收款方式" @click="showSettle=true"/>
						<u-icon name="arrow-right" color="#C0C4CC" slot="right"></u-icon>
					</u-form-item>
					<u-form-item label="铺货出库" required v-if="itemId">
						<view style="width: 100%;display:flex;justify-content: flex-end;">
						<u-radio-group v-model="form.distributionFlag" @change="radioChange" >
							<u-radio 
								v-for="(item, index) in ckList" :key="index" 
								:name="item.code"
							>
								{{item.dispName}}
							</u-radio>
						</u-radio-group>
						</view>
					</u-form-item>
					<u-form-item label="配送方式" >
						<v-select ref="dispatchType" :disabled="true" placeholder="请选择配送方式" @itemChange="choosedispatchType" code="DISPATCH_TYPE" style="width: 100%"></v-select>
					</u-form-item>
					<u-form-item label="业务员">
						<u-input v-model="userName" input-align="right" :disabled="true" placeholder="请选择业务员"  @click="showUser=true"/>
						<u-icon name="arrow-right" color="#C0C4CC" slot="right"  @click="showUser=true"></u-icon>
					</u-form-item>
					<u-form-item label="备注">
						<textarea :auto-height="true" input-align="right" placeholder="请输入备注(最多100个字符)" :maxlength="100" v-model="form.remarks" class="receiveAddress" placeholder-style="color:#C0C4CC;font-size:28upx;"/>
					</u-form-item>
				</u-form>
			</view>
			<view class="form-footer-btn">
				<u-button class="handle-btn" size="medium" shape="circle" hover-class="none" @click="handleSaveCust" :custom-style="customBtnStyle">新增销售单</u-button>
			</view>
		</view>
		<!-- 省市区 -->
		<Address ref="applyAddress" :isJrMini="false" @onConfirm="areaConfirm"></Address>
		<!-- 选择收款方式 -->
		<u-picker v-model="showSettle" title="收款方式"  @confirm="settleStyleChange" :range="settleTypeList" range-key="name" mode="selector" :default-selector="JSON.parse(JSON.stringify(defaultSettleIndex))"></u-picker>
		<!-- 客户类型 -->
		<u-picker v-model="showCust" title="客户类型" @confirm="custTypeChange" :range="custTypeList" range-key="name" mode="selector" :default-selector="JSON.parse(JSON.stringify(defaultCustIndex))"></u-picker>
		<!-- 业务员 -->
		<u-picker v-model="showUser" title="业务员" @confirm="userChange" :range="userList" range-key="name" mode="selector"></u-picker>
	</view>
</template>

<script>
	import {settleStyleQueryAll,salesSave} from '@/api/sales.js'
	import {customerDetail,custType,employeeAllList,updateByCustomerSn} from '@/api/customer.js'
	import Address from '@/components/address.vue'
	import vSelect  from  '@/components/select/v-select.vue'
	export default{
		components:{Address,vSelect},
		data(){
			return{
				title:'',
				customerData:null, // 客户信息
				priceTypeName:'', //客户类型名称
				customBtnStyle: {  //  自定义按钮样式
					margin:0
				},
				showDispatch:false,// 配送方式下拉弹窗初始值
				showSettle:false,//结算方式初始值
				settleTypeList:[],//收款方式列表
				settleStyleName:'',//收款方式名称
				custTypeList:[] ,// 客户类型数据
				showCust:false, //客户类型下拉弹窗初始值
				custTypeName:'', // 客户类型名称
				areaInfo: {},  //  省市区
				areaIdArr: [],  //  省市区id数组
				itemId:'',
				ckList:[{dispName: "是",code:1,lookupCode: "FLAG"},{dispName: "否",code:0,lookupCode: "FLAG"}],
				showUser:false,//业务员下拉框初始默认值
				userList:[], //业务员数据
				userName:'', //业务员姓名
				salesManSn:'', //业务员sn
				defaultSettleIndex:[0] ,//选中收款方式的下标
				defaultIndex:[0] ,//选中收款方式的下标
				defaultCustIndex:[0],//选中客户类型的下标
				defaultUserIndex:[0],//选中业务员的下标
				//销售单form
				form:{
					buyerName: '', // 客户名称
					buyerSn: undefined, // 客户sn
					consigneeTel: '', //  联系电话
					contactMobile: '',
					consigneeName: '', //  联系人
					shippingAddressProvinceSn: undefined, //  省
					shippingAddressProvinceName: '',
					shippingAddressCitySn: undefined, // 市
					shippingAddressCityName: '',
					shippingAddressCountySn: undefined, // 区
					shippingAddressCountyName: '',
					shippingAddress: '', //  详细地址
					fax: '', //  客户传真
					dispatchType: undefined, //  配送方式
					satelliteFlag: 0, //  是否卫星仓客户
					priceType: undefined, //  价格类型
					settleStyleSn: undefined, //  收款方式
					salesManSn: undefined, //  业务员
					salesManName: '',
					distributionFlag: '0', // 铺货出库
					salesTragetType: 'CUSTOMER',
					remarks: '' ,//  备注
					addrProvinceList:[],
					addrDistrictList:[],
					addrCityList:[]
				}
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(option) {
			console.log(option.nowId,'option')
			if(option.nowId){
				// if(option.pageType=='edit'){
				// 	uni.setNavigationBarTitle({
				// 	　　title:'编辑销售单'
				// 	})
				// }else{
				// 	uni.setNavigationBarTitle({
				// 	　　title:'新增销售单'
				// 	})
				// }
				this.itemId=option.nowId
				this.getCustomerData(this.itemId)
				this.getUserAllList()
				setTimeout(()=>{
					// 回显收款方式并下拉数据默认高亮选中
					const ind=this.settleTypeList.findIndex((item)=>{
						return item.settleStyleSn==this.customerData.settleStyleSn
					})
					console.log(ind,'ind')
					this.settleStyleName=this.settleTypeList[ind].name
					this.defaultSettleIndex=[ind]
					// 回显业务员并下拉数据默认高亮选中
					if(this.customerData.salesManSn){
						const userInd=this.userList.findIndex((item)=>{
							return item.customerSn==this.customerData.salesManSn
						})
						this.defaultUserIndex=[userInd]
						this.form.salesManName=this.userList[userInd].name
						this.form.salesManSn=this.userList[userInd].salesManSn
					}
					console.log(ind,'a',JSON.parse(JSON.stringify(this.defaultSettleIndex)) )
				},200)
			}
			this.getSettleStyle()
			this.getCustomerList()
		},
		methods:{
			getCustomerData(val){
				uni.showLoading({title:'加载中...',mask:true})
				customerDetail({id:val}).then(res=>{
					if(res.status==200){
						uni.hideLoading({})
						this.customerData=res.data
						this.areaIdArr=[this.customerData.provinceSn,this.customerData.citySn,this.customerData.countySn]
						this.areaInfo={label:this.customerData.provinceName+'-'+this.customerData.cityName+'-'+this.customerData.countyName}
						// this.setFun(res.data)
						this.form = Object.assign(this.form, {
						  buyerName: this.customerData.customerName, // 客户名称
						  buyerSn: this.customerData.customerSn, // 客户sn
						  consigneeTel: this.customerData.contactTel, //  联系电话
						  contactMobile: this.customerData.contactMobile,
						  consigneeName: this.customerData.contactName, //  联系人
						  shippingAddressProvinceSn: this.customerData.provinceSn, //  省
						  shippingAddressProvinceName: this.customerData.provinceName,
						  shippingAddressCitySn: this.customerData.citySn, // 市
						  shippingAddressCityName: this.customerData.cityName,
						  shippingAddressCountySn: this.customerData.countySn, // 区
						  shippingAddressCountyName: this.customerData.countyName,
						  shippingAddress: this.customerData.customerAddr, //  详细地址
						  fax: this.customerData.fax, //  客户传真
						  dispatchType: this.customerData.dispatchType, //  配送方式
						  satelliteFlag: this.customerData.satelliteFlag, //  是否卫星仓客户
						  priceType: this.customerData.priceType, //  价格类型
						  settleStyleSn: this.customerData.settleStyleSn //  收款方式
						})
						if(this.customerData.priceType || this.customerData.dispatchType){
							setTimeout(()=>{
								this.$refs.priceType.setVal(this.customerData.priceType)
							},200)
						}
						if(this.customerData.dispatchType){
							setTimeout(()=>{
								this.$refs.dispatchType.setVal(this.customerData.dispatchType)
							},200)
						}
						this.form=Object.assign(this.form,res.data)
					}else{
						this.customerData=null
					}
				})
			},
			// 客户信息信息更改后先保存
			handleSaveCust () {
			  const params = {
			    customerName: this.form.buyerName,
			    customerSn: this.form.buyerSn,
			    contactTel: this.form.consigneeTel, //  联系电话
			    contactMobile: this.form.contactMobile,
			    contactName: this.form.consigneeName, //  联系人
			    provinceSn: this.form.shippingAddressProvinceSn, //  省
			    provinceName: this.form.shippingAddressProvinceName,
			    citySn: this.form.shippingAddressCitySn, // 市
			    cityName: this.form.shippingAddressCityName,
			    countySn: this.form.shippingAddressCountySn, // 区
			    countyName: this.form.shippingAddressCountyName,
			    customerAddr: this.form.shippingAddress, //  详细地址
			    dispatchType: this.form.dispatchType, //  配送方式
			    priceType: this.form.priceType, //  价格类型
			    settleStyleSn: this.form.settleStyleSn //  收款方式
			  }
			  updateByCustomerSn(params).then(res => {
			    if (res.status == 200) {
			      // 保存销售单
			      this.salesSbmit()
			    } 
			  })
			},
			// 重新选择
			goBack(){
				uni.$emit('clear')
				setTimeout(()=>{
					uni.navigateBack({})
				},500)
				
			},
			radioChange(e) {
				console.log(e);
				this.form.distributionFlag=e
			},
			// 选择价格类型
			chooseType(val){
				console.log(val,'vai')
				this.form.priceType=val
			},
			// 选择配送方式
			choosedispatchType(val){
				this.form.dispatchType=val
			},
			//  选择省区市
			areaConfirm(e) {
				console.log('已选择的省市区', e)
				this.areaInfo = e
				this.areaIdArr = [ e.provinceCode, e.cityCode, e.areaCode ]
				this.form.shippingAddressProvinceSn=e.provinceCode
				this.form.shippingAddressCitySn=e.cityCode
				this.form.shippingAddressCountySn=e.areaCode
				this.form.shippingAddressProvinceName=e.labelArr[0]
				this.form.shippingAddressCityName=e.labelArr[1]
				this.form.shippingAddressCountyName=e.labelArr[2]
			},
			openAddress(){
				//  省市区  回显     参数为省市区id数组
				// console.log(this.areaIdArr,'this.areaIdArr')
				this.$refs.applyAddress.open(this.areaIdArr)
			},
			// 获取业务员列表数据
			getUserAllList () {
			  employeeAllList({}).then(res => {
			    if (res.status == 200) {
			      this.userList = res.data || []
			    } else {
			      this.userList = []
			    }
			  })
			},
			// 获取客户类型列表
			getCustomerList(){
				custType({}).then(res=>{
					if(res.status==200){
						this.custTypeList=res.data
					}else{
						this.custTypeList=[]
					}
				})
			},
			// 获取结算方式列表
			getSettleStyle(){
				settleStyleQueryAll({}).then(res=>{
					if(res.status==200){
						this.settleTypeList=res.data
					}else{
						this.settleTypeList=null
					}
				})
			},
			// 收款方式change
			settleStyleChange(e){
				console.log(e,'data')
				this.defaultSettleIndex=[e]
				this.settleStyleName=this.settleTypeList[e].name
				this.form.settleStyleSn=this.settleTypeList[e].settleStyleSn
			},
			// 客户类型change
			custTypeChange(e){
				this.defaultCustIndex=[e]
				this.custTypeName=this.custTypeList[e].name
				this.form.customerTypeSn=this.custTypeList[e].customerTypeSn
			},
			// 业务员change
			userChange(e){
				this.defaultUserIndex=[e]
				this.form.salesManName=this.userList[e].name
				this.form.salesManSn=this.userList[e].salesManSn
			},
			// 保存 (新增销售单)
			salesSbmit(){
				console.log('保存===========')
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('验证通过');
						if (this.form.customerName ==='') {
							uni.showToast({
								title: '请输入客户名称',
								icon: 'none'
							})
							return false
						}
						//  省市区
						if(this.areaIdArr.length == 0){
							uni.showToast({icon: 'none',title: '请选择省市区'})
							return
						}
						if (this.form.priceType ==undefined) {
							uni.showToast({
								title: '请选择价格类型',
								icon: 'none'
							})
							return false
						}
						if (this.form.settleStyleSn ==undefined) {
							uni.showToast({
								title: '请选择收款方式',
								icon: 'none'
							})
							return false
						}
						const params={
							buyerName:this.customerData.customerName , // 客户名称
							buyerSn: this.customerData.customerSn, // 客户sn
							consigneeTel: this.form.consigneeTel?this.form.consigneeTel: this.customerData.contactTel, //  联系电话
							contactMobile:this.form.contactMobile?this.form.contactMobile: this.customerData.contactMobile, // 联系手机
							consigneeName:this.form.consigneeName?this.form.consigneeName: this.customerData.contactName, //  联系人
							shippingAddressProvinceSn:this.form.shippingAddressProvinceSn?this.form.shippingAddressProvinceSn: this.customerData.provinceSn, //  省
							shippingAddressProvinceName:this.form.shippingAddressProvinceName?this.form.shippingAddressProvinceName: this.customerData.customerName,
							shippingAddressCitySn:this.form.shippingAddressCitySn?this.form.shippingAddressCitySn: this.customerData.citySn, // 市
							shippingAddressCityName:this.form.shippingAddressCityName?this.form.shippingAddressCityName: this.customerData.cityName,
							shippingAddressCountySn:this.form.shippingAddressCountySn?this.form.shippingAddressCountySn: this.customerData.countySn, // 区
							shippingAddressCountyName:this.form.shippingAddressCountyName?this.form.shippingAddressCountyName: this.customerData.countyName,
							shippingAddress:this.form.customerAddr?this.form.customerAddr: this.customerData.customerAddr, //  详细地址
							fax:this.form.fax?this.form.fax: this.customerData.fax, //  客户传真
							dispatchType:this.form.dispatchType?this.form.dispatchType: this.customerData.dispatchType, //  配送方式
							satelliteFlag: 0, //  是否卫星仓客户
							priceType:this.form.priceType?this.form.priceType: this.customerData.priceType, //  价格类型
							settleStyleSn:this.form.settleStyleSn?this.form.settleStyleSn: this.customerData.settleStyleSn, //  收款方式
							salesManSn:this.form.salesManSn ||undefined, //  业务员
							salesManName: '',
							distributionFlag: this.form.distributionFlag, // 铺货出库
							salesTragetType: 'CUSTOMER',
							remarks: this.remarks //  备注
						}
						console.log(params,'params')
						salesSave(params).then(res=>{
							if(res.status == 200) {
								uni.showToast({
									title: res.message,
									icon: 'none'
								})
								setTimeout(()=>{
									uni.navigateTo({
										url:'/pages/sales/edit?pageType=edit&data='+JSON.stringify(res.data)
									})
								},300)
							} 
						})
					} else {
						console.log('验证失败');
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	.addCustomer-content{
		width: 100%;
		height: 100vh;
		// background-color: #fff;
		
		display: flex;
		flex-direction: column;
		.content-customerName{
			width: 100%;
			.customerName{
				// position: fixed;
				width: 100%;
				// z-index: 999;
				color: #000000;
				font-size: 30upx;
				font-weight: 1000;
				background-color: #fff;
				padding:10upx 40upx 20upx;
			}
		}
		.content-box{
			display: flex;
			flex-direction: column;
			// margin-top: 100upx;
			padding:0 40upx;
			background-color: #fff;
		}
		.content-form{
			flex: 1;
			.receiveAddress{
				width: 100%;
				line-height: 1.5em;
				box-sizing: border-box;
				font-style: normal;
				text-align: end;
			}
		}
		.content-form:not(:last-child){
			border-bottom: none;
		}
		.form-footer-btn{
			background-color: #fff;
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			padding:0 30upx ;
			z-index: 999;
			.handle-btn{
				width: 100%;
				background-color: rgb(51, 95, 182);
				color: #fff;
			}
		}
	}
</style>
