<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="home" :iconStyle="{color: '#FD4B09'}" title="业务员" :value="form.sales" :isLink="true"
					@click="filterAll(['sales','salesName'])">
				</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-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">
					<view slot="label">
						<u-row>
							<u-col span="2.9">
								<u--image :showLoading="true" :src="item.url?item.url:'../../../static/images/404.png'"
									width="80px" height="80px" radius="10">
								</u--image>
							</u-col>
							<u-col span="9.1">
								<view
									style="font-size: 36rpx;width: 530rpx;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
									{{item.cname}}
								</view>
								<view style="display: flex;justify-content: space-between;">
									<view style="color: #707070;">单价:￥{{item.purchasePrice}}</view>
									<view style="color: #707070;">数量:{{item.storageInQuantity}}</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 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="rmb" 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 zIndex="10070" :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.purchaseAmount" 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="discount(0)"/>
						</u-form-item> -->
						<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.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>
							<u-input type="number" 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" />
						</u-form-item>
						<view style="display: flex;margin-top: 20rpx;">
							<u-button text="取消" style="width: 45%;" @click="openPopup = false,mask = false,uni.navigateBack()"></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" :keyName="keyName" @confirm="confirmWarehouse"
			@cancel="showWarehouse = false"></u-picker>
		<u-notify ref="uNotify"></u-notify>
	</view>
</template>

<script>
	import {
		customerList,
		quickBilling,
		typeSave,
		gainUser
	} from '@/api/views/sale/index.js'
	import {
		collectPayment
	} 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
			}
		},
		onLoad() {
			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
			customerList({
				size: 1,
				current: 1
			}).then(res => {
				if(res.data.records.length > 0){
					this.form.storageName = res.data.records[0].cname
					this.form.storageId = res.data.records[0].id
				}
			})
		},
		methods: {
			//时间确认选择
			confirmTiem(e) {
				this.formTwo[this.screen[1]] = dateFormat(new Date(e.value), "YYYY-MM-DD HH:mm:ss")
				this.timeOpen = false
				this.mask = false
			},
			collectionConfirm(){
				if(!this.formTwo.thisUsedProfit){
					return uni.showToast({
						icon: "none",
						title: '优惠金额不能为空',
						mask: true
					});
				}
				if(!this.formTwo.orderAmount){
					return uni.showToast({
						icon: "none",
						title: '合同金额不能为空',
						mask: true
					});
				}
				if(!this.formTwo.currentAmount){
					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,
					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.keyName = "dictValue"
							this.showWarehouse = true
						})
						break;
					case "advanceCollectionDate":
						this.timeOpen = true
						this.mask = true
						break;
					case "storageId":
						customerList({
							size: 1,
							current: 1
						}).then(request => {
							customerList({
								size: request.data.total,
								current: 1
							}).then(res => {
								this.columns = [res.data.records]
								this.keyName = 'cname'
								this.showWarehouse = true
							})
						})
						break;
					case "salesName":
						gainUser().then(res => {
							this.columns = [res.data]
							this.keyName = 'name'
							this.showWarehouse = true
						})
						break;
				}
			},
			discount(type) {
				if (type == 0) {
					if (this.formTwo.thisUsedProfit < 0) {
						return this.formTwo.thisUsedProfit = null
					}
					this.formTwo.orderAmount = (this.formTwo.purchaseAmount - this.formTwo.thisUsedProfit).toFixed(2)
					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) {
					if (this.formTwo.currentAmount < 0) {
						return this.formTwo.currentAmount = null
					}
					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'
					}
				}
			},
			deleteProduct(index) {
				this.amount = Number(this.amount) - Number(this.dataList[index].amount)
				this.numberAll = 0
				this.amount.toFixed(2)
				this.dataList.splice(index, 1)
				for (let item of this.dataList) {
					this.numberAll += Number(item.storageInQuantity)
				}
			},
			//供应商选择返回触发
			otherFun(customer) {
				this.form.corpName = customer.cname
				this.form.corpId = customer.id
				this.form.belongToCorpId = customer.belongtocompany
			},
			//商品选择返回
			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.storageInQuantity)
				}
				this.amount = this.amount.toFixed(2)
			},
			selectCustomer() {
				this.$u.route('/pages/views/purchase/selectCustomer', {
					corpType: 'GYS'
				});
			},
			historical0rders() {
				this.$u.route('/pages/views/purchase/salesOrderList');
			},
			selectProduct() {
				if (this.form.storageId) {
					this.$u.route('/pages/views/purchase/selectProduct', {
						form: JSON.stringify(this.form),
						data: JSON.stringify(this.dataList)
					});
				} 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] == "salesName") {
					this.form.sales = e.value[0].name
					this.form.salesName = e.value[0].id
					this.showWarehouse = false
				} else {
					this.form.storageName = e.value[0].cname
					this.form.storageId = e.value[0].id
					this.showWarehouse = false
				}
			},
			//采购付款
			billingCollection() {
				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: '请选择商品！'
				})
				this.form.billType = "CG";
				this.$set(this.form, "orderItemsList", this.dataList);
				let form = JSON.parse(JSON.stringify(this.form))
				delete form.corpName
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				quickBilling(form).then(res => {
					uni.showToast({
						icon: "none",
						title: '提交成功',
						mask: true
					});
					this.openPopup = true
					this.formTwo = res.data
					this.formTwo.currentAmount = (this.formTwo.orderAmount - this.formTwo.settlmentAmount).toFixed(2)
					this.formTwo.advanceCollectionDate = dateFormat(new Date(), "YYYY-MM-DD HH:mm:ss")
				})
			},
			//保存订单
			saveOrder() {
				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: '请选择商品！'
				})
				this.form.billType = "CG";
				this.$set(this.form, "orderItemsList", this.dataList);
				let form = JSON.parse(JSON.stringify(this.form))
				delete form.corpName
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				// typeSave(暂存方法)
				quickBilling(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>
