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

	const form = ref({} as any)
	const show = ref(false)
	const list = ref([] as any[])
	const dataType = ref('')
	const showDialog = ref(false)
	const listItem = ref({} as any)
	const manualDelivery = ref(false)
	const gysList = ref([])
	const djList = ref([])
	const total = ref(0)
	const currentPage = ref(1)
	const finished = ref(false)
	const loading = ref(false);

	onMounted(() => {
		init()
		getAction('/suppliers',{page:1,size:100}).then((res:any)=>{
			if(res.code===200){
				gysList.value=res.data.record
			}
		})
		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 onLoad = () => {
		if (list.value.length < total.value) {
			currentPage.value++
			init()
		} else {
			finished.value = true
		}
	};
	
	watch(form.value, () => {
		if (timer.value) {
			clearTimeout(timer.value)
		}
		timer.value = setTimeout(() => {
			list.value=[]
			currentPage.value = 1
			init()
		}, 100)
	})

const msps = ref({})

	const init = () => {
		let a = {}
		for (let i in form.value) {
			if (form.value[i]) {
				a[i] = form.value[i]
			}
		}
		let location = form.value.shelve+'-'+form.value.column+'-'+form.value.row
		let param = {
			page: currentPage.value,
			size: 30,
			location:form.value.shelve?location:null,
			...a
		}
		getAction('/rawFabric/search', param).then((res : any) => {
			if (res.code == 200) {
				res.data.page.record.forEach((l : any) => {
					list.value.push(l)
				})
				msps.value = res.data
				total.value = res.data.page.total
				loading.value = false
				finished.value = false
			}
		})
	}

	//查看详情
	const toDetile = (item : any) => {
		showDialog.value = true
		listItem.value = item
	}

	const onClickLeft = () => {
		manualDelivery.value = true
	}
	const onClickRight = () => {
		uni.navigateTo({
			url:'/pages/whiteEmbryo/warehouse-in-out'
		})
	}
	const onClickLeft1 = () =>{
		history.back()
	}
	const chooseDate = (val : any) => {
		show.value = true
		dataType.value = val
	}

	const confirmSecond = () => {
		let data={
			id:listItem.value.id,
			supplier:listItem.value.supplier,
			len: listItem.value.len,
			category:listItem.value.category,
			level:listItem.value.level,
		}
		putAction('/rawFabric', data).then((res : any) => {
			if (res.code === 200) {
				showDialog.value = false
				showToast('修改成功！')
				currentPage.value = 1
				list.value=[]
				init()
			}
		})
	}

	const onConfirmDate = (val : any) => {
		form.value[dataType.value] = formatDate(val)
		show.value = false
	}

	const pickerList = ref([])//面料数据
	const pickerContainerList = ref([])
	const showPickerList = ref(false)
	const searchValue = ref('')//查询的值
	const searchIndex = ref(0)//查询到的数组
	const mlList = ref([])
	//选择面料
	const selectChoose = (type:any) => {
		showPickerList.value = true
		dataType.value=type
	}
	//面料开启
	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) => {
		if(dataType.value=='form'){
			form.value.category = val.selectedValues[2] + '/' + val.selectedValues[0] + val.selectedValues[1]
		}else if(dataType.value=='listItem'){
			listItem.value.category = val.selectedValues[2] + '/' + val.selectedValues[0] + val.selectedValues[1]
		}
		pickerCancel()
	}
	const showPicker = ref(false)
	const popuList = ref([] as any[])
	const searchVal = ref()
	const selectValue = ref()
	//选择框事件
	const choosePic = (type:any) => {
		showPicker.value = true
		dataType.value=type
		searchVal.value=''
	}
	//选择框确认
	const pickerConfirm = (val : any) => {
		if(dataType.value==='stupid'){
			form.value.stupid = val.selectedValues[0]
		}else{
			listItem.value[dataType.value] = val.selectedValues[0]
		}
		showPickerCancel()
	}
	//取消
	const showPickerCancel = () => {
		showPicker.value = false
	}
	//弹窗开启事件
	const handleOpen = () =>{
		if(dataType.value==='supplier'){
			popuList.value=gysList.value.map(l=>({text:l.name,value:l.name}))
		}else if(dataType.value==='level'){
			popuList.value=djList.value.map(l=>({text:l.level,value:l.level}))
		}else if(dataType.value==='czyy'){
			popuList.value=[{ text: '配货进厂', value: '配货进厂' }, { text: '做本白', value: '做本白' }]
		}else if(dataType.value==='stupid'){
			popuList.value=[{ text: '是', value: '是' }, { text: '否', value: '否' }]
		}
	}
	
	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 h5ScanCode = ref(false);
	function scanCode() {
		// #ifdef H5
		manualDelivery.value = false
		h5ScanCode.value = true;
		// #endif
		// #ifndef H5
		uni.scanCode({
			success: (res : any) => {
				uni.showToast({
					icon: "none",
					title: res.result,
				});
			},
			faile: (err : any) => {
				console.log("err", err);
			},
		});
		// #endif
	}
	function handleSuccess(res : any) {
		manualDelivery.value = true
		h5ScanCode.value = false;
		if(res.length!=9) return showToast('请扫描正确的面料码！')
		listItem.value.mlbh = res
	}
	function handleFail(err : any) {
		uni.showModal({
			title: err.errName,
			content: err.errMsg,
			complete: () => {
				manualDelivery.value = true
				h5ScanCode.value = false;
			},
		});
	}
	function handleClose() {
		manualDelivery.value = true
		h5ScanCode.value = false;
	}
	//出库提交
	const confirmThirt = () => {
		if(!listItem.value.mlbh||!listItem.value.czms||!listItem.value.czyy) return showToast('请填写完整信息！')
		let param={
			barcode:listItem.value.mlbh,
			len:listItem.value.czms,
			reason:listItem.value.czyy,
		}
		postAction('/rawFabric/out',param).then((res:any)=>{
			if(res.code===200){
				manualDelivery.value = false
				showToast('提交成功！')
				list.value=[]
				currentPage.value = 1
				init()
			}
		})
	}
</script>

<template>
	<view class="flex">
		<van-nav-bar title="白胚列表" left-text="返回" left-arrow right-text="出入库记录" @click-left="onClickLeft1"
			@click-right="onClickRight" />
		<van-cell-group style="display: flex;">
			<van-field v-model="form.startDate" name="开始时间" label="开始时间" colon class="bor" label-width="5em" readonly
				@click="chooseDate('startDate')" :rules="[{ required: true, message: '请填写' }]" />
			<van-field v-model="form.endDate" name="截止时间" label="截止时间" colon class="bor" label-width="5em" readonly
				@click="chooseDate('endDate')" />
		</van-cell-group>
		<van-cell-group style="display: flex;">
			<van-field v-model="form.category" name="面料名称" label="面料名称" colon class="bor" label-width="5em" readonly
				@click="selectChoose('form')" />
			<van-field v-model="form.barcode" name="面料编号" label="面料编号" colon class="bor-a" label-width="5em" />
		</van-cell-group>
		<van-cell-group style="display: flex;">
			<van-field v-model="form.len" name="面料米数" label="面料米数" colon class="bor-a" label-width="5em" type="number"/>
			<van-field v-model="form.stupid" name="是否呆货" label="是否呆货" colon class="bor" label-width="5em" readonly @click="choosePic('stupid')"/>
		</van-cell-group>
		<van-cell-group style="display: flex;">
			<van-field name="面料位置" label="面料位置" colon label-width="5em">
				<template #input>
					<van-field v-model="form.shelve" class="bor-a" type="number"/>—
					<van-field v-model="form.column" class="bor-a" type="number"/>—
					<van-field v-model="form.row" class="bor-a" type="number"/>
				</template>
			</van-field>
		</van-cell-group>
		<view style="text-align: end;margin: 10rpx;">
			<van-button type="primary" @click="onClickLeft">扫码出库</van-button>
		</view>

		<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="content">
			<van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
				<view class="grid-container" :style="{color:item.stupid=='是'?'red':'#000'}" v-for="(item,index) in list" :key="index" @click="toDetile(item)">
					<view class="grid-item">{{item.category}}</view>
					<view class="grid-item">{{item.barcode}}</view>
					<view class="grid-item">{{item.len}}</view>
					<view class="grid-item">{{item.location}}</view>
				</view>
			</van-list>
		</view>
		<view class="floot">
			<view style="display: flex;align-items: center;justify-content: space-around;">
				<p>总匹数：{{msps.count}} 匹</p>
				<p>总米数：{{msps.len}} 米</p>
			</view>
		</view>
	</view>
	<cshaptx4869-scancode v-if="h5ScanCode" @success="handleSuccess" @fail="handleFail"
		@close="handleClose"></cshaptx4869-scancode>

	<van-dialog v-model:show="showDialog">
		<div>
			<van-cell-group inset>
				<van-field v-model="listItem.checkDate" name="质检时间" label="质检时间" colon label-width="5em" readonly />
				<van-field v-model="listItem.checkUser" name="质检人员" label="质检人员" colon label-width="5em" readonly />
				<van-field v-model="listItem.supplier" name="供应商名" label="供应商名" colon label-width="5em" readonly class="bor" @click="choosePic('supplier')"/>
				<van-field v-model="listItem.category" name="面料名称" label="面料名称" colon label-width="5em" readonly class="bor" @click="selectChoose('listItem')"/>
				<van-field v-model="listItem.barcode" name="面料编号" label="面料编号" colon label-width="5em" readonly />
				<van-field v-model="listItem.len" name="面料米数" label="面料米数" colon label-width="5em" type="number"/>
				<van-field v-model="listItem.inboundUser" name="入库人" label="入库人" colon label-width="5em" readonly />
				<van-field v-model="listItem.level" name="白胚等级" label="白胚等级" colon label-width="5em" readonly class="bor" @click="choosePic('level')"/>
				<van-field v-model="listItem.location" name="面料位置" label="面料位置" colon label-width="5em" readonly />
				<van-field v-model="listItem.inboundDate" name="入库时间" label="入库时间" colon label-width="5em" readonly />
			</van-cell-group>
		</div>
		<template #footer>
			<div class="footer-button">
				<van-button plain size="small" native-type="button" style="width: 25vw;"
					@click="showDialog=false">
					取消
				</van-button>
				<van-button size="small" type="success" native-type="submit" style="width: 25vw;" @click="confirmSecond">
					确认
				</van-button>
			</div>
		</template>
	</van-dialog>

	<van-dialog v-model:show="manualDelivery" title="扫码出库">
		<div>
			<van-cell-group inset>
				<van-field v-model="listItem.czyy" name="操作原因" label="操作原因" colon label-width="5em" readonly class="bor"
					@click="choosePic('czyy')" />
				<van-field v-model="listItem.mlbh" name="面料编号" label="面料编号" colon label-width="5em" readonly>
					<template #button>
						<van-button type="primary" @click="scanCode">扫一扫</van-button>
					</template>
				</van-field>
				<van-field v-model="listItem.czms" name="操作米数" label="操作米数" colon label-width="5em" class="bor-a"
					type="number" />
			</van-cell-group>
		</div>
		<template #footer>
			<div class="footer-button">
				<van-button plain size="small" native-type="button" style="width: 25vw;"
					@click="manualDelivery=false,listItem={}">
					取消
				</van-button>
				<van-button size="small" type="success" native-type="submit" style="width: 25vw;" @click="confirmThirt">
					确认
				</van-button>
			</div>
		</template>
	</van-dialog>


	<!--    面料选择框-->
	<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>

	<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" v-if="dataType!='stupid'">
				<view class="ck-a">
				  <van-search v-model="searchVal" label="搜索：" background="#ffffff" @input="searchPop()" :clearable="false"/>
				</view>
			</view>
		</view>
	</van-popup>
</template>

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

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

		.grid-container {
			display: grid;
			grid-template-columns: 2fr 1.6fr 1.3fr 1.5fr;
			padding: 0 15rpx;

			.grid-item {
				border: 1rpx solid #f2f2f2;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 5rpx;
			}
		}

		.content {
			flex: 1;
			overflow-y: scroll;
		}
	}

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

	::v-deep .van-field {
		font-size: 16px;
	}
	
	.floot{
		padding: 20rpx;
	}
	
	.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;
		}
	}
	

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

		::v-deep .van-field__label {
			margin: 0;
		}
	}

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

		::v-deep .van-field__label {
			margin: 0;
		}
	}

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

	::v-deep .van-field__control {
		text-align: center;
	}
	
	.footer-button {
		margin: 20px;
		display: flex;
		justify-content: space-around;
	}

	/*面料选择搜索框*/
	.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;
	}

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