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

	const showPop = ref(false)
	const list = ref([] as any[])
	const form = ref({ recommend: [], shelve: '', column: '', row: '' } as any)
	const showPicker = ref(false)
	const popuList = ref([] as any[])
	const showPicker1 = ref(false)
	const warehouseList = ref([])

	const pickerList = ref([])//面料数据
	const pickerContainerList = ref([])
	const searchValue = ref('')//查询的值
	const searchIndex = ref(0)//查询到的数组
	const mlList = ref([])

	onMounted(() => {
		getAction('/warehouse').then((res : any) => {
			if (res.code === 200) {
				warehouseList.value=[]
				res.data.forEach((l:any)=>{
					if(l.active){
						warehouseList.value.push(l)
					}
				})
			}
		})
		getAction('/fabric/info/all').then((res : any) => {
			if (res.code === 200) {
				res.data.forEach((l : any) => {
					let itemMl = mlList.value.find((m : any) => m.text === l.commodity)
					if (itemMl) {
						let itemMm = itemMl.children.find((m : any) => 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 }] }]
						})
					}
				})
			}
		})
		init()
	})
	//动态获取数据
	const onLoad = () => {
		if (list.value.length < total.value) {
			currentPage.value++
			init()
		} else {
			finished.value = true
		}
	};
	const init = () => {
		getAction('/shelves', { page: currentPage.value, size: 10, }).then((res : any) => {
			if (res.code === 200) {
				res.data.record.forEach((l:any)=>{
					list.value.push(l)
				})
				total.value = res.data.total
				loading.value = false;
				finished.value = false
			}
		})
	}

	const onClickLeft = () => {
		history.back()
	}
	const onClickRight = () => {
		form.value = { recommend: [], shelve: '', column: '', row: '' }
		showPop.value = true
	}
	const edit = (item : any) => {
		form.value = JSON.parse(JSON.stringify(item))
		form.value.active=item.active?'true':'false'
		showPop.value = true
	}
	const onSubmit = () => {
		if (form.value.id) {
			putAction('/shelves', form.value).then((res : any) => {
				if (res.code === 200) {
					showToast('编辑成功！')
					showPop.value = false
					list.value=[]
					currentPage.value=1
					init()
				}
			})
		} else {
			postAction('/shelves', form.value).then((res : any) => {
				if (res.code === 200) {
					showToast('提交成功！')
					showPop.value = false
					list.value=[]
					currentPage.value=1
					init()
				}
			})
		}
	}

	const del = (item : any) => {
		showConfirmDialog({
			title: '提示',
			message: '是否确认删除？',
		}).then(() => {
			let url = '/shelves/' + item.id
			deleteAction(url).then((res : any) => {
				if (res.code === 200) {
					list.value=[]
					currentPage.value=1
					init()
					showToast('删除成功！')
				}
			})
		})
			.catch(() => {
				// on cancel
			});
	}



	//选择框事件
	const choosePic = (type : any, index : any) => {
		showPicker.value = true
	}
	//选择框确认
	const pickerConfirm = (val : any) => {
		form.value.location = val.selectedValues[0]
		showPickerCancel()
	}
	//取消
	const showPickerCancel = () => {
		showPicker.value = false
	}
	//弹窗开启事件
	const handleOpen = () => {
		popuList.value = warehouseList.value.map((l : any) => ({ text: l.name, value: l.name }))
	}


	//选择框组事件
	const handleOpen1 = () => {
		pickerList.value = mlList.value
		pickerContainerList.value = pickerList.value
		searchValue.value = ''
		popuList.value = colorsArray
	}
	const selectChoose = () => {
		showPicker1.value = true
	}
	const onConfirm = (val : any) => {
		let ml = val[0].selectedValues[2] + '/' + val[0].selectedValues[0] + val[0].selectedValues[1]
		let color = val[1].selectedValues[0]
		form.value.recommend.push({ fabricName: ml, color: color })
		showPicker1.value = false
	}
	const onCancel = () => {
		showPicker1.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 total = ref(0)
	const currentPage = ref(1)
	const finished = ref(false)
	const loading = ref(false);

	const kwh = computed(() => {
		if (barcode.value) {
			let a = barcode.value.split('-')
			form.value.shelve = a[0]
			form.value.column = a[1]
			form.value.row = a[2]
		}
		if(form.value.id){
			return form.value.shelve+'-'+form.value.column+'-'+form.value.row
		}else{
			return barcode.value
		}
	})

	const h5ScanCode = ref(false);
	function scanCode() {
		showPop.value = false
		// #ifdef H5
		h5ScanCode.value = true;
		// #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
		showPop.value = true
	}
	function handleFail(err : any) {
		uni.showModal({
			title: err.errName,
			content: err.errMsg,
			complete: () => {
				h5ScanCode.value = false;
			},
		});
	}

	function handleClose() {
		h5ScanCode.value = false;
	}
	
	const searchColor = ref()
	const search = () =>{
		popuList.value=[]
		if(searchColor.value){
			let reg=new RegExp(searchColor.value)
			colorsArray.forEach((l:any)=>{
				if(reg.test(l.text)){
					popuList.value.push(l)
				}
			})
		}else{
			popuList.value=colorsArray
		}
	}
</script>

<template>
	<view class="flex">
		<van-nav-bar title="库位号维护" left-text="返回" left-arrow right-text="新增" @click-left="onClickLeft"
			@click-right="onClickRight" />
		<view class="content">
			<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>
			<van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
				<view class="grid-container" v-for="(item,index) in list" :key="index">
					<view class="grid-item">{{item.shelve+'-'+item.column+'-'+item.row}}</view>
					<view class="grid-item">{{item.location}}</view>
					<view class="grid-item">{{item.active?'启用':'禁用'}}</view>
					<view class="grid-item"><span style="color: #35a5f7" @click="edit(item)">编辑</span> &nbsp;&nbsp;
						<span style="color: red" @click="del(item)">删除
						</span></view>
				</view>
			</van-list>

		</view>
	</view>

	<van-popup v-model:show="showPop" style="width: 90%" round>
		<view>
			<h3 style="text-align: center">{{form.id?'编辑':'新增'}}</h3>
			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field v-model="kwh" name="库位号" label="库位号" class="nonBom" colon readonly label-width="6em">
						<template #button>
							<van-button type="primary" @click="scanCode">扫一扫</van-button>
						</template>
					</van-field>
					<van-field v-model="form.location" name="所在仓库" label="所在仓库" colon readonly class="bor"
						@click="choosePic" label-width="6em" :rules="[{ required: true, message: '请选择' }]" />
					<van-field v-model="form.maximumPayload" name="最大存储量" label="最大存储量" colon class="bor-b"
						label-width="6em" :rules="[{ required: true, message: '请选择' }]" />
					<van-field v-model="form.name" name="放置推荐" label="放置推荐" colon class="bor" readonly label-width="6em"
						@click="selectChoose" />
					<template v-for="(item,index) in form.recommend">
						<view style="display: flex;align-items: center;justify-content: center;">
							<p style="text-align: center;">{{item.fabricName}} &nbsp;&nbsp;&nbsp;&nbsp; {{item.color}}
							</p>
							<van-icon name="add" color="red" size="28" style="margin-left: 20rpx;"
								@click.stop="form.recommend.splice(index)"/>
						</view>
					</template>
					<van-field name="状态" label="状态" colon label-width="6em"
						:rules="[{ required: true, message: '请选择' }]" class="nonBom">
						<template #input>
							<van-radio-group v-model="form.active" direction="horizontal">
								<van-radio name="true">启用</van-radio>
								<van-radio name="false">禁用</van-radio>
							</van-radio-group>
						</template>
					</van-field>
				</van-cell-group>
				<view class="a-c">
					<van-button type="danger" @click="showPop=false">取消</van-button>
					<van-button type="primary" native-type="submit">确认</van-button>
				</view>
			</van-form>
		</view>
	</van-popup>
	<cshaptx4869-scancode v-if="h5ScanCode" @success="handleSuccess" @fail="handleFail"
		@close="handleClose"></cshaptx4869-scancode>

	<!--选择框-->
	<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-popup v-model:show="showPicker1" round position="bottom" @open="handleOpen1">
		<van-picker-group title="选择" :tabs="['选择面料', '选择颜色']" @confirm="onConfirm" @cancel="onCancel">
			<!--    面料选择框-->
			<view class="select-model">
				<van-picker :columns="pickerContainerList" v-model="selectedValue" />
				<view>
					<view class="top-select">
						<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>
			<view>
				<van-picker show-toolbar :columns="popuList" />
				<view class="top-select">
					<view class="search-box">
						<van-search placeholder="请输入" v-model="searchColor" label="色号搜索：" background="#ffffff"
							:clearable="false" />
						<view class="flex-btn">
							<button class="search-btn" @click="search()">搜索</button>
						</view>
					</view>
				</view>
			</view>
		</van-picker-group>
	</van-popup>
</template>

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

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

		.content {
			flex: 1;
			padding: 0 10px;
			overflow-y: scroll;

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

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

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

			.card {
				margin: 10px 15px;
				padding: 5px;
				border: 1px solid #02a7f0;
				border-radius: 10px;
			}
		}
	}

	.a-b {
		display: flex;
		margin-bottom: 10rpx;

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

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

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

	.nonBom {
		::v-deep .van-field__control {
			border-bottom: none;
			text-align: center;
		}
	}

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

	.a-c {
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin: 15rpx;

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

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

	/*面料选择搜索框*/
	.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: 0;
		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 .van-button--normal {
		padding: 5px 8px;
		height: 30px;
	}

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