<template>
	<BasicContainer :option="option" class="pageContainer">
		<template #head>
			<!-- 顶部搜索栏 -->
			<view class="header-search">
				<view class="Picker">
					<picker @change="bindPickerChange" :value="searchForm.chooseIndex"
						:range="searchForm.searchTypeList.map(val => val.label)">
						<view class="uni-input">
							{{searchForm.searchTypeList.map(val => val.label)[searchForm.chooseIndex]}}

						</view>
					</picker>
					<u-icon name="arrow-down" color="#d3832a" size="28"></u-icon>
				</view>

				<view class="search">
					<input class="searchInput" v-model="searchText" type="text">

					<template v-if="searchText">
						<view class="clearIcon">
							<u-icon @click="searchText = ''" name="close-circle" color="#333" size="35"></u-icon>
						</view>
					</template>

					<view v-if="isShowSearchList" class="searchList" @touchmove.stop>
						<template v-if="searchLoading">
							<u-loading-icon size="60" mode="semicircle" timing-function="linear"
								color="#d3832a"></u-loading-icon>
						</template>

						<template v-else-if="!searchLoading">
							<block v-for="item in searchList" :key='item.productCode'>
								<view class="searchList_item" @click="handleChooseInventory(item)">
									{{searchForm.chooseIndex === 0 ? item.name : item.productCode}}
								</view>
							</block>
						</template>
					</view>
				</view>

				<view class="searchType" @click="handleSearch">
					搜索
				</view>
			</view>

			<template v-if="pageInfo.productCode">
				<!-- 数据详情 -->
				<view class="dataInfo">
					<view class="dataInfo__item">
						<text class="label ">物料编码:</text>
						<text>
							{{pageInfo.productCode|| '暂无数据'}}
						</text>
					</view>

					<view class="dataInfo__item">
						<text class="label ">物料名称:</text>
						<text>
							{{pageInfo.name|| '暂无数据'}}
						</text>
					</view>

					<view class="dataInfo__item">
						<text class="label ">单位:</text>
						<text>
							{{pageInfo.logpmUnit || '暂无数据'}}
						</text>
					</view>

					<view class="dataInfo__item">
						<text class="label ">规格:</text>
						<text>
							{{pageInfo.packingSpecification || '暂无数据'}}
						</text>
					</view>

					<view class="dataInfo__item">
						<text class="label ">长度:</text>
						<text>
							{{pageInfo.extent|| '暂无数据'}}
						</text>
					</view>

					<view class="dataInfo__item">
						<text class="label ">宽度:</text>
						<text>
							{{pageInfo.breadth|| '暂无数据'}}
						</text>
					</view>

					<view class="dataInfo__item">
						<text class="label ">高度:</text>
						<text>
							{{pageInfo.altitude|| '暂无数据'}}
						</text>
					</view>
				</view>
			</template>

			<template v-else>
				<view style="text-align: center; position: fixed; top: 50%; left: 50%; transform: translateX(-50%);">
					暂无数据
				</view>
			</template>
		</template>

		<template #body>
			<template v-if="pageInfo.productCode">
				<view class="orderInfo" :style="{height:tableHeight}" @touchmove.stop>
					<!-- 循环显示图片 -->
					<block v-for="(value,index) in imgList">
						<view class="imgList">
							<image class="imageList_item" :src="value" @click="handleShowImage(value)"></image>
							<image class="imageList_item removeImg" @click="remove(index)"
								src="/compoment/cus-selects-fan/cha.png">
							</image>
						</view>
					</block>
					<view @click="updateimg" class="imgList">
						<view class="imageList_item flex-c-c">
							<u-icon name="plus-circle-fill" color="#d3832a" size="60"></u-icon>
						</view>
					</view>

				</view>
			</template>

			<!-- 微信小程序适配 -- 扫码按钮 -->
			<view class="scanButton">
				/* #ifdef MP-WEIXIN */
				<view @click="handleScan">扫码</view>
				/* #endif */

				<view @click="handleSubmit">
					提交
				</view>
			</view>

			<!-- 预览图片 -->
			<view class="previewPicture-container" v-if="showPreviewPicture" @click.stop="handleShowImage()">
				<img :src="previewPictureUrl" class="previewPicture" alt="">
			</view>
		</template>
	</BasicContainer>
	<tiplist ref="tiplists"></tiplist>
	<PopUp ref="MaterialReplenishment">

	</PopUp>
	<!-- #ifdef APP -->
	<saomiao2 :ishidestop="scanState !== 0"></saomiao2>
	<!-- #endif -->

</template>

<script lang="ts" setup>
	import { ref, reactive, shallowRef, watch, nextTick, computed } from 'vue';
	import {
		onShow,
		onHide,
		onLoad,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import utils from '@/utils/utils.js';
	import functions from '@/utils/functions.js';
	import {
		postMaterielList,
		postMaterielUpdateMateriel
	} from '@/api/user.js'
	import useSystemSettingsStore from '@/store/useSystemSettingsStore';
	import { storeToRefs } from 'pinia';
	const { scanState } = storeToRefs(useSystemSettingsStore())

	const option = reactive({
		title: '物料维护',
		haveData: true,
		isEnd: true,
		async pullDownRefreshInitPage() {
			pageInfo.value = {}
			scancode.value = ''
			searchText.value = ''
			isShowSearchList.value = false
			imgList.value = []

			await nextTick()
			tableHeight.value = await utils.getViewDistanceFormTop('.orderInfo')
			return null
		},
	})

	// 查询显示的列表数据
	const searchList = ref([])

	/** 搜索框的值 */
	const searchText = ref('')

	// 搜索loading
	const searchLoading = ref(false)

	// 是否显示下拉列表
	const isShowSearchList = ref(false)

	// 扫码码值
	const scancode = ref<string>('')

	/** 页面信息 */
	const pageInfo = ref({})

	/** 复选框被选中的值 */
	const seletionList = ref([])

	// 顶部搜素表单
	const searchForm = reactive({
		condition: '',
		searchTypeList: [
			{
				label: '物料名称',
				type: 1
			},
			{
				label: '物料编码',
				type: 2
			},
		],
		chooseIndex: 1,
	})

	// 表格高度
	const tableHeight = ref('40vh')

	/** 图片列表 */
	const imgList = ref([])

	/** 预览图片的地址 */
	const previewPictureUrl = ref('')

	/** 是否显示预览图片 */
	const showPreviewPicture = ref(false)

	// 组件实例
	const tiplists = ref(null)
	/** 物料补录 */
	const MaterialReplenishment = ref()


	onLoad(() => {
		// #ifdef APP
		utils.ttsspke('物料维护, 请扫描或输入物料编码')
		// #endif
	})

	// 开启监听扫描
	onShow(async () => {
		// #ifdef APP
		uni.$off('scancodedate')
		uni.$on('scancodedate', function (code) {
			if (code) {
				scancode.value = code
				searchText.value = code
				scandata()
			}
		})
		// #endif

		// await nextTick()
		// tableHeight.value = await utils.getViewDistanceFormTop('.orderInfo')
	})

	/** 搜索物料编码 || 物料名称 */
	const handleChooseInventory = (item) => {
		pageInfo.value = item

		imgList.value = pageInfo.value.picture ? pageInfo.value.picture.split(',') : []

		// 关闭下拉
		isShowSearchList.value = false
	}

	/** 扫描后执行的回调 */
	async function scandata() {
		try {
			pageInfo.value = {}
			imgList.value = []

			searchLoading.value = true
			isShowSearchList.value = true

			console.log('searchForm :>> ', searchForm);
			const submitData = {
				type: searchForm.searchTypeList[searchForm.chooseIndex].type,
				materielStr: scancode.value
			}

			const res = await postMaterielList(submitData)

			const { code, data } = res
			if (code !== 200) return

			searchList.value = data
			if (data.length > 2) return

			if (data.length === 0) uni.showToast({
				title: '暂无数据',
				icon: 'none'
			})
			else handleChooseInventory(data[0])
			isShowSearchList.value = false
		} catch (err) {
			console.log('err :>> ', err);
			//TODO handle the exception
		} finally {
			searchLoading.value = false
		}
	}

	/** 搜索 */
	const handleSearch = () => {
		if (searchText.value === '') return uni.showToast({
			title: `请输入${searchForm.searchTypeList[searchForm.chooseIndex].label}`,
			icon: 'none'
		})

		scancode.value = searchText.value
		scandata()
	}

	const selectionChange = (list) => {
		seletionList.value = list.detail.index
	}

	/** 小程序扫码 */
	function handleScan() {
		console.log(123123)
		// 微信小程序适配
		uni.scanCode({
			success(res) {
				console.log('res :>> ', res);
				console.log('res.result :>> ', res.result);
				searchText.value = res.result
				scancode.value = res.result
				scandata()
			}
		})
	}

	/**
	 * 搜索条件改变
	 */
	function bindPickerChange(e) {
		console.log('picker发送选择改变，携带值为', e.detail.value)
		// 传入索引, 修改仓库中存储的状态
		searchForm.chooseIndex = e.detail.value
	}

	/** 是否预览图片 */
	function handleShowImage(imgUrl = '/static/changku.png') {
		previewPictureUrl.value = imgUrl
		showPreviewPicture.value = !showPreviewPicture.value
	}

	/** 上传图片 */
	function updateimg() {
		// 是否为提交修改, 记录修改的类型
		uni.chooseImage({
			count: 20,
			success: async (chooseImageRes) => {
				console.log('chooseImageRes >>>>>>>>', chooseImageRes)
				const tempFilePaths = chooseImageRes.tempFilePaths as any;
				tempFilePaths.forEach(async (item) => {
					let url = await functions.upfile(item)
					console.log('url :>> ', url);
					imgList.value.push(url.link)
				})
			}
		});
	}

	/** 移除图片 */
	const remove = (index : number) => {
		imgList.value.splice(index, 1)
	}

	/** 提交 */
	const handleSubmit = async () => {
		if (Object.keys(pageInfo.value).length === 0) return uni.showToast({
			title: '请先搜索物料',
			icon: 'none'
		})

		if (imgList.value.length === 0) return uni.showToast({
			title: '请上传图片',
			icon: 'none'
		})

		const submitData = {
			...pageInfo.value,
			picture: imgList.value.join(',')
		}

		const res = await postMaterielUpdateMateriel(submitData)

		const { code } = res
		if (code !== 200) return

		uni.showToast({
			title: '更新成功',
			icon: 'none'
		})
	}
</script>

<style lang="scss" scoped>
	:deep(.pageContainer) {
		font-size: 0.9rem;
	}

	.w100 {
		width: 100%;
	}

	// 顶部搜索栏
	.header-search {
		height: 60upx;
		padding: 0 0 20upx;
		// border-bottom: 2upx solid #aaa;
		display: flex;
		justify-content: space-between;
		// align-items: center;
		margin-top: 10upx;
	}

	.search {
		position: relative;
		flex: 1;

		.clearIcon {
			display: flex;
			align-items: center;
			justify-content: center;
			position: absolute;
			bottom: 0;
			right: 20upx;
			z-index: 99;
			height: 100%;
			width: 80upx;
		}

		// 查询结果的列表
		.searchResultList {
			position: absolute;
			top: 120%;
			width: 100%;
			background: #fff;
			z-index: 80;
			text-align: center;
			line-height: 60upx;
			max-height: 300upx;
			overflow-y: scroll;
		}
	}

	.Picker {
		width: 150upx;
		justify-content: center;
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 10upx;
	}

	// 搜索输入框
	.searchInput {
		background: #fff;
		// width: 500upx;
		flex: 1;
		height: 100%;
		padding-left: 20upx;
		border: 2upx solid var(--subjectColor);
		border-radius: 30upx;
		margin: 0 20upx;
	}

	// 搜索下拉框
	.searchList {
		display: flex;
		align-items: center;
		justify-content: center;
		min-height: 200upx;
		max-height: 600upx;
		overflow-y: scroll;
		position: absolute;
		z-index: 20;
		left: 0;
		top: 120%;
		width: 100%;
		background: #fff;
		border-radius: 5upx;
		box-shadow: 0 0 20upx #acc;
		flex-wrap: wrap;

		.searchList_item {
			width: 100%;
			flex: none;
			padding: 10upx;
			border-bottom: 1upx dashed #ccc;
			box-sizing: border-box;
			word-break: break-all;
		}
	}

	// 搜索类型
	.searchType {
		height: 100%;
		display: flex;
		flex: none;
		align-items: center;
		padding: 0 40upx;
		background: #fff;
		border: 2upx solid var(--subjectColor);
		border-radius: 10upx;
		color: var(--subjectColor);
	}

	// 数据详情
	.dataInfo {
		display: flex;
		flex-wrap: wrap;
		// border-bottom: 2upx solid #aaa;
		background: #fff;
		padding: 10upx;
	}

	.dataInfo__item {
		flex: none;
		min-width: 50%;
		max-width: 100%;
		line-height: 60upx;
		display: inline-flex;
		padding: 10upx 0;

		.label {
			display: inline-block;
			width: 150upx;
			text-align: left;
			padding: 0 10rpx;
			box-sizing: border-box;
			flex: none;
		}

		>text {
			line-height: 1rem;
			word-break: break-all;
		}
	}

	// 订单列表信息
	.orderInfo {
		background: #fff;
		margin-top: 30upx;
		padding: 10upx;
		display: flex;
		flex-wrap: wrap;
		align-content: flex-start;
	}

	.imgList {
		position: relative;
		height: fit-content;

		.removeImg {
			position: absolute;
			width: 30upx;
			height: 30upx;
			background-color: transparent;
			right: 0;
			top: 0;
		}
	}

	.imageList_item {
		width: 150upx;
		height: 150upx;
		margin-right: 15upx;
		background-color: #eee;
		border-radius: 10upx;

		&.addImg {
			width: 60upx;

		}
	}

	// 扫码按钮
	.scanButton {
		position: fixed;
		bottom: 20upx;
		left: 50%;
		transform: translateX(-50%);
		display: flex;

		>view {
			width: fit-content;
			flex: none;
			padding: 20upx 60upx;
			margin: 0 20upx;
			border-radius: 10upx;
			background: var(--subjectColor);
			color: #fff;
		}
	}

	// 预览图片
	.previewPicture-container {
		z-index: 99999;
		width: 100%;
		height: 100%;
		background: #65768499;
		position: fixed;
		top: 0;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: center;

		.previewPicture {
			width: 100%;
		}
	}

	.flex-c-c {
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>