<template>
	<view style="background-color: #f2f2f6;padding-top: 1rpx;">
		<u-navbar title="销售" bgColor="#FD4B09" :autoBack="true" :placeholder="true" leftIconColor="#fff"
			:titleStyle="{color: '#fff'}">
			<view slot="right">
				<u-icon name="clock" size="40rpx" color="#fff" @click="historical0rders()"></u-icon>
			</view>
		</u-navbar>
		<view style="padding: 0 10rpx;width:96%;border-radius:10rpx;margin: 20rpx auto;background-color: #fff;">
			<u-cell-group :border="false">
				<u-cell icon="account" :iconStyle="{color: '#FD4B09'}" title="客户" :value="form.corpName" :isLink="true"
					@click="selectCustomer">
				</u-cell>
				
				<u-cell icon="account" :iconStyle="{color: '#FD4B09'}" title="联系人" 
					v-model="form.contacts" :isLink="true"
					@click="filterAll(['contacts','contacts'])">
				</u-cell>
				
				<view style="display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx 30rpx;
				    border-bottom: 1px solid #d6d7d9;">
					<view style="display: flex;align-items: center;color: #FD4B09;font-size: 30rpx;width: 200rpx;">
						<u-icon name="phone" color="#FD4B09"></u-icon>
						<text style="margin-left: 8rpx;">电话</text>
					</view>
					<view>
						<u-input v-model="form.phone" inputAlign="right" border="none"
						 placeholder="请填写电话"
							 disabledColor="#ffffff">
						</u-input>
					</view>
				</view>
				
				<!-- <u-cell icon="phone" :iconStyle="{color: '#FD4B09'}" title="电话" :isLink="true">
					<view slot="right-icon">
						<u-input v-model="form.phone" inputAlign="right" border="none"
						 placeholder="请填写电话"
							 disabledColor="#ffffff">
						</u-input>
					</view>
				</u-cell> -->
				
				<view style="display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx 30rpx;
				    border-bottom: 1px solid #d6d7d9;">
					<view style="display: flex;align-items: center;color: #FD4B09;font-size: 30rpx;width: 200rpx;">
						<u-icon name="map" color="#FD4B09"></u-icon>
						<text style="margin-left: 8rpx;">送货地址</text>
					</view>
					<view style="width: 90%;" >
						<u--textarea v-model="form.recAddress"
						autoHeight inputAlign="right" border="none"
						 placeholder="请填写送货地址"
							 disabledColor="#ffffff">
						</u--textarea>
					</view>
				</view>
				<!-- <u-cell icon="map" :iconStyle="{color: '#FD4B09'}" title="送货地址" :isLink="true">
					<view slot="right-icon">
						<u-input style="width: calc(100% - 400rpx);" v-model="form.recAddress" inputAlign="right" border="none"
						 placeholder="请填写送货地址"
							 disabledColor="#ffffff">
						</u-input>
					</view>
				</u-cell> -->
				
				<u-cell icon="account" :iconStyle="{color: '#FD4B09'}" title="业务员" v-model="form.salerName" :isLink="true"
					@click="filterAll(['salerName','salerId'])">
				</u-cell>
				<u-cell icon="calendar" :iconStyle="{color: '#FD4B09'}" title="日期"
					:value="form.businesDate?form.businesDate.slice(0,10):''" :isLink="true" @click="show = true">
				</u-cell>
				<u-cell icon="home" :iconStyle="{color: '#FD4B09'}" title="发货仓库" :value="form.storageName"
					:isLink="true" @click="filterAll(['storageName','storageId'])">
				</u-cell>
				
				<u-cell icon="car" :iconStyle="{color: '#FD4B09'}" title="配送方式" :value="form.select"
					:isLink="true" @click="filterAll(['select','select'])">
				</u-cell>
				<u-cell icon="home" :iconStyle="{color: '#FD4B09'}" title="物流公司" :value="form.logisticsCorpName"
					:isLink="true" @click="filterAll(['logisticsCorpName','logisticsCorpId'])">
				</u-cell>
				
				<view style="display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx 30rpx;
				    border-bottom: 1px solid #d6d7d9;">
					<view style="display: flex;align-items: center;color: #FD4B09;font-size: 30rpx;width: 200rpx;">
						<u-icon name="file-text" color="#FD4B09"></u-icon>
						<text style="margin-left: 8rpx;">物流单号</text>
					</view>
					<view>
						<u-input v-model="form.expressNo" inputAlign="right" border="none"
						 placeholder="请输入物流单号"
							 disabledColor="#ffffff">
						</u-input>
					</view>
				</view>
				
				<!-- <u-cell icon="file-text" :iconStyle="{color: '#FD4B09'}" title="物流单号" :isLink="true">
					<view slot="right-icon">
						<u-input v-model="form.expressNo" inputAlign="right" border="none"
						 placeholder="请输入物流单号"
							 disabledColor="#ffffff">
						</u-input>
					</view>
				</u-cell> -->
				
			</u-cell-group>
		</view>
		<view
			style="padding: 0 10rpx;width:96%;border-radius:10rpx;margin: 20rpx auto;background-color: #fff;padding-top: 10rpx;">
			<u-cell-group :border="false">
				<u-cell icon="list-dot" :iconStyle="{color: '#FD4B09'}"
					:title="'产品列表('+dataList.length+')   '+'    数量'+ numberAll" value="添加产品">
					<view slot="value" class="u-slot-value">
						<u-button type="primary" text="添加产品" shape="circle" size="small" color="#FD4B09" @click="selectProduct()"></u-button>
					</view>
				</u-cell>
				<u-cell v-for="(item,index) in dataList" :key="index" @click="tanchuangxgai(item,index)">
					<view slot="label">
						<!-- customStyle="margin-bottom: 10px" -->
						<u-row>
							<u-col span="2.9">
								<u--image :showLoading="true" 
								:src="item.goodsFilesList.length > 0?item.goodsFilesList[0].url:'../../../static/images/404.png'"
									width="80px" height="80px" radius="10">
								</u--image>
							</u-col>
							<u-col span="9.1">
								<!-- style="font-size: 36rpx;width: 530rpx;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;" -->
								<view style="font-size: 36rpx;" >
									{{item.cname}}
								</view>
								<view style="color: #707070;">批次号:{{item.dot}}</view>
								<view style="display: flex;justify-content: space-between;">
									<view style="color: #707070;">单价:￥{{item.price}}</view>
									<view style="color: #707070;">数量:{{item.goodsNum}}</view>
								</view>
								<view style="display: flex;justify-content: space-between;">
									<view style="color: #707070;">金额:￥{{item.amount}}</view>
									<view style="color: #707070; color: red;" @click="deleteProduct(index)">
										<u-button type="error" size="mini" text="删除"></u-button>
									</view>
								</view>
							</u-col>
						</u-row>
					</view>
				</u-cell>
			</u-cell-group>
		</view>
		<view style="width: 100%;height: 110rpx;"></view>
		<view class="submitBar">
			<view style="width: 100%;position: fixed;bottom: 0;background-color: #fff;border-top: 1rpx solid #ccc;">
				<view style="width: 100%;display: flex;font-size: 24rpx;justify-content: space-between;">
					<view style="width: 50%;display: flex;">
						<view style="margin-top: 10rpx;">
							<u-icon name="shopping-cart" color="#FD4B09" size="50"></u-icon>
						</view>
						<view style="margin-top: 40rpx;color: #000;">
							金额：<text style="color: red;">￥{{amount}}</text>
						</view>
					</view>
					<view @click="billingCollection"
						style="width: 25%;background-color: #5ac725;display: grid;justify-items: center;">
						<u-icon name="file-text" color="#fff"></u-icon>
						<view style="color: #fff;">开单并生成任务</view>
					</view>
					<view @click="saveOrder"
						style="width: 25%;background-color: #fd4b09;display: grid;justify-items: center;">
						<u-icon name="checkmark" color="#fff"></u-icon>
						<view style="color: #fff;">确认开单</view>
					</view>
				</view>
			</view>
		</view>
		
		
		<!-- 弹窗数据 -->
		<u-popup :show="popupShow" @close="popupShow = false" 
		:closeable="true" mode="center" customStyle="width: 90%;margin: 0 auto;">
			<view style="padding: 40rpx 25rpx;box-sizing: border-box;">
				<view style="text-align: center;margin: 10rpx 0;">
					<view style="font-size: 36rpx;word-break:break-all;">
						{{popupForm.cname}}
					</view>
				</view>
				<view style="width: 96%;margin: 0 auto;clear: both;">
					<u-cell-group>
						<u-cell title="单价">
							<view slot="value">
								<u--input type='number'  placeholder="请输入单价" border="none"
									inputAlign="right" v-model="popupForm.price" clearable disabledColor="#ffffff">
								</u--input>
							</view>
						</u-cell>
						<u-cell title="数量">
							<view slot="value">
								<u-number-box v-model="popupForm.goodsNum" :min="0">
								</u-number-box>
							</view>
						</u-cell>
						<u-cell title="批次号(DOT)" @click="dotClickfun">
							<view slot="value">
								<u--input border="none" inputAlign="right" v-model="popupForm.dot"
									disabled placeholder="请选择批次号" disabledColor="#ffffff"></u--input>
							</view>
						</u-cell>
						
						<u-cell title="库存">
							<view slot="value">
								{{popupForm.inventory?popupForm.inventory:'--'}}
							</view>
						</u-cell>
						<u-cell title="规格型号">
							<view slot="value">
								{{popupForm.specificationAndModel?popupForm.specificationAndModel:'--'}}
							</view>
						</u-cell>
					</u-cell-group>
				</view>
				
				<view style="margin-top: 40rpx;text-align: center;
				font-size: 32rpx;">
					<view style="display: flex; color: #fff;justify-content: space-around;">
						<view style="color: #FD4B09; border: 1rpx solid #FD4B09;
						width: 200rpx; height: 80rpx; 
						line-height: 80rpx; border-radius: 12rpx;"
							@click="popupShow = false">取消</view>
						<view style="background-color: #FF6F3B; width: 200rpx; height: 80rpx; line-height: 80rpx; border-radius: 12rpx;"
							@click="popupConserve()">保存</view>
					</view>
				</view>
			</view>
		</u-popup>
		
		<!-- 批次号弹窗 -->
		<u-picker :show="dotPickerShow" :columns="dotPickerColumns" keyName="dot"
		 @confirm="dotPickerConfirm" @cancel="dotPickerShow = false"></u-picker>
		
		
		
		<u-popup zIndex="10070" :closeOnClickOverlay="false" :show="openPopup" @close="openPopup = false,mask = false,uni.navigateBack()"
			mode="center" closeable round="10rpx">
			<u--form labelPosition="left" :labelStyle="{color: '#fd4b09'}" :model="formTwo" ref="formTwo"
				labelWidth="150rpx">
				<view style="width: calc(700rpx - 20px);margin: 10px;">
					<text>收款台</text>
					<view>
						<u-form-item label="订单金额" prop="cname" borderBottom>
							<u-input type="number" v-model="formTwo.orderAmount" border="none" inputAlign="right" placeholder="请输入"
								disabled disabledColor="#ffffff" />
						</u-form-item>
						<u-form-item label="优惠金额" prop="cname" borderBottom>
							<u-input type="number" v-model="formTwo.thisUsedProfit" 
							border="none" inputAlign="right" placeholder="请输入" disabledColor="#ffffff"
							  @blur="thisUsedProfitchange"/>
							  <!-- @blur="discount(0)" 之前的失焦事件具体干啥的我也不知道，因为他没有写注释 -->
						</u-form-item>
						<u-form-item label="应收金额" prop="cname" borderBottom>
							<u-input type="number" v-model="formTwo.debitAmount" border="none" inputAlign="right"
								placeholder="请输入" disabled disabledColor="#ffffff" />
						</u-form-item>
						<u-form-item label="已收金额" prop="cname" borderBottom>
							<u-input type="number" v-model="formTwo.settlmentAmount" border="none" inputAlign="right"
								placeholder="请输入" disabled disabledColor="#ffffff" />
						</u-form-item>
						<u-form-item label="溢付款" prop="cname" borderBottom>
							<u-input type="number" v-model="formTwo.overPayment" border="none" inputAlign="right"
								disabled disabledColor="#ffffff" />
						</u-form-item>
						<u-form-item label="会员卡金额" prop="cname" borderBottom labelWidth="190rpx" >
							<u-input type="digit" v-model="formTwo.memberAmout" border="none" inputAlign="right"
								disabledColor="#ffffff" @blur="memberBalancechange" >
									<template slot="suffix">
										<text style="margin-left: 10rpx; border-left: 1rpx solid #000;padding-left: 10rpx;">余额:{{balanceAmount}}</text>
									</template>
								</u-input>
						</u-form-item>
						<u-form-item label="本次收款" prop="cname" borderBottom>
							<u-input type="number" clearable v-model="formTwo.currentAmount" border="none"
								inputAlign="right" placeholder="请输入" disabledColor="#ffffff" @blur="discount(1)" />
						</u-form-item>
						<u-form-item label="收款日期" labelWidth="190rpx" prop="cname" borderBottom
							@click="filterAll(['advanceCollectionDate','advanceCollectionDate'])">
							<view style="width: 100%;text-align: right;">
								{{formTwo.advanceCollectionDate?formTwo.advanceCollectionDate.slice(0,10):''}}
							</view>
						</u-form-item>
						<u-form-item label="收款账户" prop="cname" borderBottom @click="filterAll(['account','account'])">
							<u-input v-model="formTwo.account" border="none" inputAlign="right" placeholder="请选择"
								disabled disabledColor="#ffffff">
								<template slot="suffix" style="text-align: center;">
									<u-icon name="plus-circle" size="18" @click.native.stop="newCompany()"></u-icon>
								</template>
							</u-input>
						</u-form-item>
						<view style="display: flex;margin-top: 20rpx;">
							<u-button text="取消" style="width: 45%;"
								@click="quxiaofun"></u-button>
							<u-button type="primary" text="收款" color="#FD4B09" style="width: 45%;"
								@click="collectionConfirm"></u-button>
						</view>
					</view>
				</view>
			</u--form>
		</u-popup>
		
		
		<u-datetime-picker :show="show" v-model="timeValue" mode="date" @confirm="confirm" @cancel="show = false">
		</u-datetime-picker>
		<u-datetime-picker :show="timeOpen" v-model="datetime" mode="date" @cancel="timeOpen = false,mask = false"
			@confirm="confirmTiem"></u-datetime-picker>
		<u-picker :show="showWarehouse" :columns="columns" :defaultIndex="defaultIndex" :keyName="keyName" @confirm="confirmWarehouse"
			@cancel="showWarehouse = false"></u-picker>
		<u-notify ref="uNotify"></u-notify>
	</view>
</template>

<script>
	import {
		queryBrand
	} from '@/api/views/stock/index.js'
	import {
		customerList,
		storageDescListAll,
		quickBilling,
		corpsDescDetail,
		corpsAddrCorpIdByAddr,
		stockDescDotList,
	
		typeSave,
		orderGenerateShipTask,
		gainUser
	} from '@/api/views/sale/index.js'
	import {
		collectPayment,getCorpDesc
	} from '@/api/views/sale/salesOrderDetails.js'
	import {
		dateFormat
	} from '@/common/dateFormat'
	export default {
		data() {
			return {
				show: false,
				timeOpen: false,
				openPopup: false,
				showWarehouse: false,
				timeValue: Number(new Date()),
				datetime: Number(new Date()),
				columns: [],
				dataList: [],
				amount: 0.00,
				numberAll: 0,
				screen: [],
				keyName: '',
				form: {
					corpId: '',
					corpName: '',
					customer: '',
					businesDate: '',
					storageName: '',
					total: 0
				},
				formTwo: {
				},
				revenueTop: 0,
				// 会员卡余额
				balanceAmount:0,
				// 业务员数据
				salesmanData:[],
				// 发货仓库的数据
				warehouseData:[],
				// 联系人数据
				contactsData:[],
				// 产品弹窗暂存的数据
				popupForm:{},
				popupIndex:0,
				popupShow:false,
				// 批次号弹窗
				dotPickerShow:false,
				dotPickerColumns:[],
				// 物流配送方式请求到的数据
				selectData:[],
				// 物流公司请求的数据
				logisticsCorpData:[],
				defaultIndex:[0],
				
			}
		},
		onLoad() {
			this.queryBrandfun()
			this.HYqueryBrandfun()
			uni.getSystemInfo({
				success: (e) => {
					this.revenueTop = e.statusBarHeight + 44
				}
			})
		},
		created() {
			// 赋值默认时间，当天时间
			this.form.businesDate = new Date((new Date()).getTime() + 8 * 60 * 60 * 1000).toJSON().split('T').join(' ').substr(0, 19);
			// 业务员
			// this.form.salesName = uni.getStorageSync('userInfo').user_id
			// this.form.sales = uni.getStorageSync('userInfo').user_name
			
			// 赋值第一项当作默认值
			storageDescListAll().then(res => {
				this.warehouseData = res.data
				if(res.data.length > 0){
					this.form.storageName = res.data[0].cname
					this.form.storageId = res.data[0].id
				}
			})
			gainUser({
				roleName:'业务员'
			}).then(res => {
				this.salesmanData = res.data
				if(res.data.length > 0){
					this.$set(this.form,'salerName',res.data[0].name)
					this.$set(this.form,'salerId',res.data[0].id)
				}
			})
		},
		methods: {
			// 优惠金额的监听
			thisUsedProfitchange(value){
				// 订单金额
				this.formTwo.orderAmount = this.formTwo.orderAmount ? Number(this.formTwo.orderAmount) : 0
				// 优惠金额
				this.formTwo.thisUsedProfit = this.formTwo.thisUsedProfit ? Number(this.formTwo.thisUsedProfit) : 0
				// 已收金额
				this.formTwo.settlmentAmount = this.formTwo.settlmentAmount ? Number(this.formTwo.settlmentAmount) : 0
				// 应收金额
				this.formTwo.debitAmount = this.formTwo.debitAmount?Number(this.formTwo.debitAmount):0
				// 会员卡金额
				this.formTwo.memberAmout = this.formTwo.memberAmout ? Number(this.formTwo.memberAmout) : 0
				if (this.formTwo.thisUsedProfit < 0) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "优惠金额不能小于零",
					})
					this.formTwo.thisUsedProfit = 0	
				}
				if (this.formTwo.thisUsedProfit > this.formTwo.orderAmount) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "优惠金额不能大于订单金额",
					})
					this.formTwo.thisUsedProfit = 0
				}
				// this.formTwo.currentAmount = 
				this.formTwo.debitAmount = this.formTwo.orderAmount - this.formTwo.thisUsedProfit
			},
			// 会员卡收款监听事件
			memberBalancechange(value){
				// 订单金额
				this.formTwo.orderAmount = this.formTwo.orderAmount ? Number(this.formTwo.orderAmount) : 0
				// 优惠金额
				this.formTwo.thisUsedProfit = this.formTwo.thisUsedProfit ? Number(this.formTwo.thisUsedProfit) : 0
				// 已收金额
				this.formTwo.settlmentAmount = this.formTwo.settlmentAmount ? Number(this.formTwo.settlmentAmount) : 0
				// 应收金额
				this.formTwo.debitAmount = this.formTwo.debitAmount?Number(this.formTwo.debitAmount):0
				// 会员卡金额
				this.formTwo.memberAmout = this.formTwo.memberAmout ? Number(this.formTwo.memberAmout) : 0
				if (this.formTwo.memberAmout < 0) {
					this.$delete(this.formTwo, 'memberAmout')
					this.$set(this.formTwo, 'memberAmout', 0)
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "会员卡金额不能小于零",
					})
					// this.formTwo.memberAmout = 0
				}
				if (this.formTwo.memberAmout >= this.balanceAmount) {
					this.$delete(this.formTwo, 'memberAmout')
					this.$set(this.formTwo, 'memberAmout', this.balanceAmount)
					// this.formTwo.memberAmout = this.balanceAmount
					this.formTwo.currentAmount = 0
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: "会员卡金额不能大于余额",
					})
				}
				const curr = this.formTwo.debitAmount - this.formTwo.settlmentAmount
				if (this.formTwo.memberAmout > curr) {
					// this.formTwo.memberAmout = curr
					this.$delete(this.formTwo, 'memberAmout')
					this.$set(this.formTwo, 'memberAmout', curr)
				}
				this.formTwo.currentAmount = this.formTwo.debitAmount - this.formTwo.settlmentAmount - this.formTwo.memberAmout
			
			},
			newCompany() {
				uni.$u.route('/pages/views/product/createCompany', {
					code: "account",
					title: "收款账户"
				});
			},
			//时间确认选择
			confirmTiem(e) {
				this.formTwo[this.screen[1]] = dateFormat(new Date(e.value), "YYYY-MM-DD HH:mm:ss")
				this.timeOpen = false
				this.mask = false
			},
			// 开单弹窗取消
			quxiaofun(){
				this.openPopup = false,
				this.mask = false,
				uni.navigateBack()
			},
			// 收款
			collectionConfirm() {
				if (!this.formTwo.orderAmount) {
					return uni.showToast({
						icon: "none",
						title: '合同金额不能为空',
						mask: true
					});
				}
				// 判断本次收款和会员卡收款不能为空
				if (!this.formTwo.currentAmount || this.formTwo.currentAmount == 0) {
					if (!this.formTwo.memberAmout || this.formTwo.memberAmout == 0) {
						return uni.showToast({
							icon: "none",
							title: '本次收款金额或会员卡金额不能为空或零',
							mask: true
						});
					}
				}
				if (!this.formTwo.account) {
					return uni.showToast({
						icon: "none",
						title: '收款帐户不能为空',
						mask: true
					});
				}
				let this_ = this
				uni.showModal({
					title: '是否确认收款',
					content: '本次收款金额' + this_.formTwo.currentAmount + '会员卡收款金额' + this_.formTwo.memberAmout,
					success: function(rest) {
						if (rest.confirm == true) {
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							collectPayment(this_.formTwo).then(res => {
								uni.showToast({
									icon: "none",
									title: '收款成功',
									mask: true,
									duration: 2000
								});
								this.openPopup = false
								setTimeout(function() {
									uni.hideLoading();
									uni.navigateBack();
								}, 2000);
							})
						}
					}
				})
			},
			//集合筛选条件
			filterAll(screen) {
				this.screen = screen
				switch (screen[1]) {
					case "account":
						this.$u.api.getWorkDicts('account').then(res => {
							this.columns = [res.data]
							this.defaultIndex = [0]
							this.keyName = "dictValue"
							this.showWarehouse = true
						})
						break;
					case "advanceCollectionDate":
						this.timeOpen = true
						this.mask = true
						break;
					case "storageId":
						this.columns = [this.warehouseData]
						this.defaultIndex = [0]
						this.keyName = 'cname'
						this.showWarehouse = true
						break;
					case "salerId":
						this.columns = [this.salesmanData]
						this.defaultIndex = [0]
						this.keyName = 'name'
						this.showWarehouse = true
						break;
					case "contacts":
						if (!this.form.corpId) return this.$refs.uNotify.show({
							top: this.revenueTop,
							type: 'warning',
							message: '请选择客户！'
						})
						this.columns = [this.contactsData]
						this.defaultIndex = [0]
						this.keyName = 'contacts'
						this.showWarehouse = true
						break;
					// 配送方式
					case "select":
						this.columns = [this.selectData]
						this.defaultIndex = [0]
						this.keyName = 'dictValue'
						this.showWarehouse = true
						break;
					// 物流公司
					case "logisticsCorpId":
						this.columns = [this.logisticsCorpData]
						this.defaultIndex = [0]
						this.keyName = 'dictValue'
						this.showWarehouse = true
						break;
				}
			},
			discount(type) {
				if (type == 0) {
					if (this.formTwo.thisUsedProfit < 0) {
						return this.formTwo.thisUsedProfit = null
					}
					this.formTwo.orderAmount = (this.formTwo.costAmount - this.formTwo.thisUsedProfit).toFixed(2)
					this.formTwo.currentAmount = this.formTwo.orderAmount
					if (this.formTwo.orderAmount < 0) {
						this.$set(this.formTwo, "orderAmount", null)
						this.$set(this.formTwo, "thisUsedProfit", null)
						uni.showToast({
							icon: "none",
							title: '优惠金额不能大于订单金额',
							mask: true
						});
					}
					if ((this.formTwo.currentAmount - this.formTwo.orderAmount) > 0) {
						this.formTwo.overPayment = (this.formTwo.currentAmount - this.formTwo.orderAmount).toFixed(2)
					} else {
						this.formTwo.overPayment = '0.00'
					}
				} else if (type == 1) {
					// 已收金额
					this.formTwo.settlmentAmount = this.formTwo.settlmentAmount ? Number(this.formTwo.settlmentAmount) : 0
					// 应收金额
					this.formTwo.debitAmount = this.formTwo.debitAmount?Number(this.formTwo.debitAmount):0
					this.formTwo.memberAmout = this.formTwo.memberAmout?Number(this.formTwo.memberAmout):0
					this.formTwo.currentAmount = this.formTwo.currentAmount?Number(this.formTwo.currentAmount):0
					console.log((this.formTwo.debitAmount - this.formTwo.settlmentAmount - this.formTwo.memberAmout),353);
					if (this.formTwo.currentAmount > (this.formTwo.debitAmount - this.formTwo.settlmentAmount - this.formTwo.memberAmout)) {
						this.$refs.uToast.show({
							type: 'error',
							icon: false,
							message: "收款和会员卡金额不能大于应收金额",
						})
						this.formTwo.currentAmount = 0
					}
					
					if (this.formTwo.currentAmount < 0) {
						return this.formTwo.currentAmount = 0
					}
				}
			},
			// 产品删除
			deleteProduct(index) {
				this.amount = Number(this.amount) - Number(this.dataList[index].amount)
				this.amount.toFixed(2)
				this.dataList.splice(index, 1)
				this.numberAll = 0
				for (let item of this.dataList) {
					this.numberAll += Number(item.goodsNum)
				}
			},
			//客户选择跳转回来触发
			otherFun(customer) {
				console.log(customer,495);
				this.form.corpName = customer.cname
				this.form.corpId = customer.id
				this.form.salerId = customer.salesmanId
				this.form.salerName = ''
				this.salesmanData.map(item=>{
					if (item.id == this.form.salerId) {
						this.form.salerName = item.name
					}
				})
				this.form.storageName = ''
				this.form.storageId = customer.deliveryWarehouseId
				this.warehouseData.map(item=>{
					if (item.id == this.form.storageId) {
						this.form.storageName = item.cname
					}
				})
				this.corpsAddrCorpIdByAddrfun()
				// corpsDescDetail({id:customer.id}).then(res=>{
				// 	console.log(res,517);
				// 	this.form.contacts = res.data.corpsAddrList[0].contacts
				// 	this.form.recAddress = res.data.corpsAddrList[0].belongtoarea + res.data.corpsAddrList[0].detailedAddress
				// 	this.form.phone =  res.data.corpsAddrList[0].tel
				// })
				
				// this.form.belongToCorpId = customer.belongtocompany
			},
			// 获取联系人数据 赋值第一项
			corpsAddrCorpIdByAddrfun(){
				corpsAddrCorpIdByAddr({
					pid:this.form.corpId
				}).then(res=>{
					this.contactsData = res.data
					this.$set(this.form,'contacts',this.contactsData[0].contacts)
					this.$set(this.form,'recAddress',this.contactsData[0].address)
					this.$set(this.form,'phone',this.contactsData[0].tel)
				})
			},
			//商品跳转选择完成返回
			getProduct(dataList) {
				this.amount = Number(this.amount)
				for (let item of dataList) {
					this.dataList.push(item)
					this.amount += Number(item.amount)
					this.numberAll += Number(item.goodsNum)
				}
				this.amount = this.amount.toFixed(2)
			},
			// 客户跳转
			selectCustomer() {
				this.$u.route('/pages/views/salesSlip/selectCustomer', {
					corpType: 'KH'
				});
			},
			historical0rders() {
				this.$u.route('/pages/views/salesSlip/salesOrderList');
			},
			// 获取物流配送方式数据
			queryBrandfun(){
				queryBrand({code:'deliveryMethod'}).then(res=>{
					this.selectData = res.data
				})
			},
			// 获取货运公司数据
			HYqueryBrandfun(){
				queryBrand({code:'tyre_express_company'}).then(res=>{
					this.logisticsCorpData = res.data
				})
			},
			// 批次号打开弹窗按钮 获取批次号数据
			dotClickfun(){
				this.dotPickerShow = true
				stockDescDotList({
					storageId: this.form.storageId,
					goodsId: this.popupForm.goodsId
				}).then(res=>{
					this.dotPickerColumns = [res.data]
				})
			},
			// 批次号弹窗的确认
			dotPickerConfirm(e){
				this.popupForm.dot = e.value[0].dot
				this.dotPickerShow = false
			},
			
			// 产品弹窗编辑
			tanchuangxgai(row,index){
				this.popupForm = row
				this.popupIndex = index
				this.popupShow = true
			},
			//修改弹窗点击保存事件
			popupConserve() {
				if (this.popupForm.whether == 1) {
					if (!this.popupForm.dot) {
						return uni.showToast({
							icon: 'none',
							title: '批次号必填',
							position: "bottom"
						})
					}
				}
				if (!this.popupForm.goodsNum) {
					return uni.showToast({
						icon: 'none',
						title: '数量不能为0',
						position: "bottom"
					})
				}
				this.popupForm.amount = (Number(this.popupForm.price) * Number(this.popupForm.goodsNum)).toFixed(2);
				this.dataList[this.popupIndex] = this.popupForm
				
				this.amount = 0
				for(let item of this.dataList) {
					this.amount = (Number(this.amount) + Number(item.amount)).toFixed(2)
				}
				uni.hideLoading();
				this.popupShow = false
			},
			
			// 添加产品跳转
			selectProduct() {
				if (!this.form.corpId) return this.$refs.uNotify.show({
					top: this.revenueTop,
					type: 'warning',
					message: '请选择客户！'
				})
				if (this.form.storageId) {
					this.$u.route('/pages/views/salesSlip/selectProduct', {
						form: JSON.stringify(this.form),
						data: JSON.stringify(this.dataList),
						corpId:this.form.corpId
					});
				} else {
					this.$refs.uNotify.show({
						top: this.revenueTop,
						type: 'warning',
						message: '请选择发货仓库！'
					})
				}
			},
			confirm(e) {
				this.show = false
				this.form.businesDate = new Date((new Date(e.value)).getTime() + 8 * 60 * 60 * 1000).toJSON().split('T')
					.join(' ').substr(0, 19)
			},
			confirmWarehouse(e) {
				if (this.screen[1] == "account") {
					this.formTwo.account = e.value[0].dictValue
					this.showWarehouse = false
				} else if(this.screen[1] == "salerId") {
					this.form.salerName = e.value[0].name
					this.form.salerId = e.value[0].id
					this.showWarehouse = false
				}else if(this.screen[1] == "contacts") {
					this.form.contacts = e.value[0].contacts
					this.form.recAddress = e.value[0].address
					this.form.phone = e.value[0].tel
					this.showWarehouse = false
				}else if(this.screen[1] == "select") {
					this.form.select = e.value[0].dictValue
					this.showWarehouse = false
				}else if(this.screen[1] == "logisticsCorpId") {
					this.form.logisticsCorpId = e.value[0].dictKey
					this.form.logisticsCorpName = e.value[0].dictValue
					this.showWarehouse = false
				} else if (this.screen[1] == "storageId") {
					this.form.storageName = e.value[0].cname
					this.form.storageId = e.value[0].id
					this.showWarehouse = false
				}else {
					console.log(123);
				}
			},
			//开单收款
			billingCollection() {
				uni.showModal({
					title: '提示',
					content: '是否要开单并生成任务',
					success: (rest)=> {
						if (rest.confirm == true) {
							this.saveOrder('生成任务')
						}
					}
				})
				
				
			},
			//保存订单
			saveOrder(zhuangtai) {
				if (!this.form.corpId) return this.$refs.uNotify.show({
					top: this.revenueTop,
					type: 'warning',
					message: '请选择客户！'
				})
				if (!this.form.businesDate) return this.$refs.uNotify.show({
					top: this.revenueTop,
					type: 'warning',
					message: '请选择日期！'
				})
				if (!this.form.storageId) return this.$refs.uNotify.show({
					top: this.revenueTop,
					type: 'warning',
					message: '请选择发货仓库！'
				})
				if (this.dataList.length == 0) return this.$refs.uNotify.show({
					top: this.revenueTop,
					type: 'warning',
					message: '请选择产品！'
				})
				// if (!this.form.select) {
				// 	return this.$refs.uNotify.show({
				// 		top: this.revenueTop,
				// 		type: 'warning',
				// 		message: '请选择配送方式！'
				// 	})
				// }
				// if (!this.form.logisticsCorpId) {
				// 	return this.$refs.uNotify.show({
				// 		top: this.revenueTop,
				// 		type: 'warning',
				// 		message: '请选择物流公司！'
				// 	})
				// }
				// if (!this.form.expressNo) {
				// 	return this.$refs.uNotify.show({
				// 		top: this.revenueTop,
				// 		type: 'warning',
				// 		message: '请输入物流单号！'
				// 	})
				// }
				let arr = this.dataList.map(item=>{
					return {
						brandId:item.brandId,
						brandName:item.brandName,
						goodsId:item.id,
						price:item.price,
						goodsName:item.cname,
						goodsNum:item.goodsNum,
						goodsNo:item.code,
						propertyName: item.specificationAndModel,
						dot:item.dot,
						whether:item.whether,
						units:item.unit,
						goodsDescription:item.goodsDescription,
						inventory:item.inventory,
						pattern:item.brandItem,
						subTotalMoney:item.goodsNum * item.price, // 小计
						remarks:item.remarks, // 备注
						dotedittype:false, // 批次号的状态
						goodsNumtype:false, // 价格数量
						pricetype:false,  // 价格
					}
				})
				let form = {
					bsType:'XS',
					businessSource:'内部销售',
					cost:'',
					freight: '',
					grossProfit:'',
					ordNo:'',
					paymentAmountTl:'',
					salesAmount:'',
					srcOrdNo:'',
					totalMoney:'',
					contacts:this.form.contacts, // 联系人
					orderItemsList:arr,
					phone:this.form.phone,// 电话
					recAddress:this.form.recAddress,// 地址
					customerId:this.form.corpId,
					businesDate:this.form.businesDate,
					receivableType:'网络支付',
					remarks:'', // 备注
					salerId:this.form.salerId,
					shipType:this.form.select,
					storageId:this.form.storageId,
					expressNo:this.form.expressNo,
					logisticsCorpId:this.form.logisticsCorpId,
					logisticsCorpName:this.form.logisticsCorpName,
					select:this.form.select
				}
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				// typeSave(暂存方法)
				quickBilling(form).then(res => {
					if(zhuangtai == '生成任务') {
						this.orderGenerateShipTaskfun(res.data)
					}else {
						uni.showToast({
							icon: "none",
							title: '开单成功',
							mask: true
						});
						setTimeout(function() {
							uni.hideLoading();
							uni.navigateBack();
						}, 1000);
					}
					
				})
			},
		
			// 生成任务接口
			orderGenerateShipTaskfun(form){
				orderGenerateShipTask({
					bsType: "XS",
					...form
				}).then(res=>{
					uni.showToast({
						icon: "none",
						title: '生成任务成功',
						mask: true
					});
					setTimeout(function() {
						uni.hideLoading();
						uni.navigateBack();
					}, 1000);
				})
			},
			
		}
	}
</script>

<style scoped>
	.submitBar {
		width: 100%;
		position: fixed;
		bottom: 0rpx;
		padding-bottom: 20rpx;
		font-size: 32rpx;
		color: #000;
		text-align: center;
		border-top: 2rpx solid #f2f2f6;
		background-color: #fff;
	}

	::v-deep .u-navbar__content {
		background-image: linear-gradient(to bottom, #FD4B09, #FF6F3B);
	}

	::v-deep .u-cell__title-text {
		color: #FD4B09;
	}
</style>
