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

	const form = ref({ createTime: formatDate(new Date()), dict: [{stupid1:false, infos: [] }] } as any)
	const show = ref(false)
	const gysList = ref([])
	const djList = ref([])
	const showPicker = ref(false)
	const popuList = ref([])
	const showDialog = ref(false)
	const pickerList = ref([])//面料数据
	const pickerContainerList = ref([])
	const showPickerList = ref(false)
	const searchValue = ref('')//查询的值
	const searchIndex = ref(0)//查询到的数组
	const mlList = ref([])

	onMounted(() => {
		getAction('/suppliers').then((res : any) => {
			if (res.code === 200) {
				gysList.value=[]
				res.data.forEach((l:any)=>{
					if(l.active){
						gysList.value.push(l)
					}
				})
			}
		})
		getAction('/rawFabricLevels', { page: 1, size: 100 }).then((res : any) => {
			if (res.code === 200) {
				djList.value = res.data.record
			}
		})
		getAction('/fabric/info/all').then((res : any) => {
			if (res.code === 200) {
				res.data.forEach((l : any) => {
					let itemMl = mlList.value.find(m => m.text === l.commodity)
					if (itemMl) {
						let itemMm = itemMl.children.find(m => m.value === l.momme)
						if (itemMm) {
							itemMm.children.push({ text: l.width + 'cm', value: l.width })
						} else {
							itemMl.children.push({
								text: l.momme + 'mm',
								value: l.momme,
								children: [{ text: l.width + 'cm', value: l.width }]
							})
						}
					} else {
						mlList.value.push({
							text: l.commodity,
							value: l.commodity,
							children: [{ text: l.momme + 'mm', value: l.momme, children: [{ text: l.width + 'cm', value: l.width }] }]
						})
					}
				})
			}
		})
	})

	const typeData = ref()
	const indexData = ref()
	//选择框事件
	const choosePic = (type : any, index : any) => {
		showPicker.value = true
		typeData.value = type
		indexData.value = index
		searchVal.value = ''
	}
	//选择框确认
	const pickerConfirm = (val : any) => {
		if (typeData.value === 'level') {
			form.value.dict[indexData.value][typeData.value] = val.selectedValues[0]
		} else {
			form.value[typeData.value] = val.selectedValues[0]
		}
		showPickerCancel()
	}
	//取消
	const showPickerCancel = () => {
		showPicker.value = false
	}
	//弹窗开启事件
	const handleOpen = () => {
		if (typeData.value === 'supplier') {
			popuList.value = gysList.value.map(l => ({ text: l.name, value: l.name }))
		} else if (typeData.value === 'level') {
			popuList.value = djList.value.map(l => ({ text: l.level, value: l.level }))
		}
	}
	const searchVal = ref()
	const selectValue = ref()
	const searchPop = () => {
		if (timer.value) {
			clearTimeout(timer.value)
		}
		timer.value = setTimeout(() => {
			getSeach()
		}, 800)
	}
	function getSeach() {
		let reg = new RegExp(searchVal.value)
		let a = popuList.value.find((l : any) => reg.test(l.text))
		if (a) {
			selectValue.value = [a.text]
		}
	}

	const onSubmit = () => {
		form.value.dict.forEach((l:any)=>{
			l.stupid=l.stupid1?'是':'否'
		})
		postAction('/rawFabric', form.value).then((res : any) => {
			if (res.code === 200) {
				showToast('提交成功！')
				uni.redirectTo({
					url: '/pages/whiteEmbryo/w-warehousing'
				})
			}
		})
	}

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

	const chooseDate = () => {
		show.value = true
	}
	const onConfirmDate = (val : any) => {
		form.value.createTime = formatDate(val)
		show.value = false
	}
	const h5ScanCode = ref(false);
	function scanCode(index : any) {
		// #ifdef H5
		h5ScanCode.value = true;
		indexData.value = index
		// #endif
		// #ifndef H5
		uni.scanCode({
			success: (res) => {
				uni.showToast({
					icon: "none",
					title: res.result,
				});
			},
			faile: (err) => {
				console.log("err", err);
			},
		});
		// #endif
	}
	const barcode = ref()
	function handleSuccess(res : any) {
		h5ScanCode.value = false;
		barcode.value = res
		if (res.length != 9) return showToast('请扫描正确的面料编号！')
		getAction('/rawFabric/valid', { barcode: res }).then((res1 : any) => {
			if (res1.code === 200) {
				let tj = false
				form.value.dict.forEach((l : any) => {
					let item = l.infos.find(m => m.barcode === res)
					if (item) {
						tj = true
					}
				})
				if (tj) {
					showToast('扫码失败，该编号已被使用，请重新扫码！')
				} else {
					showDialog.value = true
				}
			} else {
				showToast('扫码失败，该编号已被使用，请重新扫码！')
			}
		})
	}
	function handleFail(err : any) {
		uni.showModal({
			title: err.errName,
			content: err.errMsg,
			complete: () => {
				h5ScanCode.value = false;
			},
		});
	}

	function handleClose() {
		h5ScanCode.value = false;
	}

	//扫码提交
	const meter = ref('' as any)
	const comment = ref('' as any)
	const checked = ref(false)
	const confirmSecond = () => {
		if (!meter.value) return showToast('请填写米数！')
		var x = String(meter.value).indexOf('.') + 1;   //小数点的位置
		var y = String(meter.value).length - x;  //小数的位数
		if (y === 0) return showToast('请输入正确数字！')
		if (x > 0 && y > 1) return showToast('请保留一位小数！')
		form.value.dict[indexData.value].infos.push({ barcode: barcode.value, len: meter.value, freeze: checked.value, comment:comment.value })
		showDialog.value = false
		meter.value = ''
		comment.value=''
		checked.value = false
	}

	//选择面料
	const selectChoose = () => {
		showPickerList.value = true
	}
	//面料开启
	const mlmcOpen = () => {
		pickerList.value = mlList.value
		pickerContainerList.value = pickerList.value
		searchValue.value = ''
	}
	//面料关闭
	const pickerCancel = () => {
		showPickerList.value = false
	}

	//搜索
	const selectedValue = ref()
	const getSeachList = () => {
		searchIndex.value = 0
		let reg = new RegExp(searchValue.value)
		let arr = []
		pickerList.value.forEach(l => {
			if (reg.test(l.text)) {
				arr.push(l)
			}
		})
		pickerContainerList.value = arr
	}
	//向上选择
	const upSearch = () => {
		if (searchIndex.value === 0 && pickerContainerList.value.length) {
			searchIndex.value = pickerContainerList.value.length - 1
			selectedValue.value = [pickerContainerList.value[searchIndex.value].text]
		} else if (pickerContainerList.value.length) {
			searchIndex.value--
			selectedValue.value = [pickerContainerList.value[searchIndex.value].text]
		} else {
			showToast('没有了！')
		}
	}
	//向下选择
	const downSearch = () => {
		if (pickerContainerList.value.length) {
			if (searchIndex.value === pickerContainerList.value.length) {
				searchIndex.value = 0
				selectedValue.value = [pickerContainerList.value[searchIndex.value].text]
			} else {
				searchIndex.value++
				selectedValue.value = [pickerContainerList.value[searchIndex.value].text]
			}
		} else {
			showToast('没有了！')
		}
	}
	//搜索框输入
	const timer = ref()
	const searchTo = () => {
		if (timer.value) {
			clearTimeout(timer.value)
		}
		timer.value = setTimeout(() => {
			getSeachList()
		}, 800)
	}
	const onConfirm = (val : any) => {
		form.value.fabricName = val.selectedValues[2] + '/' + val.selectedValues[0] + val.selectedValues[1]
		pickerCancel()
	}

	const totalMeter = computed(() => {
		let ms = 0
		let ps = 0
		form.value.dict.forEach((l : any) => {
			l.infos.forEach((m : any) => {
				ms += m.len * 1
				ps++
			})
		})
		return [ms.toFixed(1), ps]
	})
</script>

<template>
	<view class="flex">
		<van-nav-bar title="白胚入库" left-text="返回" left-arrow @click-left="onClickLeft" />
		<van-form @submit="onSubmit">
			<van-cell-group inset>
				<van-field v-model="form.createTime" name="入库日期" label="入库日期" colon class="bor" label-width="5em"
					readonly :rules="[{ required: true, message: '请填写' }]" @click="chooseDate()" />
				<van-field v-model="form.supplier" name="供应商名" label="供应商名" colon class="bor" label-width="5em"
					:rules="[{ required: true, message: '请填写' }]" @click="choosePic('supplier',0)" readonly />
				<van-field v-model="form.fabricName" name="面料名称" label="面料名称" colon class="bor"
					:rules="[{ required: true, message: '请填写' }]" @click="selectChoose" label-width="5em" readonly />
				<view class="content">
					<template v-for="(item,index) in form.dict" :key="index">
						<van-field v-model="item.level" name="白胚等级" label="白胚等级" colon class="bor"
							:rules="[{ required: true, message: '请填写' }]" @click="choosePic('level',index)"
							label-width="5em" readonly>
							<template #button>
								<van-icon name="add" color="red" size="25" @click.stop="form.dict.push({stupid1:false,infos:[]})"
									v-if="index===0" />
								<van-icon name="clear" color="red" size="25" @click.stop="form.dict.splice(index,1)"
									v-else />
							</template>
						</van-field>
						<van-field name="呆货" label="呆货" colon label-width="5em" readonly>
							<template #input>
								<van-switch v-model="item.stupid1" />
							</template>
						</van-field>
						<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="(itemSecond,indexSecond) in item.infos" :key="indexSecond">
							<view class="grid-item">{{itemSecond.barcode}}</view>
							<view class="grid-item">{{itemSecond.len}}</view>
							<view class="grid-item">{{itemSecond.comment}}</view>
							<view class="grid-item" style="color:red" @click="item.infos.splice(indexSecond,1)">删除
							</view>
						</view>
						<view class="grid-container">
							<view class="grid-item">
								<van-button type="primary" @click="scanCode(index)">扫一扫</van-button>
								<cshaptx4869-scancode v-if="h5ScanCode" @success="handleSuccess" @fail="handleFail"
									@close="handleClose"></cshaptx4869-scancode>
							</view>
							<view class="grid-item"></view>
							<view class="grid-item"></view>
							<view class="grid-item"></view>
						</view>
					</template>
				</view>
			</van-cell-group>
			<view style="margin: 16px;">
				<van-button round block type="primary" native-type="submit">
					提交
				</van-button>
			</view>
		</van-form>
		<view class="floot">
			<view style="display: flex;align-items: center;justify-content: space-around;">
				<p>总匹数：{{totalMeter[1]}} 匹</p>
				<p>总米数：{{totalMeter[0]}} 米</p>
			</view>
		</view>
	</view>

	<van-dialog v-model:show="showDialog">
		<view>
			<van-cell-group inset>
				<van-field v-model="barcode" name="面料编号" label="面料编号" colon class="line" readonly
					label-width="5em" />
				<van-field v-model="meter" name="面料米数" label="面料米数" colon class="line" type="number"
					label-width="5em" />
				<van-field v-model="comment" name="备注" label="备注" colon class="line" label-width="5em" />
			</van-cell-group>
			<van-checkbox v-model="checked" style="margin-left:5.5em;">暂存</van-checkbox>
		</view>
		<template #footer>
			<view class="footer-button">
				<van-button plain size="small" native-type="button" style="width: 25vw;"
					@click="showDialog=false,meter='',checked=false">
					取消
				</van-button>
				<van-button size="small" type="success" native-type="submit" style="width: 25vw;"
					@click="confirmSecond">
					确认
				</van-button>
			</view>
		</template>
	</van-dialog>

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

	<!--选择框-->
	<van-popup v-model:show="showPicker" round position="bottom" @open="handleOpen">
		<view class="ck-box">
			<van-picker show-toolbar :columns="popuList" @confirm="pickerConfirm" @cancel="showPickerCancel"
				v-model="selectValue" ref="pickerRef" />
			<view class="ck">
				<view class="ck-a">
					<van-search v-model="searchVal" label="搜索：" background="#ffffff" @input="searchPop()"
						:clearable="false" />
				</view>
			</view>
		</view>
	</van-popup>

	<!--    面料选择框-->
	<van-popup v-model:show="showPickerList" position="bottom" @open="mlmcOpen">
		<view class="select-model">
			<van-picker :columns="pickerContainerList" @cancel="pickerCancel" v-model="selectedValue"
				@confirm="onConfirm" />
			<view>
				<view class="top-select">
					<view class="confirm-select">
						<p>请选择品种</p>
					</view>
					<view class="search-box">
						<view>
							<van-search placeholder="请输入品种名字" v-model="searchValue" label="面料搜索：" background="#ffffff"
								@input="searchTo()" :clearable="false" />
						</view>
						<view class="flex-btn">
							<button class="search-btn" @click="upSearch()">↑</button>
							<button class="search-btn" @click="downSearch()">↓</button>
						</view>
					</view>
				</view>
			</view>
		</view>
	</van-popup>
</template>

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

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

		.content {
			flex: 1;

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

				.grid-item {
					border: 1px solid #f2f2f2;
					text-align: center;
					padding: 8rpx 0;

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

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

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

	::v-deep .van-button--normal {
		padding: 5px 8px;
		height: 30px;
	}

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

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

	.ck-box {
		position: relative;

		.ck {
			position: absolute;
			top: 80rpx;
			left: 0;
			right: 0;
			z-index: 999;
		}

		.ck-a {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	/*面料选择搜索框*/
	.select-model {
		position: relative;
	}

	.confirm-select {
		width: 100%;
	}

	.confirm-select>p {
		text-align: center;
	}

	.confirm-select>button {
		border: none;
		background-color: #ffffff;
		color: #388aed;
		margin: 10px 30px 0 0;
	}

	.top-select {
		position: absolute;
		top: 30px;
		left: 0;
		right: 0;
		margin: auto;
		z-index: 999;
	}

	::v-deep .select-model .van-picker__toolbar {
		height: 66px;
		align-items: flex-start;
		/*justify-content: flex-end;*/
	}

	::v-deep .select-model .van-picker__cancel,
	.select-model .van-picker__confirm {
		height: 30px;
		padding: 10px 16px 0;
	}

	::v-deep .select-model .van-picker__confirm {
		height: 30px;
		padding: 10px 16px 0;
	}

	.search-btn {
		padding: 1px 8px;
		border: none;
		background-color: #388aed;
		color: #ffffff;
		margin-left: 5px;
		height: 30px;
		line-height: 25px;
	}

	.search-box {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		padding-top: 15px;
		padding-bottom: 5px;
		position: relative;
		background-color: #fff;
	}

	.van-search {
		background-color: #f7f7f8;
	}

	.ml-search-jump {
		padding: 3px 10px;
		background-color: #388aed;
		color: #ffffff;
		border: none;
		margin-left: 10px;
	}

	.flex-btn {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
	}
</style>