<template>
	<view style="padding-top: 1rpx;">
		<u--form labelPosition="left" :labelStyle="{color: '#fd4b09'}" :model="form" ref="form" labelWidth="150rpx"
			style="margin-top: 10rpx;padding-bottom: 130rpx;">
			<view style="width: calc(96%);margin: 0 auto;background-color: #fff;border-radius: 20rpx;">
				<u-cell-group :border="false">
					<u-cell :border="false" center title="累计欠款" arrow-direction="down" :value="form.balanceAmount">
						<view slot="icon" style="width: 10rpx;height: 35rpx;background-color: #fd4b09;"></view>
					</u-cell>
				</u-cell-group>
				<view style="padding: 0 10rpx;">
					<u-form-item label="客户名称" prop="corpName" borderBottom>
						<u-input v-model="form.corpName" inputAlign="right" border="none" placeholder="请选择" disabled
							disabledColor="#ffffff" />
					</u-form-item>
					<u-form-item label="收款日期" prop="settlementDate" borderBottom
						@click="filterAll(['settlementDate','settlementDate'])">
						<view style="width: 100%;text-align: right;">
							{{form.settlementDate?form.settlementDate.slice(0,10):''}}
						</view>
					</u-form-item>
					<u-form-item label="收款单号" prop="sysNo" borderBottom>
						<u-input v-model="form.sysNo" border="none" inputAlign="right" disabled
							disabledColor="#ffffff" />
					</u-form-item>
					<u-form-item label="溢付款" prop="caseOverPayment" borderBottom>
						<u-input v-model="form.caseOverPayment" border="none" inputAlign="right" disabled
							disabledColor="#ffffff" />
					</u-form-item>
					<u-form-item label="收款金额" prop="amount" borderBottom>
						<u-input v-model="form.amount" border="none" inputAlign="right" placeholder="请输入"
							disabledColor="#ffffff" type="number" @blur="divideEqually" />
					</u-form-item>
					<u-form-item label="收款账户" prop="account" borderBottom @click="filterAll(['account','account'])">
						<u-input v-model="form.account" inputAlign="right" border="none" 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>
			</view>
			<view
				style="width: calc(96%);margin: 0 auto;background-color: #fff;border-radius: 20rpx;margin-top: 20rpx;">
				<u-cell-group :border="false">
					<u-cell :border="false" center title="收款列表">
						<view slot="icon" style="width: 10rpx;height: 35rpx;background-color: #fd4b09;"></view>
						<view slot="value">
							<view style="font-size: 14rpx;">未收总额￥<view
									style="display: initial;font-size: 28rpx;font-weight: bold">{{amount}}
								</view>
							</view>
						</view>
						<u-icon slot="right-icon" name="arrow-right"></u-icon>
					</u-cell>
				</u-cell-group>
				<u-checkbox-group v-model="checkboxValue" @change="checkboxChange" placement="column">
					<view class="contentBox" v-for="(item,index) in orderList" :key="index">
						<view class="textBox">
							<view>{{item.srcSysno}}</view>
							<view>
								<u-checkbox :customStyle="{marginBottom: '8px'}" :name="item.id" activeColor="#fd4b09">
								</u-checkbox>
							</view>
						</view>
						<view class="textBox">
							<view>销售金额:￥{{item.amount}}</view>
							<view>销售日期:{{item.accDate?item.accDate.slice(0,10):''}}</view>
						</view>
						<view class="textBox" style="margin-top: -10rpx;">
							<view style="margin-top: 7.5rpx;">未收金额:￥{{item.outstandingAmount}}</view>
							<view style="display: flex;">
								<u-input placeholder="请输入" type="number" @change="thisTime(item)" v-model="item.currentAmount"
									inputAlign="right" fontSize="24rpx" border="none" :customStyle="{
								width: '225rpx',
								padding: '0'
							}">
									<text slot="prefix">本次收款:￥</text>
								</u-input>
							</view>
						</view>
					</view>
				</u-checkbox-group>
			</view>
			<view
				style="width: calc(96%);margin: 0 auto;background-color: #fff;border-radius: 20rpx;margin-top: 20rpx;">
				<u-cell-group :border="false">
					<u-cell :border="false" center title="图片信息" arrow-direction="down">
						<view slot="icon" style="width: 10rpx;height: 35rpx;background-color: #fd4b09;"></view>
					</u-cell>
				</u-cell-group>
				<view style="padding: 0 10rpx;">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="10"></u-upload>
				</view>
			</view>
		</u--form>
		<view style="width: 100%;position: fixed;bottom: 0;background-color: #fff;">
			<view style="width: 100%;display: flex;font-size: 24rpx;padding-bottom: 30rpx;padding-top: 10rpx;"
				@click="submit">
				<view style="width: 96%;margin: 0 auto;">
					<view
						style="width: 100%;background-color: #fd4b09;border-radius: 100rpx;display: grid;justify-items: center;padding: 5rpx 0;">
						<u-icon name="checkmark" color="#fff"></u-icon>
						<view style="color: #fff;">确认收款</view>
					</view>
				</view>
			</view>
		</view>
		<u-datetime-picker :show="timeOpen" v-model="datetime" mode="date" @cancel="timeOpen = false"
			@confirm="confirmTiem"></u-datetime-picker>
		<u-picker :show="showOpen" :columns="columns" keyName="dictValue" @cancel="showOpen = false"
			@confirm="showPicker"></u-picker>
	</view>
</template>

<script>
	import {
		queryList,
		getSubmit
	} from '@/api/views/sale/aiiReceivables.js'
	import {
		dateFormat
	} from '@/common/dateFormat.js'
	export default {
		data() {
			return {
				form: {},
				formTwo: {},
				columns: [],
				orderList: [],
				fileList1: [],
				checkboxValue: [],
				timeOpen: false,
				showOpen: false,
				datetime: Number(new Date()),
				amount: 0,
			}
		},
		onLoad(data) {
			this.form = {
				corpName: data.corpsName,
				corpId:data.corpId,
				settlementDate: dateFormat(new Date()),
				balanceAmount: data.balanceAmount,
				srcOrderno:data.sysNo
			}
			queryList({
				corpId: data.corpId,
				billType: "XS",
				tradeType: "YPJ"
			}).then(res => {
				this.orderList = res.data
				for (let item of res.data) {
					this.amount += Number(item.outstandingAmount)
				}
				this.amount = this.amount.toFixed(2)
			})
		},
		methods: {
			newCompany() {
				uni.$u.route('/pages/views/product/createCompany',{
					code:"account",
					title:"收款账户"
				});
			},
			submit() {
				let accList = []
				for (let item of this.orderList) {
					for (let li of this.checkboxValue) {
						if(item.id == li){
							if(item.currentAmount == 0){
								return uni.showToast({
									icon: "none",
									title: '本次收款金额不能为0',
									mask: true
								});
							}
							accList.push(item)
						}
					}
				}
				if(accList.length == 0){
					return uni.showToast({
						icon: "none",
						title: '未选择收款',
						mask: true
					});
				}
				if(!this.form.account){
					return uni.showToast({
						icon: "none",
						title: '未选择收款账户',
						mask: true
					});
				}
				let this_ = this
				let form = {
					...this.form,
					dc:"D",
					itemType:"YPJ",
					billType:"D",
					filesList:this.fileList1,
					accList:accList
				}
				uni.showModal({
					title: '提示',
					content: '是否确认提交对账',
					success: function(rest) {
						if (rest.confirm == true) {
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							getSubmit(form).then(res=>{
								uni.showToast({
									icon: "none",
									title: '操作成功',
									mask: true
								});
								setTimeout(function() {
									uni.hideLoading();
									uni.navigateBack();
								}, 1500);
							})
						}
					}
				})
			},
			thisTime(item) {
				if (item.currentAmount < 0) {
					uni.showToast({
						icon: "none",
						title: '不能输入负数',
						mask: true
					});
					return item.currentAmount = 0
				}
				let amount = 0.00
				let amountTwo = 0.00
				for (let li of this.orderList) {
					amountTwo += Number(li.currentAmount)
				}
				if((Number(amountTwo) > Number(this.form.amount)) || !this.form.amount){
					this.form.amount = amountTwo
				}
				for (let li of this.orderList) {
					for(let ul of this.checkboxValue)
					if(li.id == ul){
						amount += Number(li.outstandingAmount)
					}
				}
				if(Number(this.form.amount) > Number(amount)){
					this.form.caseOverPayment = Number(this.form.amount) - Number(amount)
					this.form.caseOverPayment = this.form.caseOverPayment.toFixed(2)
				}else{
					this.form.caseOverPayment = 0.00
				}
				if (item.currentAmount) {
					for (let otem of this.checkboxValue) {
						if (otem == item.id) return
					}
					this.checkboxValue.push(item.id)
				} else {
					for (let otem in this.checkboxValue) {
						if (this.checkboxValue[otem] == item.id) return this.checkboxValue.splice(otem, 1)
					}
				}
			},
			checkboxChange(e) {
				let amount = 0.00
				if (e.length > 0) {
					for (let item of this.orderList) {
						for (let em of e) {
							if (em == item.id) {
								console.log(Number(item.currentAmount) , Number(item.outstandingAmount))
								if(Number(item.currentAmount) <= Number(item.outstandingAmount) || item.currentAmount == null){
									item.currentAmount = Number(item.outstandingAmount).toFixed(2)
								}
								if(Number(item.outstandingAmount) < Number(item.currentAmount)){
									amount += Number(item.currentAmount)
								}else{
									amount += Number(item.outstandingAmount)
								}
								break
							} else {
								item.currentAmount = null
							}
						}
					}
					// for (let li of this.orderList) {
					// 	amount += Number(li.currentAmount)
					// }
					if (this.form.amount <= Number(this.form.amount) + Number(amount).toFixed(2) || !this.form.amount) {
						this.form.amount = Number(amount).toFixed(2)
					}
					let i = 0.00
					for (let li of this.orderList) {
						for(let ul of e)
						if(li.id == ul){
							i += Number(li.outstandingAmount)
						}
					}
					if(Number(i) - Number(this.form.amount) < 0){
						this.form.caseOverPayment = Number(this.form.amount) - Number(i)
					}else{
						this.form.caseOverPayment = '0.00'
					}
				} else {
					this.form.caseOverPayment = '0.00'
					for (let item of this.orderList) {
						item.currentAmount = ''
						this.form.amount = ''
					}
				}
			},
			//平均分配
			divideEqually() {
				let amount = Number(this.form.amount)
				// if(!amount) return
				this.checkboxValue = []
				if (this.form.amount < 0) {
					uni.showToast({
						icon: "none",
						title: '不能输入负数',
						mask: true
					});
					return this.form.amount = 0
				}
				for (let item of this.orderList) {
					if (Number(amount) - Number(item.outstandingAmount) >= 0) {
						item.currentAmount = Number(item.outstandingAmount).toFixed(2)
						amount = Number(amount) - Number(item.outstandingAmount)
						this.checkboxValue.push(item.id)
					} else {
						if (amount == 0) {
							item.currentAmount = ''
						} else {
							item.currentAmount = amount.toFixed(2)
							this.checkboxValue.push(item.id)
							amount = 0
						}
					}
				}
				this.form.caseOverPayment = amount.toFixed(2)
			},
			//集合筛选条件
			filterAll(screen) {
				this.screen = screen
				switch (screen[1]) {
					case "settlementDate":
						this.timeOpen = true
						break;
					case "account":
						this.$u.api.getWorkDicts('account').then(res => {
							this.columns = [res.data]
							this.showOpen = true
						})
						break;
				}
			},
			// 下拉选择
			showPicker(e) {
				this.form[this.screen[1]] = e.value[0].dictValue
				this.showOpen = false
			},
			//时间确认选择
			confirmTiem(e) {
				this.form[this.screen[1]] = dateFormat(new Date(e.value), "YYYY-MM-DD HH:mm:ss")
				this.timeOpen = false
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						sort: this.fileList1.length,
						fileName: JSON.parse(result).data.originalName,
						url: JSON.parse(result).data.link
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: http.config.baseURL +
							'/blade-resource/oss/endpoint/put-file', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							// 客户端认证参数
							'Authorization': 'Basic ' + Base64.encode(clientId + ':' +
								clientSecret),
							'Blade-Auth': 'bearer ' + uni.getStorageSync('accessToken')
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data)
							}, 1000)
						}
					});
				})
			},
			// 删除图片
			deletePic(event) {
				let this_ = this
				uni.showModal({
					title: '提示',
					content: '是否确认删除',
					success: function(rest) {
						if (rest.confirm == true) {
							if (this_[`fileList${event.name}`][event.index].id) {
								removeFile({
									ids: this_[`fileList${event.name}`][event.index].id
								}).then(res => {
									uni.showToast({
										icon: "none",
										title: '删除成功',
										mask: true
									});
									this_[`fileList${event.name}`].splice(event.index, 1)
								})
							} else {
								uni.showToast({
									icon: "none",
									title: '删除成功',
									mask: true
								});
								this_[`fileList${event.name}`].splice(event.index, 1)
							}
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.contentBox {
		width: 96%;
		margin: 0rpx auto;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		/* box-shadow: 0 5rpx 14rpx 0 rgba(101, 176, 249, 0.42); */
		padding-top: -10rpx;
		padding-bottom: 10rpx;
	}

	.textBox {
		padding: 0 0px;
		display: flex;
		justify-content: space-between;
		font-size: 24rpx;
		margin-bottom: 10rpx;
	}

	::v-deep .u-cell__body {
		padding: 20rpx 10rpx;
	}
</style>
