<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="80" :rules="rules">
				<uv-form-item label="客户:" @click="selectShow()" prop="customerName" required>
					<uv-input disabledColor="#ffffff" :disabled="type == 'edit' ? true : false" 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 required label="商机名称:" prop="name">
					<uv-input v-model="form.name" placeholder="请输入商机名称" />
				</uv-form-item>
				<uv-form-item label="预算金额:">
					<uv-input type="number" v-model="form.money" placeholder="请输入预算金额" />
				</uv-form-item>
				<uv-form-item label="预计成交 :" @click="createTimeShow2">
					<uni-datetime-picker type="datetime" placeholder="选择预计成交" v-model="form.dealTime" />
				</uv-form-item>
				<uv-form-item label="下次跟进 :">
					<uni-datetime-picker type="datetime" placeholder="选择下次跟进" v-model="form.nextTime" />
				</uv-form-item>
				<uv-form-item label="备注:">
					<uv-textarea v-model="form.remark" placeholder="请输入备注"></uv-textarea>
				</uv-form-item>
			</uv-form>
			<!-- 产品 -->
			<view class="flex cif-title" @click="selectProduct">
				<view class="flex-1 text">产品关联</view>
				<view class="flex align-center" style="color:#2979ff">
					选择产品<uv-icon name="arrow-right" color="#909399" size="20"></uv-icon>
				</view>
			</view>
			<view class="list">
				<block v-if="selectList.length > 0">
					<view class="item" v-for="(item,index) in selectList" :key="index">
						<view class="number flex">
							<view class="flex-1">序号: {{index+1}}</view>
							<uv-number-box :min="1" v-model="item.nums" :longPress="false" @change="valChange()"></uv-number-box>
						</view>
						<view class="content flex align-center">
							<view class="flex-1 name">{{item.storeName ? item.storeName : item.name}}({{item.sku}})</view>
							<view class="price flex align-center">
								<view class="pr-1" style="font-weight: 600;">￥</view>
								<uv-input type="number" :clearable="false" placeholder="请输入价格" v-model="item.price"
									@input="inputChang" />
							</view>
						</view>
						<view class="brief flex">
							<view class="">备注：</view>
							<uv-input v-model="item.remarks" />
						</view>
						<!-- 删除按钮 -->
						<view class="close" @click="remove(index)">
							<uv-icon name="close" color="#909399" size="20"></uv-icon>
						</view>
					</view>
				</block>
				<uv-empty text="暂未选择产品" v-else margin-top="50" mode="list"></uv-empty>
			</view>
			<view class="flex mb-1 mt-1 align-center">
				<view class="mr-1" style="width:150rpx">优惠率：</view>
				<view class="flex-1"><uv-input type="number" v-model="form.discountRate" placeholder="请填写0到100的数"
						@input="inputChang" /></view>
			</view>
			<view class="flex mb-1 mt-3 align-center">
				<view class="mr-1" style="width: 150rpx">总额：</view>
				<view class="flex-1"><uv-input type="number" v-model="form.totalPrice" /></view>
			</view>
			<view class="mt-4" style="text-align: center;">
				<uv-button color="#09b4f1" @click="submit" :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.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>

	</view>
</template>

<script setup>
	import {
		ref,
		unref,
		computed
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		getCustomerListPage
	} from '@/api/customer'
	import {
		businessCreate,
		businessUpdate,
		getBusiness,
		getBusinessProductListByBusinessId
	} from '@/api/business'
	import AddressSelect from '@/components/AddressSelect/index.vue'
	import {
		formatDateTime,
		prePage
	} from '@/utils/util'
	import {
		useMainStore
	} from '@/store/store'
	import {
		storeToRefs
	} from 'pinia'
	const main = useMainStore()
	const {
		selectProductList
	} = storeToRefs(main)
	const title = ref('添加商机')
	const labelPosition = ref('left')
	const keyword = ref('')
	const listStatus = ref('loadmore')
	const customerList = ref([])
	const goodsName = ref('')
	const page = ref(1)
	const pageSize = ref(10)
	const lastPage = ref(false)
	const selectList = ref([])
	const businessData = ref({})
	const type = ref('add')
	const businessId = ref(0)
	const customerId = ref(0)
	const dealTime = ref('')
	const content = ref('')
	const customerName = ref('')
	const form = ref({
		customerId: '',
		customerName: '',
		name: '',
		nextTime: '',
		dealTime: '',
		money: '',
		remark: '',
		discountRate: '',
		totalPrice: '',
	})
	const timeText = ref('')
	const errorType = ref('message')
	const rules = ref({})

	onLoad((e) => {
		if (e.type) {
			type.value = e.type
		}
		if (type.value == "edit") {
			title.value = '编辑商机'
			businessId.value = e.id
			getBusinessInfo()
		}
		getCustomerList()
	})

	onShow(() => {
		selectList.value = selectProductList.value
		count_price()
	})

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


	// 获取商机数据详情
	const getBusinessInfo = async () => {
		form.value = await getBusiness({
			id: businessId.value
		})
		selectList.value = await getBusinessProductListByBusinessId({
			businessId: businessId.value
		})
	}
	// 搜索
	const onSearch = () => {
		page.value = 1
		lastPage.value = false
		getCustomerList()
	}

	// 去选择产品
	const selectProduct = () => {
		uni.navigateTo({
			url: '/pages/components/pages/business/selectProduct'
		});

	}

	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 = (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
		//customerId.value = val.id
		form.value.customerName = val.name ? val.name : ''
		selectShowClose()
	}
	// 产品数量增加
	const valChange = () => {
		count_price()
	}
	// 优惠率改变
	const inputChang = () => {
		count_price()
	}
	// 移除已选产品
	const remove = (i) => {
		selectList.value.splice(i, 1)
		count_price()
	}
	// 计算价格
	const count_price = () => {
		let total = 0;
		setTimeout(() => {
			for (let i = 0; i < selectList.value.length; i++) {
				total += selectList.value[i].nums * selectList.value[i].price
			}
			if (form.value.discountRate > 0) {
				total = total - (form.value.discountRate / 100) * total
			}
			form.value.totalPrice = total.toFixed(2)
		}, 500)

	}


	// 提交跟进
	const uForm = ref()
	const submit = () => {
		if (form.value.customerId == '') {
			uni.showToast({
				icon: 'error',
				title: '请选择客户'
			})

			return
		}
		if (form.value.name == '') {
			uni.showToast({
				icon: 'error',
				title: '请填写商机名称'
			})

			return
		}
		// if(selectList.value.length <= 0){
		// 	uni.showToast({
		// 		icon: 'error',
		// 		title: '请选择产品'
		// 	})

		// 	return
		// }
		onSubmit()

	}

	// 修确认提交
	const onSubmit = async () => {
		// 已选产品数据处理
		let newArr = []
		selectList.value.forEach((item, index) => {
			let obj = {}
			obj.name = item.storeName
			obj.nums = item.nums
			obj.price = item.price
			obj.productAttrUnique = item.productAttrUnique
			obj.productId = item.productId ? item.productId : item.id
			obj.sku = item.sku
			obj.remarks = item.remarks
			obj.subtotal = item.nums * item.price
			newArr[index] = obj
		})
		if (type.value == 'add') {
			form.value.businessProducts = newArr
			await businessCreate(form.value)

			uni.showToast({
				title: '添加成功',
				icon: 'success',
				duration: 2000
			})
			prePage().$vm.isRefresh = true
			setTimeout(() => {
				uni.navigateBack();
			}, 1000);
		} else {
			// selectList.value.forEach((item,index)=>{
			// 	item.subtotal = item.nums * item.price
			// })
			form.value.businessProducts = newArr
			await businessUpdate(form.value)
			uni.showToast({
				title: '修改成功',
				icon: 'success',
				duration: 2000
			})
			prePage().$vm.isRefresh = true
			setTimeout(() => {
				uni.navigateBack();
			}, 1000);
		}
	}
</script>

<style lang="scss" scoped>
	.set-box {
		padding: 0rpx 22rpx 50rpx 32rpx;

		.cif-title {
			padding: 22rpx 0;

			.text {
				font-size: 30rpx;
				font-weight: 700;
			}
		}

		.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;
					}
				}

				.brief {
					margin: 10rpx 0;
					font-size: 28rpx;
					color: $uv-tips-color;
				}

				.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;
		}
	}
</style>