<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" labelPosition="top" labelWidth="130" :rules="rules">
				<uv-form-item label="选择合同:" @click="!isCheck ? selectShow() : ''" required prop="contractName">
					<uv-input :disabled="isCheck" 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="计划开票日期:" required prop="invoiceDate">
					<uni-datetime-picker v-if="!isCheck" type="date" placeholder="请选择计划开票日期" :clear-icon="false"
						v-model="form.invoiceDate" />
					<uv-input v-else v-model="form.invoiceDate" :disabled="isCheck" placeholder="请输入开票内容" />
				</uv-form-item>
				<uv-form-item label="开票主体:" required prop="invoiceBody">
					<uv-input v-model="form.invoiceBody" :disabled="isCheck" placeholder="请输入开票主体" />
				</uv-form-item>
				<uv-form-item label="发票抬头:" prop="invoiceName" required>
					<uv-input v-model="form.invoiceName" :disabled="isCheck" placeholder="请输入发票抬头" />
				</uv-form-item>
				<uv-form-item label="抬头类型:" required prop="invoiceIssue">
					<view style="margin-top: 14rpx;">
						<uv-radio-group v-model="form.invoiceIssue" required :disabled="isCheck">
							<uv-radio v-for="(item, index) in sexList" :key="index" :name="item.name">
								<text style="padding-right: 20rpx;">{{ item.text }}</text>
							</uv-radio>
						</uv-radio-group>
					</view>
				</uv-form-item>
				<uv-form-item label="发票类型:" required prop="invoiceType">
					<view style="margin-top: 14rpx;">
						<uv-radio-group v-model="form.invoiceType" required :disabled="isCheck">
							<uv-radio v-for="(item, index) in typeList" :key="index" :name="item.name">
								<text style="padding-right: 20rpx;">{{ item.text }}</text>
							</uv-radio>
						</uv-radio-group>
					</view>
				</uv-form-item>
				<uv-form-item label="统一社会信用代码:" required prop="registerNo">
					<uv-input v-model="form.registerNo" :disabled="isCheck" placeholder="请输入统一社会信用代码" />
				</uv-form-item>
				<uv-form-item label="开票金额:" prop="amount" required>
					<uv-input type="number" v-model="form.amount" :disabled="isCheck" placeholder="请输入开票金额" />
				</uv-form-item>
				<uv-form-item label="开票内容:" prop="content">
					<uv-input v-model="form.content" :disabled="isCheck" placeholder="请输入开票内容" />
				</uv-form-item>
				<uv-form-item label="开票单位地址:" prop="unitAddress">
					<uv-input v-model="form.unitAddress" :disabled="isCheck" placeholder="请输入开票单位地址" />
				</uv-form-item>
				<uv-form-item label="开票单位电话:" prop="unitPhone">
					<uv-input v-model="form.unitPhone" :disabled="isCheck" placeholder="请输入开票单位电话" />
				</uv-form-item>
				<uv-form-item label="开票单位开户银行:" prop="unitBankName">
					<uv-input v-model="form.unitBankName" :disabled="isCheck" placeholder="请输入开票单位开户银行" />
				</uv-form-item>
				<uv-form-item label="开票单位银行账号:" prop="unitBankNo">
					<uv-input v-model="form.unitBankNo" :disabled="isCheck" placeholder="请输入开票单位银行账号" />
				</uv-form-item>
				<uv-form-item label="开票单位邮箱:" prop="email">
					<uv-input v-model="form.email" :disabled="isCheck" placeholder="请输入开票单位邮箱" />
				</uv-form-item>
				<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>
			</uv-form>
			<view class="mt-4" style="text-align: center;">
				<uv-button color="#09b4f1" @click="submit" :disabled="isCheck" :ripple="true">确定提交</uv-button>
			</view>
		</view>
		<uv-popup mode="bottom" round="38" ref="selectShowRef5">
			<view class="popup-content">
				<view class="popup-title">
					<view class="" style="width: 45px;">
					</view>
					<text class="">输入驳回理由</text>
					<view class="" @click="selectShowClose5" style="width: 45px;">
						<uv-icon name="close" color="#909399" size="30"></uv-icon>
					</view>
				</view>
				<view style="height: 500rpx;padding: 20rpx;">
					<uv-textarea v-model="form2.remark" placeholder="输入驳回理由"></uv-textarea>
				</view>
				<view style="padding: 20rpx;">
					<uv-button color="#09b4f1" @click="submitCheck(2)">确定</uv-button>
				</view>
			</view>
		</uv-popup>
		<!-- 选择客户弹窗 -->
		<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>
				<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.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="timeValue" mode="datetime"
			@confirm="createTimeChange"></uv-datetime-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		unref,
		computed
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		getListByDeptId
	} from '@/api/contract'
	import {
		invoiceCreate,
		getInvoice,
		invoiceUpdate,
		check,
		invoiceIssue
	} from '@/api/invoice'
	import {
		getSimpleUserList,
		getFlowUsers,
		getSimpleUserList2,
		uploadFile,
		deleteBpmFile
	} from '@/api/user'
	import AddressSelect from '@/components/AddressSelect/index.vue'
	import {
		formatDateTime,
		prePage
	} from '@/utils/util'
	const title = ref('申请发票')
	const labelPosition = ref('left')
	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(formatDateTime(new Date()))
	const content = ref('')
	const customerName = ref('')
	const form = ref({
		invoiceDate: undefined, // 开票日期
		customerName: undefined, // 客户名称
		customerId: undefined, // 客户编号
		projectId: [], // 开票项目
		invoiceBody: undefined, // 开票主体
		invoiceName: undefined, // 发票抬头
		invoiceIssue: 1, // 抬头类型 | 1企业2个人3事业单位
		invoiceType: 1, // 发票类型 | 1增值税普票2增值税专票
		registerNo: undefined, // 纳税人识别号
		amount: undefined, // 开票金额
		content: undefined, // 开票内容
		unitAddress: undefined, // 开票单位地址
		unitPhone: undefined, // 开票单位联系方式
		unitBankName: undefined, // 开票单位开户行
		unitBankNo: undefined, // 开票单位银行账号
		email: undefined, // 开票单位邮箱
		contractId: undefined, // 关联合同编号
		contractInstanceId: undefined, // 关联合同审批单编号
		fileItems: []
	})
	const timeText = ref('')
	const errorType = ref('message')
	const rules = ref({
		contractName: [{
			required: true,
			message: '请选择合同',
			trigger: ['change', 'blur']
		}],
		invoiceDate: [{
			required: true,
			message: '请选择开票日期',
			trigger: ['change', 'blur']
		}],
		invoiceBody: [{
			required: true,
			message: '请填写开票主体',
			trigger: ['change', 'blur']
		}],
		invoiceName: [{
			required: true,
			message: '请填写发票抬头',
			trigger: ['change', 'blur']
		}],
		registerNo: [{
			required: true,
			message: '请填写统一社会信用代码',
			trigger: ['change', 'blur']
		}],
		amount: [{
			required: true,
			message: '请填写发票金额',
			trigger: ['change', 'blur']
		}],
	})
	const customerContacts = ref([])
	const userList = ref([])
	const username = ref('')
	const keyword3 = ref('')
	const businessList = ref([])
	const isCheck = ref(false)
	const form2 = ref({
		id: 0,
		agreeType: 1,
		remark: ''
	})
	const sexList = ref([{
			name: 1,
			text: '企业',
		},
		{
			name: 2,
			text: '个人',
		},
		{
			name: 3,
			text: '事业单位',
		},
	])
	const typeList = ref([{
			name: 1,
			text: '普票',
		},
		{
			name: 2,
			text: '专票',
		},
	])

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

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

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

	// 获取商机数据详情
	const getContractInfo = async () => {
		form.value = await getInvoice({
			id: contractId.value
		})
		form.value.invoiceDate = form.value.invoiceDate.join("-")

		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)
				}
			})
		}

		customerList.value.forEach(item => {
			if (item.id == form.value.contractId) {
				form.value.contractName = item.contractName
			}
		})
	}

	//获取合同
	const getCustomerList = async () => {
		await getListByDeptId().then(res => {
			customerList.value = res
		})
	}

	// 选择客户
	const onItem = async (val, i) => {
		customerList.value.forEach((item, index) => {
			if (val.id == item.id) {
				item.checked = true
			} else {
				item.checked = false
			}
		})
		form.value.contractId = val.id
		form.value.contractName = val.contractName
		form.value.contractInstanceId = val.processInstanceId
		selectShowClose()
	}

	const selectShowRef5 = ref()
	const selectShow5 = async () => {
		unref(selectShowRef5).open()
	}
	const selectShowClose5 = () => {
		unref(selectShowRef5).close()
	}

	const submitCheck = async (type) => {
		if (type == 2 && form2.value.remark == '') {
			uni.showToast({
				icon: 'error',
				title: '请填写驳回理由'
			})
			return
		}
		form2.value.id = contractId.value
		form2.value.type
		await check(form2.value)

		uni.showToast({
			title: '审核成功',
			icon: 'success',
			duration: 2000
		})
		prePage().$vm.isRefresh = true
		setTimeout(() => {
			uni.navigateBack();
		}, 1000);
	}


	// 提交跟进
	const uForm = ref()
	const submit = () => {
		if (form.value.contractName == '') {
			uni.showToast({
				icon: 'error',
				title: '请选择合同'
			})
			return
		}
		uForm.value.validate().then(res => {
			onSubmit()
		}).catch(errors => {
			uni.showToast({
				icon: 'error',
				title: '请完善发票信息'
			})
		})
	}

	// 修确认提交
	const onSubmit = async () => {
		await invoiceCreate(form.value)
		uni.showToast({
			title: '申请成功',
			icon: 'success',
			duration: 2000
		})
		prePage().$vm.isRefresh = true
		setTimeout(() => {
			uni.navigateBack();
		}, 1000);
	}


	// 附件上传相关
	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 50rpx 34rpx;

		.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 {
		width: 750rpx;

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