<template>
	<uv-navbar :fixed="false" :title="title" left-arrow @leftClick="$onClickLeft" />
	<view style="overflow:hidden">
		<view class="set-box bg-white">
			<uv-alert type="warning" v-if="form.checkStatus == 1" description="合同正在审核中,不可以修改!"></uv-alert>
			<uv-alert type="warning" v-else-if="form.checkStatus == 2" description="合同已经审核通过,不可以修改!"></uv-alert>
			<uv-form :model="form" ref="uForm" :errorType="errorType" labelWidth="85" :rules="rules">
				<!-- <uv-form-item required label="合同编号:" prop="contractNo">
					<uv-input v-model="form.contractNo" :disabled="isCheck" />
				</uv-form-item> -->
				<uv-form-item required label="合同名称:" prop="contractName">
					<uv-input v-model="form.contractName" :disabled="isCheck" placeholder="请输入合同名称" />
				</uv-form-item>
				<uv-form-item label="选择客户:" @click="type !== 'detail' ? selectShow() : ''" prop="customerName" required>
					<uv-input disabledColor="#ffffff" disabled="true" 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() : ''">
					<uv-input disabledColor="#ffffff" disabled v-model="form.businessName" placeholder="选择商机">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item label="合同金额:" prop="contractMoney" required>
					<uv-input type="number" v-model="form.contractMoney" :disabled="isCheck" placeholder="请输入合同金额" />
				</uv-form-item>
				<uv-form-item label="签约时间 :" @click="type !== 'detail'  ? createTimeShow() : ''">
					<uv-input v-model="form.signingDate" placeholder="选择签约时间 " disabled disabledColor="#ffffff">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item label="开始时间 :" @click="type !== 'detail'  ? createTimeShow2() : ''">
					<uv-input v-model="form.startDate" placeholder="选择开始时间 " disabled disabledColor="#ffffff">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item label="结束时间 :" @click="type !== 'detail'  ? createTimeShow3() : ''">
					<uv-input v-model="form.endDate" placeholder="选择结束时间 " disabled disabledColor="#ffffff">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item label="客户签约人:" @click="type !== 'detail'  ? selectShow2() : ''" required>
					<uv-input disabledColor="#ffffff" disabled v-model="form.contactsName" 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'  ? selectShow6() : ''" required>
					<uv-input disabledColor="#ffffff" disabled v-model="form.companyName" 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'  ? selectShow3() : ''" required>
					<uv-input disabledColor="#ffffff" disabled v-model="form.signatoryName" placeholder="选择签约人">
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
			</uv-form>
			<!-- 产品 -->
			<view class="flex cif-title" @click="type !== 'detail' ? 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>
							<uni-number-box :min="1" v-model="item.nums" @change="valChange" :disabled="isCheck" />
						</view>
						<view class="content flex align-center">
							<view class="flex-1 storeName">{{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 :disabled="true" type="number" :clearable="false" placeholder="请输入价格" v-model="item.price" />
							</view>
						</view>
						<view class="brief flex align-center">
							<view style="margin-right: 14rpx;">备注:</view>
							<uv-input v-model="item.remarks" :disabled="isCheck" />
						</view>
						<!-- 删除按钮 -->
						<view class="close" @click="type !== 'detail'  ? 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">
					<uni-easyinput type="number" :disabled="isCheck" placeholder="请填写优惠金额" @blur="inputChang"
						v-model="form.discountRate"></uni-easyinput>
				</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" :disabled="true" /></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">图片</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="24"></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>
		<uv-popup mode="bottom" round="38" ref="selectShowRef2">
			<view class="popup-content">
				<view class="popup-title">
					<view class="" style="width: 45px;">
					</view>
					<text class="">选择客户签约人</text>
					<view class="" @click="selectShowClose2" style="width: 45px;">
						<uv-icon name="close" color="#909399" size="24"></uv-icon>
					</view>
				</view>
				<scroll-view scroll-y style="height: 760rpx;width: 100%;">
					<view class="list">
						<block v-if="customerContacts.length > 0">
							<view class="mb-4">
								<view class="item flex" v-for="(item,index) in customerContacts" :key="index"
									@click="onItem2(item,index)">
									<view class="title">{{item.customerName}}</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-popup mode="bottom" round="38" ref="selectShowRef3">
			<view class="popup-content">
				<view class="popup-title">
					<view class="" style="width: 45px;">
					</view>
					<text class="">选择公司签约人</text>
					<view class="" @click="selectShowClose3" style="width: 45px;">
						<uv-icon name="close" color="#909399" size="24"></uv-icon>
					</view>
				</view>
				<uv-search margin="10rpx 26rpx 30rpx 26rpx" shape="square" v-model="keyword3" :show-action="false"
					:clearabled="true" placeholder="输入用户名称搜索" @change="onSearch3"></uv-search>
				<scroll-view scroll-y style="height: 760rpx;width: 100%;">
					<view class="list">
						<block v-if="userList.length > 0">
							<view class="mb-4">
								<view class="item flex" v-for="(item,index) in userList" :key="index" @click="onItem3(item,index)">
									<view class="title">{{item.nickname}}</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="listStatus3"></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="24"></uv-icon>
					</view>
				</view>
				<scroll-view scroll-y style="height: 760rpx;width: 100%;">
					<view class="list">
						<block v-if="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.name}}</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-popup mode="bottom" round="38" ref="selectShowRef6">
			<view class="popup-content">
				<view class="popup-title">
					<view class="" style="width: 45px;">
					</view>
					<text class="">选择签约公司</text>
					<view class="" @click="selectShowClose6" style="width: 45px;">
						<uv-icon name="close" color="#909399" size="24"></uv-icon>
					</view>
				</view>
				<scroll-view scroll-y style="height: 760rpx;width: 100%;">
					<view class="list">
						<block v-if="companyList.length > 0">
							<view class="mb-4">
								<view class="item flex" v-for="(item,index) in companyList" :key="index" @click="onItem6(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>
						</block>
						<uv-empty text="暂无数据" v-else mode="list"></uv-empty>
					</view>
				</scroll-view>
			</view>
		</uv-popup>

		<uv-datetime-picker ref="datetimePicker" v-model="signingDateValue" mode="date"
			@confirm="createTimeChange"></uv-datetime-picker>
		<uv-datetime-picker ref="datetimePicker2" v-model="startDateValue" mode="date"
			@confirm="createTimeChange2"></uv-datetime-picker>
		<uv-datetime-picker ref="datetimePicker3" v-model="endDateValue" mode="date"
			@confirm="createTimeChange3"></uv-datetime-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		unref,
		computed
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		getCustomerListPage,
		getContactsPage
	} from '@/api/customer'
	import {
		getBusinessProductListByBusinessId,
		getBusinessPage
	} from '@/api/business'
	import {
		getContractNo,
		createContract,
		getContract,
		getContractProductListByContractId,
		updateContract,
		check,
		getCompanyDept,
		createOAContract,
		getOAContract
	} from '@/api/contract'
	import {
		getSimpleUserList,
		getFlowUsers,
		getSimpleUserList2,
		getAllUserList,
		uploadFile,
		deleteBpmFile
	} from '@/api/user'
	import AddressSelect from '@/components/AddressSelect/index.vue'
	import {
		timestampToDate,
		prePage,
		getFileType
	} from '@/utils/util'
	import {
		useMainStore
	} from '@/store/store'
	import {
		storeToRefs
	} from 'pinia'
	import {
		deepClone
	} from '../../../../uni_modules/uv-ui-tools/libs/function'
	const main = useMainStore()
	const {
		selectProductList
	} = storeToRefs(main)
	const title = ref('添加合同')
	const labelPosition = ref('left')
	const keyword = ref('')
	const listStatus = ref('loadmore')
	const listStatus3 = ref('loadmore')
	const customerList = ref([])
	const goodsName = ref('')
	const page = ref(1)
	const page3 = ref(1)
	const pageSize = ref(15)
	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 content = ref('')
	const customerName = ref('')
	const form = ref({
		fileItems: [], //附件
		contractType: 1, //	合同类型
		contractNo: '', //合同编号
		contractName: '', //合同名称
		customerId: '', //客户ID
		customerName: '', //客户名称
		startDate: timestampToDate(new Date()), //开始时间
		signingDate: timestampToDate(new Date()), //签约日期
		endDate: timestampToDate(new Date()), //结束时间
		remark: '', //备注
		discountRate: 0, //整单折扣
		totalPrice: 0, //产品总金额
		contactsName: '', //客户签约人
		contactsId: '', //签约人id
		companyId: '', //签约公司编号
		companyName: '', //签约公司名称
		businessId: '', //商机ID
		invoiceMoney: '', //	已开票金额
		contractMoney: '', //	合同金额
		signatoryId: '', //	签约人编号
		signatoryName: '', //	签约人名称
	})
	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)

	onLoad((e) => {
		type.value = e.type
		if (type.value == 'detail') {
			isCheck.value = true
			title.value = '合同详情'
			contractId.value = e.id
			getContractInfo()
		}
		getUserList() //获取签约人
		getCustomerList()
		getCompanyList() //获取公司列表
	})

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

	// 附件上传相关
	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()
						});
				});
			}
		});
	}


	//获取公司列表
	const companyList = ref([])
	const getCompanyList = async () => {
		companyList.value = await getCompanyDept()
		if (form.value.companyId) {
			companyList.value.forEach((item, index) => {
				if (form.value.companyId == item.id) {
					item.checked = true
				} else {
					item.checked = false
				}
			})
		}
	}


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

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

	// 选择时间
	const signingDateValue = ref(timestampToDate(new Date()))
	const createTimeChange = (e) => {
		form.value.signingDate = timestampToDate(e.value)
	}

	const datetimePicker2 = ref()
	const createTimeShow2 = () => {
		unref(datetimePicker2).open()
	}

	// 选择时间
	const startDateValue = ref(timestampToDate(new Date()))
	const createTimeChange2 = (e) => {
		form.value.startDate = timestampToDate(e.value)
		if (form.value.endDate) {
			//比较开始时间和结束时间大小
			let startDate = new Date(form.value.startDate);
			let endDate = new Date(form.value.endDate);
			if (startDate > endDate) {
				form.value.endDate = ''
				uni.showToast({
					icon: 'none',
					title: '结束时间不能大于开始时间'
				})
			}
		}
	}

	const datetimePicker3 = ref()
	const createTimeShow3 = () => {
		unref(datetimePicker3).open()
	}

	// 选择时间
	const endDateValue = ref(timestampToDate(new Date()))
	const createTimeChange3 = (e) => {
		form.value.endDate = timestampToDate(e.value)
		if (form.value.startDate) {
			//比较开始时间和结束时间大小
			let startDate = new Date(form.value.startDate);
			let endDate = new Date(form.value.endDate);
			if (endDate < startDate) {
				form.value.endDate = ''
				uni.showToast({
					icon: 'none',
					title: '结束时间不能大于开始时间'
				})
			}
		}
	}
	// 获取商机数据详情
	const getContractInfo = async () => {
		form.value = await getOAContract({
			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)
				}
			})
		}

		selectList.value = await getContractProductListByContractId({
			contractId: contractId.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 < pageSize.value) {
					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 getUserList = async (isNextPage, pages) => {
		await getAllUserList({
			username: keyword3.value,
			deptId: form.value.companyId
		}).then(res => {
			userList.value = res
			if (form.value.signatoryId) {
				userList.value.forEach((item, index) => {
					if (form.value.signatoryId == item.id) {
						item.checked = true
						username.value = item.nickname
					} else {
						item.checked = false
					}
				})
			}
		})
	}


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


	// 选择客户
	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 : ''
		//选择了客户 返回客户联系人
		let data = await getContactsPage({
			customerId: val.id
		})
		customerContacts.value = data.list
		//根据客户查找商机
		let data2 = await getBusinessPage({
			customerId: val.id
		})
		businessList.value = data2.list
		selectShowClose()
	}

	const selectShowRef2 = ref()
	const selectShow2 = () => {
		unref(selectShowRef2).open()
	}
	const selectShowClose2 = () => {
		unref(selectShowRef2).close()
	}

	const onItem2 = async (val, i) => {
		customerContacts.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.contactsId = val.id
		form.value.contactsName = val.name ? val.name : ''
		selectShowClose2()
	}


	const selectShowRef3 = ref()
	const selectShow3 = async () => {
		unref(selectShowRef3).open()
	}
	const selectShowClose3 = () => {
		unref(selectShowRef3).close()
	}

	const onItem3 = async (val, i) => {
		userList.value.forEach((item, index) => {
			if (val.id == item.id) {
				item.checked = true
			} else {
				item.checked = false
			}
		})
		form.value.signatoryId = val.id
		form.value.signatoryName = val.nickname ? val.nickname : ''
		selectShowClose3()
	}

	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.name = val.name ? val.name : item.name;
			} else {
				item.checked = false
			}
		})
		form.value.businessId = val.id
		form.value.businessName = val.name ? val.name : ''
		selectList.value = await getBusinessProductListByBusinessId({
			businessId: val.id
		})
		selectShowClose4()
	}


	//公司
	const selectShowRef6 = ref()
	const selectShow6 = async () => {
		unref(selectShowRef6).open()
	}
	const selectShowClose6 = () => {
		unref(selectShowRef6).close()
	}
	const onItem6 = (val, i) => {
		companyList.value.forEach((item, index) => {
			if (val.id == item.id) {
				item.checked = true
			} else {
				item.checked = false
			}
		})
		form.value.companyId = val.id
		form.value.companyName = val.name
		userList.value = []
		page3.value = 1
		getUserList()
		selectShowClose6()
	}

	// 产品数量增加
	const valChange = (e) => {
		count_price()
	}
	// 优惠率改变
	const inputChang = (e) => {
		if (e.detail.value > form.value.totalPrice) {
			form.value.discountRate = 0
			uni.showToast({
				icon: 'none',
				title: '折扣金额不能大于总金额'
			})
		}

		if (e.detail.value < 0) {
			form.value.discountRate = 0
			uni.showToast({
				icon: 'none',
				title: '折扣金额不能小于0'
			})
		}

		count_price()
	}
	// 移除已选产品
	const remove = (i) => {
		selectList.value.splice(i, 1)
		count_price()
	}
	// 计算价格
	const count_price = () => {
		let list = deepClone(selectList.value)

		if (list.length > 0) {
			let total = 0;
			for (let i = 0; i < list.length; i++) {
				total = total + (list[i].nums * list[i].price)
			}
			total = total - Number(form.value.discountRate || 0)
			form.value.totalPrice = total.toFixed(2)
		} else {
			form.value.totalPrice = 0
		}
	}

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

		if (form.value.contactsName == '') {
			uni.showToast({
				icon: 'error',
				title: '请选择客户签约人'
			})
			return
		}
		if (form.value.signatoryId == '') {
			uni.showToast({
				icon: 'error',
				title: '请选择公司签约人'
			})
			return
		}

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


	// 修确认提交
	const submitBtn = ref(false)
	const onSubmit = () => {
		let newArr = []
		submitBtn.value = true
		uni.showLoading({
			title: '提交中'
		});
		selectList.value.forEach((item, index) => {
			let obj = {}
			obj.name = item.storeName ? item.storeName : item.name
			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
		})

		form.value.contractProducts = newArr
		form.value.fileItems = [...imgFiles.value, ...pdfList.value]
		createOAContract(form.value).then(res => {
			submitBtn.value = false
			uni.hideLoading();
			uni.showToast({
				title: '添加成功',
				icon: 'success',
				duration: 2000
			})
			prePage().$vm.isRefresh = true
			setTimeout(() => {
				uni.navigateBack();
			}, 1000);
		}).catch(err => {
			submitBtn.value = false
			uni.hideLoading();
		})
	}
</script>

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

		.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: 64px;
			padding-right: 25rpx;
		}

		.list {
			margin-bottom: 45rpx;

			.item {
				padding: 0 20rpx 30rpx 30rpx;
				justify-content: space-between;

				.title {
					flex: 1;
					font-size: 29rpx;
				}

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

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

	.storeName {
		font-size: 30rpx;
	}

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