<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app';
	import { onMounted, ref } from 'vue';
	import { formatDate } from '../../utils/date';
	import { getAction, postAction } from '../../common/http';
	import { showToast } from 'vant';

	const form = ref({} as any)
	const showDialog = ref(false)
	const show = ref(false)
	const formItem = ref({ jcps: 0, jcms: 0 } as any)
	const list = ref()
	const orderId = ref()
	const tributeList = ref([] as any[])
	const zt = ref()

	// 定义 props
	defineProps<{
		id ?: string;
		zt?:string;
	}>();
	
	onLoad(async (option : any) => {
		if (option) {
			try {
				orderId.value = option.id
				zt.value=option.zt
			} catch (error) {
				console.error('Failed to parse item JSON:', error);
				// 可以选择在这里显示错误消息给用户
			}
		}
	})
	onMounted(() => {
		getAction('/tribute/'+orderId.value+'?type=现货单').then((res:any)=>{
			if(res.code===200){
				res.data.forEach((k:any)=>{
					k.data.mls.forEach((l:any)=>{
						l.xxs.forEach((m:any)=>{
							tributeList.value.push(m)
						})
					})
				})
			}
		})
		getAction('/interOrder/'+orderId.value).then((res : any) => {
			if (res.code === 200) {
				form.value = res.data
			}
		})
		getAction('/factory').then((res : any) => {
			if (res.code === 200) {
				list.value = res.data.map((l : any) => ({ text: l.name, value: l.name }))
			}
		})
	})

	const onClickLeft = () => {
		window.history.back()
	}

	const onSubmit = () => {
		let val = {
			orderId: orderId.value,
			type: '现货单',
			factory: formItem.value.rc,
			qty: formItem.value.jcps,
			len: formItem.value.jcms,
			tributeDate: formItem.value.phrq,
			data: {
				craft: form.value.craft,
				makeUser: form.value.makeUser,
				belongTo: '',
				zt: typeData.value,
				sd: form.value.sd,
				customerComment:form.value.comment,
				mls: []
			}
		}
		let set = new Set()
		bhms.value.forEach((l : any) => {
			set.add(l.index)
		})
		set.forEach((l : any) => {
			let xxs = []
			bhms.value.forEach((m : any) => {
				if (m.index == l) {
					xxs.push(m)
				}
			})
			val.data.mls.push({ name: form.value.fabric[l].name,sh:form.value.color, xxs: xxs })
		})
		
		postAction('/tribute', val).then((res : any) => {
			if (res.code === 200) {
				showToast('提交成功！')
				uni.redirectTo({
					url: '/pages/distribution/distribution'
				})
			}
		})
	}
	const typeData = ref()
	const beforeSubmit = (type : any) => {
		typeData.value = type
	}

	//扫一扫
	const h5ScanCode = ref(false);
	const bhms = ref([] as any[])
	const indexType = ref()
	//点击扫一扫
	const upScanCode = (index : any) => {
		scanCode()
		indexType.value = index
	}
	const conScanCode = () => {
		showDialog.value = false
		formItem.value.jcps = 0
		formItem.value.jcms = 0
		bhms.value.forEach((l : any) => {
			formItem.value.jcps++
			formItem.value.jcms += l.ms * 1
		})
		formItem.value.jcms = (formItem.value.jcms).toFixed(1)
	}

	function scanCode() {
		showDialog.value = false
		h5ScanCode.value = true;
		uni.scanCode({
			success: (res) => {
				uni.showToast({
					icon: "none",
					title: res.result,
				});
			},
			faile: (err : any) => {
				console.log("err", err);
			},
		});
	}
	function handleSuccess(res : any) {
		h5ScanCode.value = false;
		getAction('/rawFabric/qrcode', { barcode: res }, { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }).then((res1 : any) => {
			if (res1.code === 200) {
				bhms.value.push({
					code: res,
					ms: res1.data.len,
					syps: res1.data.len,
					index: indexType.value,
				})
				showDialog.value = true
			}
		})
	}
	function handleFail(err : any) {
		uni.showModal({
			title: err.errName,
			content: err.errMsg,
			complete: () => {
				h5ScanCode.value = false;
			},
		});
	}
	function handleClose() {
		h5ScanCode.value = false;
	}

	const chooseDate = () => {
		show.value = true
	}
	//日期选择
	const onConfirmDate = (val : any) => {
		formItem.value.phrq = formatDate(val)
		show.value = false
	}

	const showPicker = ref(false)
	const popuList = ref([] as any[])
	//选择框事件
	const choosePic = () => {
		showPicker.value = true
	}
	//选择框确认
	const pickerConfirm = (val : any) => {
		formItem.value.rc = val.selectedValues[0]
		showPickerCancel()
	}
	//取消
	const showPickerCancel = () => {
		showPicker.value = false
	}
	//弹窗开启事件
	const handleOpen = () => {
		popuList.value = list.value
	}
	
	const totalPs = (index:any) =>{
		let zps = 0
		tributeList.value.forEach((l:any)=>{
			if(l.index==index){
				zps++
			}
		})
		bhms.value.forEach((l:any)=>{
			if(l.index==index){
				zps++
			}
		})
		return Number(zps.toFixed(1))
	}
</script>

<template>
	<view class="flex">
		<van-nav-bar title="现货需求单" left-text="返回" left-arrow @click-left="onClickLeft" />
		<view class="content">
			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field v-model="form.id" name="需求单号" label="需求单号" colon class="bor-n" label-width="5em"
						readonly />
					<van-field v-model="form.makeTime" name="做单日期" label="做单日期" colon class="bor-n" label-width="5em"
						readonly />
					<van-field v-model="form.makeUser" name="做单人" label="做单人" colon class="bor-n" label-width="5em"
						readonly />
					<van-field v-model="form.color" name="颜色色号" label="颜色色号" colon class="bor-n" readonly
						label-width="5em" />
					<van-field v-model="form.craft" name="工艺" label="工艺" colon label-width="5em" readonly
						class="bor-n" />
					<van-field v-model="form.comment" name="备注" label="备注" colon label-width="5em" readonly
						class="bor-n" />

					<view class="grid-container">
						<view class="grid-item">面料名称</view>
						<view class="grid-item">匹数</view>
						<view class="grid-item">谁定</view>
						<view class="grid-item">面料编号/米数</view>
					</view>

					<template v-for="(item,index) in form.fabric" :key="index">
						<view class="grid-container">
							<view class="grid-item">{{item.name}}</view>
							<view class="grid-item">{{item.quantity}}</view>
							<view class="grid-item">门店</view>
							<view class="grid-item">
								<view v-for="(itemSecond,indexSecond) in tributeList" :key="indexSecond">
									<view v-if="itemSecond.index==index" class="box">
										{{itemSecond.code}}<br>{{itemSecond.ms}}米
									</view>
								</view>
								<view v-for="(itemSecond,indexSecond) in bhms" :key="indexSecond">
									<view v-if="itemSecond.index==index" class="box">
										{{itemSecond.code}}<br>{{itemSecond.ms}}米
										<van-icon name="cross" color="red" @click="bhms.splice(indexSecond,1),conScanCode()" />
									</view>
								</view>
								<p :style="{color:totalPs(index)>item.quantity?'red':''}">总匹数：{{totalPs(index)}}</p>
								<view class="a-c" v-if="form.zt!='已配全'">
									<van-button type="primary" @click="upScanCode(index)">
										扫一扫
									</van-button>
								</view>
							</view>
						</view>
					</template>

					<cshaptx4869-scancode v-if="h5ScanCode" @success="handleSuccess" @fail="handleFail"
						@close="handleClose">
					</cshaptx4869-scancode>

					<view v-if="form.zt!='已配全'">
						<van-field v-model="formItem.phrq" name="配货日期" label="配货日期" colon class="bor" label-width="5em"
							readonly :rules="[{ required: true, message: '请填写' }]" @click="chooseDate()" />
						<van-field v-model="formItem.rc" name="染厂选择" label="染厂选择" colon class="bor" label-width="5em"
							readonly :rules="[{ required: true, message: '请填写' }]" @click="choosePic()" />
						<van-field v-model="formItem.jcps" name="进厂匹数" label="进厂匹数" colon label-width="5em"
							class="bor-n" readonly />
						<van-field v-model="formItem.jcms" name="进厂米数" label="进厂米数" type="number" colon class="bor-n" readonly
							label-width="5em" />
					</view>
				</van-cell-group>
				<view style="margin: 16px;display: flex;" v-if="form.zt!='已配全'">
					<van-button round block type="primary" native-type="submit" @click="beforeSubmit('部分配货')">
						部分配货
					</van-button>
					<van-button round block type="primary" native-type="submit" @click="beforeSubmit('已配全')"
						style="margin-left: 15px;">
						已配全
					</van-button>
				</view>
			</van-form>
		</view>
	</view>

	<van-dialog v-model:show="showDialog">
		<view style="overflow-y: scroll;max-height: 80vh;">
			<h3 style="text-align: center;margin-top: 10rpx;">扫码成功</h3>
			<van-cell-group inset>
				<view v-for="(item,index) in bhms" :key="index">
					<view style="display: flex;align-items: center;">
						<van-field v-model="item.code" name="面料编号" label="面料编号" colon readonly label-width="5em"
							class="bor-n" />
							<van-icon name="close" color="red" size="22px" @click="bhms.splice(index,1)"/>
					</view>
					
					<van-field v-model="item.syps" name="剩余米数" label="剩余米数" colon label-width="5em" class="bor-n"
						readonly />
					<van-field v-model="item.ms" name="排单米数" label="排单米数" type="number" @input="item.ms=item.ms.replace(/^\D*(\d*(?:\.\d{0,1})?).*$/g, '$1')" colon label-width="5em" />
				</view>
			</van-cell-group>
		</view>
		<template #footer>
			<view class="footer-button">
				<van-button size="small" style="width: 25vw;" @click="conScanCode">
					扫描结束
				</van-button>
				<van-button size="small" type="success" style="width: 25vw;" @click="scanCode">
					继续扫码
				</van-button>
			</view>
		</template>
	</van-dialog>

	<!--选择框-->
	<van-popup v-model:show="showPicker" round position="bottom" @open="handleOpen">
		<van-picker show-toolbar :columns="popuList" @confirm="pickerConfirm" @cancel="showPickerCancel"
			ref="pickerRef" />
	</van-popup>

	<van-calendar v-model:show="show" @confirm="onConfirmDate" :min-date="new Date(2025, 0, 1)" />
</template>

<style lang="scss" scoped>
	.flex {
		display: flex;
		flex-direction: column;
		height: 100vh;
		width: 100vw;

		.van-nav-bar {
			width: 100%;
		}

		.content {
			flex: 1;
			padding: 0 10px;

			.grid-container {
				display: grid;
				grid-template-columns: 2fr 1fr 1.5fr 2fr;

				.grid-item {
					border: 1px solid #f2f2f2;
					text-align: center;
					padding: 15rpx 0;
					display: flex;
					flex-direction: column;
					justify-content: center;

					::v-deep .van-cell {
						padding: 0 5px;
					}
				}
			}
		}
	}

	.footer-button {
		margin: 20px;
		display: flex;
		justify-content: space-around;
	}

	::v-deep .van-field {
		font-size: 16px;
	}

	.a-c {
		display: flex;
		align-items: center;
		justify-content: center;

		::v-deep .van-button--normal {
			padding: 8rpx;
			height: 50rpx;
			width: 4em;
		}
	}

	.bor {
		::v-deep .van-field__control {
			border: 1px solid #d7d7d7;
		}
	}

	.bor-n {
		::v-deep .van-field__control {
			border: none;
		}
	}

	::v-deep .van-field__control {
		border-bottom: 1px solid #d7d7d7;
		text-align: center;
		font-size: 16px;
		
	}

	::v-deep .van-field__label {
		text-align: end;
	}

	.box {
		margin: 5rpx 20rpx;
		border: 1rpx solid #d7d7d7;
		border-radius: 10rpx;
	}

	.line {
		border-bottom: 1rpx solid #d7d7d7;
		margin-bottom: 10rpx;
	}
</style>