<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app';
	import { onMounted, ref } from 'vue';
	import { getAction, postAction } from '../../common/http';
	import { formatDate } from '../../utils/date';
	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 orderItem = ref({ craftComment: {} } as any)
	const list = ref()
	const orderId = ref()
	const fabricId = ref()
	const tributeList = ref([] as any[])
	const zt = ref()

	// 定义 props
	defineProps<{
		id ?: string;
		subId ?: string;
		zt ?: string;
	}>();

	onLoad(async (option : any) => {
		if (option) {
			try {
				orderId.value = option.id
				fabricId.value = option.subId
				zt.value = option.zt
			} catch (error) {
				console.error('Failed to parse item JSON:', error);
				// 可以选择在这里显示错误消息给用户
			}
		}
	})

	onMounted(() => {
		getAction('/customOrder/' + orderId.value).then((res : any) => {
			if (res.code === 200) {
				form.value = res.data.customOrder
				orderItem.value = res.data.orderItems.find((l : any) => l.id == fabricId.value)
			}
		})
		getAction('/tribute/' + fabricId.value).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('/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: fabricId.value,
			type: '定做单',
			factory: formItem.value.rc,
			qty: formItem.value.jcps,
			len: formItem.value.jcms,
			tributeDate: formItem.value.phrq,
			data: {
				craft: orderItem.value.craft,
				makeUser: form.value.makeUser,
				belongTo: form.value.belongTo,
				zt: typeData.value,
				sd: form.value.sd,
				innerComment:form.value.interComment,
				customerComment:form.value.customerComment,
				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: orderItem.value.fabric[l].name,sh:orderItem.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) => {
		indexType.value = index
		scanCode()
	}
	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
	}
</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.belongTo" name="订单归属" label="订单归属" colon class="bor-n" label-width="5em"
						readonly />
					<van-field v-model="form.sd" name="谁定" label="谁定" colon class="bor-n" readonly label-width="5em" />
					<van-field v-model="orderItem.craft" name="工艺" label="工艺" colon label-width="5em" readonly
						class="bor-n" />
					<van-field v-model="orderItem.craftComment.name" name="工艺要求" label="工艺要求" colon label-width="5em"
						readonly class="bor-n" />
					<van-field v-model="form.interComment" name="内部备注" label="内部备注" colon label-width="5em" readonly
						class="bor-n" />
					<van-field v-model="orderItem.color" 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>
					<view class="grid-container" v-for="(item,index) in orderItem.fabric" :key="index">
						<view class="grid-item">{{item.name}}</view>
						<view class="grid-item">{{item.qty}}</view>
						<view class="grid-item">{{item.len}}</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)" />
								</view>
							</view>
							<view class="a-c" v-if="zt!='已配全'">
								<van-button type="primary" @click="upScanCode(index)">
									扫一扫
								</van-button>
							</view>
						</view>
					</view>
					<cshaptx4869-scancode v-if="h5ScanCode" @success="handleSuccess" @fail="handleFail"
						@close="handleClose">
					</cshaptx4869-scancode>

					<view v-if="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="进厂米数" colon class="bor-n" readonly
							label-width="5em" />
					</view>
				</van-cell-group>
				<view style="margin: 16px;display: flex;" v-if="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>
			<h3 style="text-align: center;margin-top: 10rpx;">扫码成功</h3>
			<van-cell-group inset>
				<view v-for="(item,index) in bhms" :key="index">
					<van-field v-model="item.code" name="面料编号" label="面料编号" colon readonly label-width="5em"
						class="bor-n" />
					<van-field v-model="item.syps" name="剩余米数" label="剩余米数" colon label-width="5em" class="bor-n"
						readonly />
					<van-field v-model="item.ms" name="排单米数" label="排单米数" colon label-width="5em" />
				</view>
			</van-cell-group>
		</view>
		<template #footer>
			<view class="footer-button">
				<van-button plain size="small" native-type="button" style="width: 25vw;" @click="conScanCode">
					扫描结束
				</van-button>
				<van-button size="small" type="success" native-type="submit" 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>