<template>
	<uv-navbar :fixed="false" :title="title" left-arrow @leftClick="$onClickLeft" />
	<view style="overflow:hidden">
		<view class="set-box bg-white">
			<uv-form :model="form" ref="uForm" :errorType="errorType" labelWidth="85" :rules="rules">
				<uv-form-item label="选择客户:" @click="type !== 'detail' ? selectShow() : ''" required>
					<uv-input disabled v-model="form.customerName" placeholder="选择客户">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item label="选择合同:" @click="type !== 'detail'  ? selectShow4() : ''" required>
					<uv-input disabled v-model="form.contractName" placeholder="选择合同">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item label="回款金额:" prop="money" required>
					<uv-input @blur="moneyBlur" type="number" v-model="form.money" :disabled="isCheck" />
				</uv-form-item>
				<uv-form-item label="回款时间 :" @click="type !== 'detail'  ? createTimeShow() : ''">
					<uv-input v-model="form.returnTime" placeholder="选择回款时间 " disabled>
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item label="备注:">
					<uv-textarea v-model="form.remark" :disabled="isCheck" placeholder="请输入备注"></uv-textarea>
				</uv-form-item>
			</uv-form>
			<view class="container-item" style="flex-direction: column;align-items: flex-start;border-bottom: none;">
				<view class="container-item-upload">
					<view class="container-item-label">图片</view>
				</view>
				<view class="item-photo-list">
					<view class="item-photo-list-item" style="font-size: 0; position: relative;margin-bottom: 60rpx;"
						:style="{marginRight:(index+1)%3==0?'0rpx':'20rpx'}" v-for="(item, index) in imgFiles" :key="item"
						@click="replaceImage(item, index)">
						<image v-if="!isCheck" src="https://sys.znkjfw.com/imgs/crmimages/close.png" mode="aspectFit"
							class="item-photo-list-item-close" @click.stop="deleteItem(item, index)"></image>
						<image v-if="!isCheck" :src="item.url" mode="" style="width: 100%; height: 100%"></image>
					</view>
					<image src="http://sys.znkjfw.com/imgs/process/uploadzp.png" mode="aspectFill" class="item-photo-list-item"
						v-if="imgFiles.length<9 && !isCheck" @click="chooseImage"></image>
				</view>
			</view>
			<view class="container-item" style="flex-direction: column;align-items: flex-start;border-bottom: none;">
				<view class="container-item-upload">
					<view class="container-item-label">附件 （pdf）</view>
				</view>
				<view class="item-photo-list">
					<view class="item-photo-list-item" style="font-size: 0; position: relative;margin-bottom: 60rpx;"
						:style="{marginRight:(index+1)%3==0?'0rpx':'20rpx'}" v-for="(item, index) in pdfList" :key="item">
						<image v-if="!isCheck" src="https://sys.znkjfw.com/imgs/crmimages/close.png" mode="aspectFit"
							class="item-photo-list-item-close" @click.stop="deleteFiles(item, index)"></image>
						<image v-if="!isCheck" src="http://sys.znkjfw.com/imgs/process/pdfIcon.png" mode=""
							style="width: 100%; height: 100%">
						</image>
						<view class="item-photo-list-item-name">
							{{item.name || ''}}
						</view>
					</view>
					<image v-if="!isCheck" src="http://sys.znkjfw.com/imgs/process/uploadzp.png" mode="aspectFill"
						class="item-photo-list-item" @click="chooseFiles"></image>
				</view>
			</view>
			<view class="mt-4" style="text-align: center;">
				<uv-button color="#09b4f1" @click="submit" :disabled="isCheck || submitBtn" :ripple="true">确定提交</uv-button>
			</view>
		</view>

		<!-- 选择客户弹窗 -->
		<uv-popup mode="bottom" round="38" ref="selectShowRef">
			<view class="popup-content">
				<view class="popup-title">
					<view class="" style="width: 45px;">
					</view>
					<text class="">选择客户</text>
					<view class="" @click="selectShowClose" style="width: 45px;">
						<uv-icon name="close" color="#909399" size="30"></uv-icon>
					</view>
				</view>
				<uv-search margin="30rpx 20rpx" shape="square" v-model="keyword" :show-action="false" :clearabled="true"
					placeholder="输入客户名称搜索" @change="onSearch"></uv-search>
				<scroll-view scroll-y style="height: 760rpx;width: 100%;" @scrolltolower="reachBottom">
					<view class="list">
						<block v-if="customerList && customerList.length > 0">
							<view class="mb-4">
								<view class="item flex" v-for="(item,index) in customerList" :key="index" @click="onItem(item,index)">
									<view class="title">{{item.name}}</view>
									<view class="check-icon">
										<uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
									</view>
								</view>
							</view>
							<uv-load-more :status="listStatus"></uv-load-more>
						</block>
						<uv-empty text="暂无数据" v-else mode="list"></uv-empty>
					</view>
				</scroll-view>
			</view>
		</uv-popup>
		<uv-popup mode="bottom" round="38" ref="selectShowRef4">
			<view class="popup-content">
				<view class="popup-title">
					<view class="" style="width: 45px;">
					</view>
					<text class="">选择合同</text>
					<view class="" @click="selectShowClose4" style="width: 45px;">
						<uv-icon name="close" color="#909399" size="30"></uv-icon>
					</view>
				</view>
				<scroll-view scroll-y style="height: 760rpx;width: 100%;">
					<view class="list">
						<block v-if="businessList && businessList.length > 0">
							<view class="mb-4">
								<view class="item flex" v-for="(item,index) in businessList" :key="index" @click="onItem4(item,index)">
									<view class="title">{{item.contractName}}</view>
									<view class="check-icon">
										<uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
									</view>
								</view>
							</view>
						</block>
						<uv-empty text="暂无数据" v-else mode="list"></uv-empty>
					</view>
				</scroll-view>
			</view>
		</uv-popup>
		<uv-datetime-picker ref="datetimePicker" v-model="returnTime" mode="date"
			@confirm="createTimeChange"></uv-datetime-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		unref,
		computed
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		getCustomerListPage,
		getDictData
	} from '@/api/customer'
	import {
		getContractByCustomerId,
	} from '@/api/contract'
	import {
		getCode,
		receivablesCreate,
		getReceivables,
		receivablesUpdate,
		check
	} from '@/api/receivables'
	import {
		getSimpleUserList,
		getFlowUsers,
		getSimpleUserList2,
		uploadFile,
		deleteBpmFile
	} from '@/api/user'
	import AddressSelect from '@/components/AddressSelect/index.vue'
	import {
		formatDateTime,
		timestampToDate,
		prePage,
		getFileType
	} from '@/utils/util'
	const title = ref('添加回款')
	const labelPosition = ref('left')
	const keyword = ref('')
	const listStatus = ref('loadmore')
	const listStatus3 = ref('loadmore')
	const customerList = ref([])
	const accountName = ref('')
	const page = ref(1)
	const page3 = ref(1)
	const pageSize = ref(10)
	const lastPage = ref(false)
	const lastPage3 = ref(false)
	const selectList = ref([])
	const businessData = ref({})
	const type = ref('add')
	const contractId = ref(0)
	const customerId = ref(0)
	const nextTime = ref('')
	const returnTime = ref(timestampToDate(new Date()))
	const content = ref('')
	const customerName = ref('')
	const form = ref({
		fileItems: [],
		customerName: undefined,
		customerId: undefined,
		contractId: undefined,
		contractName: undefined,
		returnTime: timestampToDate(new Date()),
		money: 0,
		remark: undefined
	})
	const timeText = ref('')
	const errorType = ref('message')
	const rules = ref({

	})
	const customerContacts = ref([])
	const userList = ref([])
	const username = ref('')
	const keyword3 = ref('')
	const businessList = ref([])
	const isCheck = ref(false)

	const moneyBlur = () => {
		let reg = /^[0-9]*$/
		if (!reg.test(form.value.money)) {
			uni.showToast({
				icon: 'error',
				title: '金额请输入数字'
			})
			form.value.money = 0
		}
	}

	onLoad((e) => {
		type.value = e.type
		if (type.value == 'detail') {
			isCheck.value = true
			title.value = '回款详情'
			contractId.value = e.id
			getContractInfo()
		}
		getCustomerList()
		getFlowUsersList()
	})

	const getFlowUsersList = async () => {
		let data = await getFlowUsers({
			flowType: 'receivables'
		})
		let users = await getSimpleUserList2()
		let userIdArr = []
		let userArr = []
		for (var i = 0; i <= data.length; i++) {
			users.forEach((item, index) => {
				if (data[i] == item.id) {
					userIdArr.push(item.id)
					userArr.push(item.nickname)
				}
			})
		}
	}

	const getNumber = async () => {
		form.value.number = await getCode()
	}

	const selectShowRef = ref()
	const selectShow = () => {
		unref(selectShowRef).open()
	}
	const selectShowClose = () => {
		unref(selectShowRef).close()
	}

	const datetimePicker = ref()
	const createTimeShow = () => {
		unref(datetimePicker).open()
	}

	// 选择时间
	const createTimeChange = (e) => {
		form.value.returnTime = timestampToDate(e.value)
		returnTime.value = timestampToDate(e.value)
	}

	// 获取商机数据详情
	const getContractInfo = async () => {
		form.value = await getReceivables({
			id: contractId.value
		})
		if (form.value.fileItems.length) {
			form.value.fileItems.forEach(item => {
				if (getFileType(item.name) == 'image') {
					imgFiles.value.push(item)
				}
				if (getFileType(item.name) == 'pdf') {
					pdfList.value.push(item)
				}
			})
		}
		form.value.returnTime = form.value.returnTime.join("-")
		returnTime.value = form.value.returnTime
	}
	// 搜索
	const onSearch = () => {
		page.value = 1
		lastPage.value = false
		getCustomerList()
	}

	const getCustomerList = async (isNextPage, pages) => {
		await getCustomerListPage({
			pageNo: page.value,
			pageSize: pageSize.value,
			relation: 'my',
			name: keyword.value,
		}).then(res => {
			if (res) {
				// 不够一页
				if (res.list.length < 10) {
					listStatus.value = 'nomore'
				}
				// 最后一页
				if (res.list.length == 0) {
					lastPage.value = true
				}
				// 第二页开始
				if (isNextPage) {
					customerList.value = customerList.value.concat(res.list)
					return
				}
				customerList.value = res.list

				if (form.value.customerId) {
					customerList.value.forEach((item, index) => {
						if (form.value.customerId == item.id) {
							item.checked = true
							customerName.value = item.name
						} else {
							item.checked = false
						}
					})
				}
			}
		})
	}

	// 滚动到底部加载更多
	const reachBottom = () => {
		if (lastPage.value || listStatus.value == 'loading') return
		listStatus.value = 'loading'
		setTimeout(() => {
			getCustomerList(true, ++page.value)
			if (customerList.value.length >= 10) {
				listStatus.value = 'loadmore';
			} else {
				listStatus.values = 'loading';
			}
		}, 1200)
	}


	// 选择客户
	const onItem = async (val, i) => {
		customerList.value.forEach((item, index) => {
			if (val.id == item.id) {
				item.checked = true
				val.name = val.name ? val.name : item.name;
			} else {
				item.checked = false
			}
		})
		form.value.customerId = val.id
		form.value.customerName = val.name ? val.name : ''
		//根据客户查找商机
		businessList.value = await getContractByCustomerId({
			customerId: val.id
		})
		selectShowClose()
	}

	const selectShowRef4 = ref()
	const selectShow4 = async () => {
		unref(selectShowRef4).open()
	}
	const selectShowClose4 = () => {
		unref(selectShowRef4).close()
	}

	const onItem4 = async (val, i) => {
		businessList.value.forEach((item, index) => {
			if (val.id == item.id) {
				item.checked = true
				val.contractName = val.contractName ? val.contractName : item.contractName;
			} else {
				item.checked = false
			}
		})
		form.value.contractId = val.id
		form.value.contractName = val.contractName || ''
		selectShowClose4()
	}


	// 提交跟进
	const uForm = ref()
	const submit = () => {
		if (form.value.customerId == '') {
			uni.showToast({
				icon: 'error',
				title: '请选择客户'
			})
			return
		}
		if (form.value.contractName == '') {
			uni.showToast({
				icon: 'error',
				title: '请选择合同'
			})
			return
		}
		if (form.value.money == '') {
			uni.showToast({
				icon: 'error',
				title: '请填写收款金额'
			})
			return
		}
		onSubmit()
	}


	// 修确认提交
	const submitBtn = ref(false)
	const onSubmit = () => {
		uni.showLoading({
			title: '提交中'
		});
		submitBtn.value = true
		form.value.fileItems = [...imgFiles.value, ...pdfList.value]
		receivablesCreate(form.value).then(res => {
			uni.showToast({
				title: '添加成功',
				icon: 'success',
				duration: 2000
			})
			submitBtn.value = false
			uni.hideLoading();
			prePage().$vm.isRefresh = true
			setTimeout(() => {
				uni.navigateBack();
			}, 1000);
		}).catch(err => {
			submitBtn.value = false
			uni.hideLoading();
		})
	}

	// 附件上传相关
	const imgFiles = ref([]) //图片列表
	const pdfList = ref([]) //pdf列表
	//删除文件
	const deleteFiles = (val, i) => {
		deleteBpmFile({
			url: val.url
		}).then(res => {
			pdfList.value.splice(i, 1)
		})
	}
	//上传
	const uploadFileApi = (url) => {
		return new Promise((reslove, reject) => {
			uploadFile(url, true)
				.then((res) => {
					console.log(res, 'success')
					reslove(res);
				})
				.catch((err) => {
					console.log(err, 'err')
					reject(err);
				});
		});
	}
	//获取文件后缀名
	const getExtension = (fileName) => {
		let arr = fileName.split('.');
		return arr[arr.length - 1];
	}
	//选择图片
	const chooseImage = () => {
		uni.chooseImage({
			count: 9 - imgFiles.value.length, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择
			success: (res) => {
				let promise = Promise.resolve();
				let arr = [];
				uni.showLoading({
					title: '上传中'
				})

				res.tempFilePaths.forEach((item) => {
					promise = promise.then(() => uploadFileApi(item));
					promise
						.then((ress) => {
							arr.push(1)
							imgFiles.value.push({
								name: ress.name,
								url: ress.url
							})
							if (arr.length >= res.tempFilePaths.length) {
								uni.hideLoading()
							}
						})
						.catch((err) => {
							uni.hideLoading()
						});
				});
			}
		});
	}
	//上传文件 pdf
	const chooseFiles = () => {
		wx.chooseMessageFile({
			count: 9 - pdfList.value.length, //默认100
			extension: ['pdf', '.pdf'],
			success: (res) => {
				let isUploadFile = true
				res.tempFiles.forEach(item => {
					if (getExtension(item.name) != 'pdf') {
						isUploadFile = false
					}
				})
				if (!isUploadFile) {
					uni.showToast({
						title: '请您上传pdf格式文件',
					});
					return
				}
				let promise = Promise.resolve();
				let arr = [];
				uni.showLoading({
					title: '上传中'
				})

				res.tempFiles.forEach((item) => {
					promise = promise.then(() => uploadFileApi(item.path));
					promise
						.then((ress) => {
							arr.push(1)
							pdfList.value.push({
								name: ress.name,
								url: ress.url
							})
							if (arr.length >= res.tempFilePaths.length) {
								uni.hideLoading()
							}
						})
						.catch((err) => {
							uni.hideLoading()
						});
				});
			}
		});
	}
</script>

<style lang="scss" scoped>
	.set-box {
		padding: 0rpx 22rpx 40rpx 34rpx;
		margin-bottom: 80rpx;

		.list {
			margin: 40rpx 15rpx 60rpx;

			.item {
				position: relative;
				border-radius: 15rpx;
				box-shadow: 1px 0px 5px rgba(50, 50, 50, 0.3);
				padding: 25rpx 35rpx;
				margin-bottom: 45rpx;

				.number {
					margin-bottom: 20rpx;
				}

				.content {
					margin-bottom: 20rpx;

					.price {
						width: 245rpx;
						font-size: 28rpx;
						color: #fa3534;
					}
				}

				.close {
					position: absolute;
					right: -8px;
					top: -30rpx;
					background-color: #fff;
					border-radius: 50%;
					height: 60rpx;
					width: 60rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					box-shadow: 1px 0px 5px rgba(50, 50, 50, 0.3);
				}
			}

		}
	}

	.popup-content {
		.popup-title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			position: relative;
			font-size: 35rpx;
			font-weight: 600;
			text-align: center;
			height: 50px;
			padding-right: 25rpx;
		}

		.list {
			margin-bottom: 45rpx;

			.item {
				padding: 0 25rpx;
				justify-content: space-between;
				height: 45px;

				.title {
					flex: 1;
					font-size: 28rpx;
					font-weight: 600;
				}

				.check-icon {
					text-align: center;
					width: 100rpx;
				}
			}
		}

		.bottom_btn {
			display: flex;
			justify-content: flex-end;
			padding: 28rpx 10rpx 45rpx;
		}
	}

	.container-item {
		width: 100%;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #e8e8e8;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.container-item-label {
		flex-shrink: 0;
		color: #020202;
		font-weight: 400;
		font-face: PingFang SC;
		font-size: 30rpx;
		margin-right: 15rpx;
	}

	.item-photo-list {
		display: flex;
		flex-wrap: wrap;
		padding: 0 30rpx;
		margin-top: 20rpx;
	}

	.item-photo-list-item-name {
		position: absolute;
		width: 100%;
		left: 0;
		bottom: -40rpx;
		font-size: 22rpx;
		text-align: center;
		overflow: hidden;
		/* 确保超出容器的文本被裁剪 */
		white-space: nowrap;
		/* 确保文本在一行内显示 */
		text-overflow: ellipsis;
		/* 超出部分显示为省略号 */
	}

	.item-photo-list-item-close {
		width: 40rpx;
		height: 40rpx;
		position: absolute;
		right: -20rpx;
		top: -20rpx;
	}

	.item-photo-list-item {
		width: 180rpx;
		height: 180rpx;
		flex-shrink: 0;
		border: 2rpx solid #e5e5e5;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		/* margin-right: 20rpx; */
	}

	.container-item-upload {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
	}
</style>